import { useMutation, useQueryClient } from "react-query";
import firestore from "@react-native-firebase/firestore";
import { useAuthContext } from "@/contexts/AuthContext";
import {IGrocery} from "@/hooks/firebase/types/groceryData";

export const useCreateGrocery = () => {
    const { user: currentUser, profileData } = useAuthContext();
    const queryClients = useQueryClient();

    return useMutation({
        mutationKey: ["createGrocery"],
        mutationFn: async (groceryData: Partial<IGrocery>) => {
            try {
                const newDoc = firestore().collection('Groceries').doc();
                await firestore()
                    .collection("Groceries")
                    .add({...groceryData, id: newDoc.id, familyId: profileData?.familyId, creatorId: currentUser?.uid})
            } catch (e) {
                console.error(e)
            }
        },
        onSuccess: () => {
            queryClients.invalidateQueries("groceries")
        }
    })
}