import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { QUERY_KEYS } from "@/utils/query-key";
import toast from "react-hot-toast";
import {
  getProductComments,
  updateCommentStatus,
  deleteComment,
} from "./_requests";
import {
  ProductCommentFilters,
  UpdateCommentStatusRequest,
} from "./_models";

export const useProductComments = (filters: ProductCommentFilters) => {
  return useQuery({
    queryKey: [QUERY_KEYS.GET_PRODUCT_COMMENTS, filters],
    queryFn: () => getProductComments(filters),
  });
};

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

  return useMutation({
    mutationFn: ({
      commentId,
      payload,
    }: {
      commentId: string;
      payload: UpdateCommentStatusRequest;
    }) => updateCommentStatus(commentId, payload),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: [QUERY_KEYS.GET_PRODUCT_COMMENTS] });
      toast.success("وضعیت نظر با موفقیت تغییر کرد");
    },
    onError: () => {
      toast.error("خطا در تغییر وضعیت نظر");
    },
  });
};

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

  return useMutation({
    mutationFn: (commentId: string) => deleteComment(commentId),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: [QUERY_KEYS.GET_PRODUCT_COMMENTS] });
      toast.success("نظر با موفقیت حذف شد");
    },
    onError: () => {
      toast.error("خطا در حذف نظر");
    },
  });
};

