"use client";

import { useMutation } from "@tanstack/react-query";
import { toast } from "sonner";
import { registerProviderApi } from "@/lib/api/auth.api";
import { setAuthCookie } from "@/lib/auth/session";
import { getApiErrorMessage } from "@/lib/api/error";
import type {
  RegisterProviderRequest,
  RegisterProviderResponse,
} from "@/types/auth";

/**
 * Submits the full provider registration. The backend creates the provider +
 * owner and returns a token immediately so the owner can reach a
 * pending-verification screen — the account still can't trade until an admin
 * sets status ACTIVE.
 *
 * Pass `onError` to map known failures (400 phone/email taken, 409 business name)
 * back to the offending step; when omitted, a generic toast is shown.
 */
export function useRegisterProvider(options?: {
  onSuccess?: (data: RegisterProviderResponse) => void;
  onError?: (error: unknown) => void;
}) {
  return useMutation({
    mutationFn: (payload: RegisterProviderRequest) =>
      registerProviderApi(payload),
    onSuccess: (data) => {
      setAuthCookie(data.accessToken);
      options?.onSuccess?.(data);
    },
    onError: (error: unknown) => {
      if (options?.onError) {
        options.onError(error);
        return;
      }
      toast.error(
        getApiErrorMessage(error, "Registration failed. Please try again."),
      );
    },
  });
}
