import { useMutation, useQueryClient } from '@tanstack/react-query';

import { persistAuthTokens } from '@/lib/auth/session';
import { useAuth } from '@/context/auth';

import { authApi } from '../apis';
import { authKeys } from '../keys';
import { toAppRoles } from '../routing';
import type { OtpVerify } from '../types';

/**
 * Verify the OTP, then establish the session: persist the token pair, sync AuthContext with the
 * roles the server returned (so the shells pick chrome immediately), and invalidate `/me` — the
 * role router's input. The router (rendered on success) then routes to the right app.
 *
 * Wrong/expired/lockout codes come back as domain 400s via `mutation.error`; the OTP screen maps
 * them to inline states. The fetch layer owns 401/403/5xx toasts.
 */
export function useVerifyOtp() {
  const [, dispatch] = useAuth();
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: (body: OtpVerify) => authApi.verifyOtp(body),
    onSuccess: (tokens, variables) => {
      persistAuthTokens(tokens);
      dispatch({
        type: 'LOG_IN',
        user: { phone: variables.phone, roles: toAppRoles(tokens.roles) },
      });
      queryClient.invalidateQueries({ queryKey: authKeys.me() });
    },
  });
}
