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

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

    return useMutation({
        mutationKey: ["createFeedback"],
        mutationFn: async (feedback: Partial<IFeedback>) => {
            if (feedback.id) {
                const snapshot = await firestore()
                    .collection("Feedbacks")
                    .where("id", "==", feedback.id)
                    .get();

                if (!snapshot.empty) {
                    const docId = snapshot.docs[0].id;
                    await firestore()
                        .collection("Feedbacks")
                        .doc(docId)
                        .set({
                            ...feedback,
                            creatorId: currentUser?.uid,
                        }, { merge: true });
                    return;
                }
            }

            const newDoc = firestore().collection('Feedbacks').doc();
            await firestore()
                .collection("Feedbacks")
                .add({ ...feedback, id: newDoc.id, creatorId: currentUser?.uid });
        },
        onSuccess: () => {
            queryClient.invalidateQueries({ queryKey: ["feedbacks"] });
        }
    });
};

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

    return useMutation({
        mutationKey: ["createFeedbacksFromProvider"],
        mutationFn: async (feedbackDataArray: Partial<IFeedback>[]) => {
            const promises = feedbackDataArray.map(async (feedbackData) => {
                const snapshot = await firestore()
                    .collection("Feedbacks")
                    .where("id", "==", feedbackData.id)
                    .get();

                if (snapshot.empty) {
                    return firestore()
                        .collection("Feedbacks")
                        .add({ ...feedbackData, creatorId: currentUser?.uid });
                }

                const docId = snapshot.docs[0].id;
                return firestore()
                    .collection("Feedbacks")
                    .doc(docId)
                    .set({ ...feedbackData, creatorId: currentUser?.uid }, { merge: true });
            });

            await Promise.all(promises);
        },
        onSuccess: () => {
            queryClient.invalidateQueries({ queryKey: ["feedbacks"] });
        }
    });
};