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 {
                if (eventData.id) {
                    const snapshot = await firestore()
                        .collection("Events")
                        .where("id", "==", eventData.id)
                        .get();

                    if (!snapshot.empty) {
                        const docId = snapshot.docs[0].id;
                        await firestore()
                            .collection("Events")
                            .doc(docId)
                            .set({
                                ...eventData,
                                creatorId: currentUser?.uid,
                                familyId: profileData?.familyId
                            }, {merge: true});
                        return;
                    }
                }
                const newDoc = firestore().collection('Events').doc();
                await firestore()
                    .collection("Events")
                    .add({...eventData, id: newDoc.id, creatorId: currentUser?.uid, familyId: profileData?.familyId});
            } catch (e) {
                console.error(e);
            }
        },
        onSuccess: () => {
            queryClients.invalidateQueries("events")
        }
    })
}

export const useCreateEventsFromProvider = () => {
    const { user: currentUser } = useAuthContext();
    const queryClient = useQueryClient();

    return useMutation({
        mutationKey: ["createEventsFromProvider"],
        mutationFn: async (eventDataArray: Partial<EventData>[]) => {
            try {
                // Create an array of promises for each event's Firestore read/write operation
                const promises = eventDataArray.map(async (eventData) => {
                    console.log("Processing EventData: ", eventData);

                    // Check if the event already exists
                    const snapshot = await firestore()
                        .collection("Events")
                        .where("id", "==", eventData.id)
                        .get();

                    if (snapshot.empty) {
                        // Event doesn't exist, so add it
                        return firestore()
                            .collection("Events")
                            .add({ ...eventData, creatorId: currentUser?.uid });
                    } else {
                        // Event exists, update it
                        const docId = snapshot.docs[0].id;
                        return firestore()
                            .collection("Events")
                            .doc(docId)
                            .set({ ...eventData, creatorId: currentUser?.uid }, { merge: true });
                    }
                });

                // Execute all promises in parallel
                await Promise.all(promises);

            } catch (e) {
                console.error("Error creating/updating events: ", e);
            }
        },
        onSuccess: () => {
            queryClient.invalidateQueries("events");
        }
    });
};