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

export const useDeleteEvent = () => {
    const queryClient = useQueryClient();

    return useMutation({
        mutationKey: ["deleteEvent"],
        mutationFn: async ({eventId, docId}: { eventId?: string; docId?: string }) => {
            try {
                if (docId) {
                    await firestore()
                        .collection("Events")
                        .doc(docId)
                        .delete();
                } else if (eventId) {
                    const snapshot = await firestore()
                        .collection("Events")
                        .where("id", "==", eventId)
                        .get();

                    const doc = snapshot.docs[0];
                    if (doc) {
                        await doc.ref.delete();
                    } else {
                        console.warn("Event not found");
                    }
                } else {
                    console.warn("No identifier provided");
                }
            } catch (e) {
                console.error(e);
            }
        },
        onSuccess: () => {
            queryClient.invalidateQueries("events");
        }
    });
};