import { useMutation } from "@tanstack/react-query";
import { createParticle, updateStreamLastChildAt } from "@/lib/firestore-particles";
import type { ParticleType, ParticlePropertiesMap } from "@/api/types";
import { particlePath, ParticlePath, toFirestoreChildrenPath, toFirestoreDocPath } from "@/lib/particle-path";

interface CreateParticleParams<T extends ParticleType = ParticleType> {
  // Path to which the new particle will be added as a child
  path: ParticlePath;
  type: T;
  properties: ParticlePropertiesMap[T];
  createdByEmail: string;
}

export function useCreateParticle() {
  return useMutation({
    mutationFn: async (params: CreateParticleParams) => {
      const collectionPath = toFirestoreChildrenPath(params.path);
      const result = await createParticle(
        collectionPath,
        params.type,
        params.properties,
        params.createdByEmail,
      );

      const streamDocPath = toFirestoreDocPath(params.path);
      await updateStreamLastChildAt(streamDocPath);
      return result;
    }
  });
}

type CreateStreamParticleParams = {
  networkId: string;
  properties: ParticlePropertiesMap["stream"];
  createdByEmail: string;
  visibleTo?: string[];
};

export function useCreateStreamParticle() {
  return useMutation({
    mutationFn: async (params: CreateStreamParticleParams) => {
      const path = particlePath(params.networkId, []);
      const networkCollectionPath = toFirestoreChildrenPath(path);
      return await createParticle(
        networkCollectionPath,
        "stream",
        params.properties,
        params.createdByEmail,
        params.visibleTo,
      );
    }
  });
}
