import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { AuthAPI } from "@/lib/auth/auth-api";
import { useOnboardingStore } from "@/store/onboarding-store";
import { useAuthStore } from "@/store/auth-store";

export function useRegister() {
  const qc = useQueryClient();
  const { reset } = useOnboardingStore();
  const { setLoggingIn } = useAuthStore();

  const register = useMutation({
    mutationFn: (payload: {
      first_name: string;
      last_name: string;
      email: string;
      phone_mobile: number | string
      password: string;
      clientId?: string | number;
    }) => {
      setLoggingIn(true);
      return AuthAPI.register(payload, payload.clientId);
    },

    onSuccess: async (res) => {
      const token = res?.results?.authorisation?.token;
      const user = res?.results?.user; // contains id, name, email, etc.

      // -------- STORE TOKEN + USER ID --------
      if (token) localStorage.setItem("auth_token", token);
      if (user?.id) localStorage.setItem("user_id", user.id.toString());

      // -------- FETCH FULL PERSONAL INFO --------
      // Because basic user object is NOT what your app needs.
      if (user?.id) {
        const personalInfo = await AuthAPI.getUser(); // this now calls client_personal_info/{id}

        // Update React Query cache with the REAL user
        qc.setQueryData(["auth", "user"], personalInfo);
      }

      // -------- RESET ONBOARDING FOR NEW USER --------
      reset();
    },

    onSettled: () => {
      setLoggingIn(false);
    },
  });

  return {
    register: register.mutateAsync,
    isSubmitting: register.isPending,
  };
}
export const useNewClientPersonalInfo = (
  customerId: string | number,

) => {
  return useQuery({
    queryKey: ['new-client-personal-info', customerId],
    queryFn: async () => {
      const res = await AuthAPI.getNewClientPersonalInfo(customerId);
      return res;
    },
    enabled: !!customerId,
  });
};


