import firestore from "@react-native-firebase/firestore";
import { useMutation, useQueryClient } from "react-query";

export const useUpdateHouseholdName = () => {
  const queryClient = useQueryClient();

  return useMutation({
    mutationKey: ["updateHouseholdName"],
    mutationFn: async ({
      familyId,
      name,
    }: {
      familyId: string;
      name: string;
    }) => {
      console.log("Mutation function called with data:", { familyId, name });

      try {
        // Reference to the Households collection
        const householdRef = firestore().collection("Households");

        // Query to check if the household exists
        const snapshot = await householdRef.where("familyId", "==", familyId).get();

        if (!snapshot.empty) {
          // If a household with the familyId exists, update the name
          const docId = snapshot.docs[0].id;
          console.log(`Household found with ID ${docId}, updating name...`);

          await householdRef.doc(docId).update({ name });

          console.log("Household name updated successfully.");
        } else {
          // If no household exists, create a new one with familyId and name
          console.log("No household found, creating a new one...");

          await householdRef.add({ familyId, name });

          console.log("New household created successfully.");
        }
      } catch (e) {
        console.error("Error updating or creating household:", e);
        throw e; // Ensure error propagates to the mutation error handling
      }
    },
    onSuccess: () => {
      queryClient.invalidateQueries("households"); // Invalidate the "households" query to refresh data
    },
  });
};
