import { useMutation, useQueryClient } from "@tanstack/react-query";
import { apiPost } from "../../../../lib/api/methods";
import { PROFILE_ENDPOINTS } from "../endpoints";
import { successToast, errorToast } from "../../../../utils/toast";
import { SUCCESS_MESSAGES } from "./messages";


type VerifyNewMailResponse = {
  message: string;
};

export default function useVerifyNewMail() {
  const queryClient = useQueryClient();
  const { mutateAsync, isPending } = useMutation({
    mutationKey: ["verify-new-email"],
    mutationFn: async (data: { email: string; otp: string }) => {
      const res = await apiPost<VerifyNewMailResponse>(
        PROFILE_ENDPOINTS.VERIFY_NEW_EMAIL_OTP,
        data,
      );
      return res;
    },
    onSuccess: (data) => {
      successToast(SUCCESS_MESSAGES.VERIFY_NEW);
      queryClient.invalidateQueries({ queryKey: ["profile"] });
    },
    onError: (error: any) => {
      errorToast(error?.response?.data?.message ?? "Something went wrong.");
    },
  });

  return { handleVerifyNewMail: mutateAsync, loading: isPending };
}
