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

interface UpdateFeedbackParams {
  id: number;
  changes: Partial<IFeedback>;
}

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

  return useMutation({
    mutationKey: ["updateFeedback"],
    mutationFn: async ({ id, changes }: UpdateFeedbackParams) => {
      try {
        const snapshot = await firestore()
          .collection("Feedbacks")
          .where("id", "==", id)
          .get();

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

        const docId = snapshot.docs[0].id;
        const feedbackData = snapshot.docs[0].data();

        if (feedbackData.creatorId !== currentUser?.uid) {
          throw new Error(
            "Unauthorized: You can only update your own feedback"
          );
        }

        await firestore()
          .collection("Feedbacks")
          .doc(docId)
          .update({
            ...changes,
            updatedAt: firestore.FieldValue.serverTimestamp(),
            lastModifiedBy: currentUser?.uid,
          });

        return {
          id,
          ...feedbackData,
          ...changes,
        };
      } catch (e) {
        console.error("Error updating feedback: ", e);
        throw e;
      }
    },
    onSuccess: (updatedFeedback) => {
      queryClient.invalidateQueries("feedbacks");

      queryClient.setQueryData(
        ["feedback", updatedFeedback.id],
        updatedFeedback
      );
    },
  });
};
