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

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

  return useMutation({
    mutationKey: ["deleteFeedback"],
    mutationFn: async (feedbackId: string) => {
      try {
        // Find the document with matching id field
        const snapshot = await firestore()
          .collection("Feedbacks")
          .where("id", "==", feedbackId)
          .get();

        if (snapshot.empty) {
          throw new Error("Feedback not found");
        }

        // Get the first matching document
        const docId = snapshot.docs[0].id;

        // Optional: Check if the current user is the creator
        const feedbackData = snapshot.docs[0].data();
        if (feedbackData.creatorId !== currentUser?.uid) {
          throw new Error(
            "Unauthorized: You can only delete your own feedback"
          );
        }

        // Delete the document
        await firestore().collection("Feedbacks").doc(docId).delete();
      } catch (e) {
        console.error("Error deleting feedback: ", e);
        throw e; // Re-throw the error to be handled by the mutation
      }
    },
    onSuccess: () => {
      queryClient.invalidateQueries({queryKey: ["feedbacks"]});
    },
  });
};
