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

export const useDeleteEvent = () => {
    const {user, profileData} = useAuthContext();
    const queryClient = useQueryClient();

    return useMutation({
        mutationKey: ["deleteEvent"],
        mutationFn: async ({eventId, docId}: { eventId?: string; docId?: string }) => {
            try {
                await firestore()
                    .collection("Events")
                    .doc(eventId ?? docId)
                    .delete();
            } catch (e) {
                console.error(e);
                throw e;
            }
        },
        onMutate: async ({eventId, docId}) => {
            await queryClient.cancelQueries({
                queryKey: ["events", user?.uid]
            });

            const previousPersonalEvents = queryClient.getQueryData(["events", user?.uid, false]);
            const previousFamilyEvents = queryClient.getQueryData(["events", user?.uid, true]);

            const updateQueryData = (old: any[] | undefined) =>
                old?.filter(event => event.id !== (eventId ?? docId));

            queryClient.setQueryData(
                ["events", user?.uid, false],
                updateQueryData
            );
            queryClient.setQueryData(
                ["events", user?.uid, true],
                updateQueryData
            );

            return {previousPersonalEvents, previousFamilyEvents};
        },
        onError: (err, variables, context) => {
            queryClient.setQueryData(
                ["events", user?.uid, false],
                context?.previousPersonalEvents
            );
            queryClient.setQueryData(
                ["events", user?.uid, true],
                context?.previousFamilyEvents
            );
        },
        onSettled: () => {
            if (profileData?.familyId) {
                firestore()
                    .collection("Households")
                    .where("familyId", "==", profileData.familyId)
                    .get()
                    .then(snapshot => {
                        snapshot.docs.forEach(doc => {
                            doc.ref.update({
                                lastSyncTimestamp: firestore.FieldValue.serverTimestamp()
                            });
                        });
                    });
            }
        }
    });
};