import { useMutation } from "@tanstack/react-query";
import { SignupSchema } from "./schema";
import { apiPost } from "../../../../lib/api/methods";
import { AUTH_ENDPOINTS } from "../endpoints";
import { errorToast, successToast } from "../../../../utils/toast";
import { AxiosError } from "axios";
import { SUCCESS_MESSAGES } from "./messages";


export default function useRegister() {
  const { mutateAsync, isPending } = useMutation({
    mutationKey: ["register"],
    mutationFn: async (payload: SignupSchema) => {
      const response = await apiPost<{
        message: string;
      }>(AUTH_ENDPOINTS.SIGNUP, {
        ...payload,
        dialCode: payload.mobileNumber.dialCode,
        mobileNumber: payload.mobileNumber.number,
      });
      return response;
    },

    onSuccess: (data) => {
      successToast(SUCCESS_MESSAGES.REGISTER);
    },
    onError: (
      error: AxiosError<{
        message?: string;
        errors?: Record<string, string[]>;
      }>,
    ) => {
      const message = error?.response?.data?.message;
      errorToast(message ?? "Something went wrong, please try again.");
    },
  });

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