import { useQuery } from "@tanstack/react-query";
import firestore from "@react-native-firebase/firestore";

export const useGetHouseholdName = (familyId: string) => {
  return useQuery({
    queryKey: ["household", familyId],
    queryFn: async () => {
      try {
        const snapshot = await firestore()
            .collection("Households")
            .where("familyId", "==", familyId)
            .get();

        if (!snapshot.empty) {
          const householdData = snapshot.docs[0].data();
          console.log("Household found:", householdData);
          return householdData.name ?? null;
        }

        console.log("No household found for the given familyId.");
        return null;
      } catch (e) {
        console.error("Error fetching household name:", e);
        throw e;
      }
    },
    enabled: Boolean(familyId),
    staleTime: 5 * 60 * 1000,
  });
};