import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { QUERY_KEYS } from "@/utils/query-key";
import {
  getAutoVerifySetting,
  updateAutoVerifySetting,
} from "./_requests";
import {
  UpdateAutoVerifySettingRequest,
  AutoVerifySettingResponse,
} from "./_models";
import toast from "react-hot-toast";

export const useAutoVerifySetting = () => {
  return useQuery({
    queryKey: [QUERY_KEYS.GET_AUTO_VERIFY_SETTING],
    queryFn: getAutoVerifySetting,
  });
};

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

  return useMutation({
    mutationKey: [QUERY_KEYS.UPDATE_AUTO_VERIFY_SETTING],
    mutationFn: (data: UpdateAutoVerifySettingRequest) =>
      updateAutoVerifySetting(data),
    onSuccess: (data: AutoVerifySettingResponse) => {
      queryClient.invalidateQueries({
        queryKey: [QUERY_KEYS.GET_AUTO_VERIFY_SETTING],
      });
      toast.success(
        `تأیید خودکار کاربران جدید ${data.setting.data.enabled ? "فعال" : "غیرفعال"} شد`
      );
    },
    onError: (error: any) => {
      console.error("Error updating auto verify setting:", error);
      toast.error(error?.message || "خطا در به‌روزرسانی تنظیمات");
    },
  });
};
