import { useMutation, useQueryClient } from "@tanstack/react-query";
import { createUserManagementApi } from "~/utils/api-client-factory";

export function useServiceSendOtp(
  phoneNumber: string,
  setEnableVerifySection: (enable: boolean) => void
) {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: async () => {
      const userApi = createUserManagementApi();
      try {
        await userApi.apiUserV1RegisterCreate({
          data: { phoneNumber },
        });
        setEnableVerifySection(true);
        return true;
      } catch (error) {
        console.log("error on send otp", error);
        throw new Error("Failed to send OTP");
      }
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["sendOtpService"] });
    },
  });
}

// New service to send OTP and phone_number
export function useServiceVerifyOtp(
  phoneNumber: string,
  otp: string,
  toast: (toast: {
    title: string;
    description?: string;
    variant?: "default" | "destructive";
  }) => void
) {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: async () => {
      const userApi = createUserManagementApi();
      try {
        const response = await userApi.apiUserV1VerifyOtpCreate({
          data: { phoneNumber, otp },
        });
        return response;
      } catch (error) {
        console.log("error on verify otp", error);
        toast({
          description: "کد تایید یا شماره موبایل اشتباه است.",
          title: "خطایی رخ داد.",
          variant: "destructive",
        });
        throw error;
      }
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["VerifyOtpService"] });
      queryClient.invalidateQueries();
    },
  });
}
