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

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

    return useMutation({
        mutationKey: ["createEvent"],
        mutationFn: async (eventData: Partial<EventData>) => {
            try {
                console.log("CALLLLL")
                await firestore()
                    .collection("Events")
                    .add({...eventData, creatorId: currentUser?.uid, familyId: profileData?.familyId})
            } catch (e) {
                console.error(e)
            }
        },
        onSuccess: () => {
            queryClients.invalidateQueries("events")
        }
    })
}

export const useCreateEventFromProvider = () => {
    const {user: currentUser} = useAuthContext()
    const queryClients = useQueryClient()

    return useMutation({
        mutationKey: ["createEventFromProvider"],
        mutationFn: async (eventData: Partial<EventData>) => {
            try {
                const snapshot = await firestore()
                    .collection("Events")
                    .where("id", "==", eventData.id)
                    .get();

                if (snapshot.empty) {
                    await firestore()
                        .collection("Events")
                        .add({...eventData, creatorId: currentUser?.uid})
                } else {
                    console.log("ENTER HERE")
                    const docId = snapshot.docs[0].id;
                    await firestore()
                        .collection("Events")
                        .doc(docId)
                        .update({...eventData, creatorId: currentUser?.uid});
                }
            } catch (e) {
                console.error(e)
            }
        },
        onSuccess: () => {
            queryClients.invalidateQueries("events")
        }
    })
}