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

import { COOKIE_NAMES } from '@/lib/cookies';
import { getClientCookie } from '@/lib/cookies/client';
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 { PublicRole } from '../types';

/**
 * Self-assign a public actor role for a brand-new user. Because role claims live inside the access
 * token, we rotate the token pair after selecting so subsequent role-gated calls carry the new
 * claim (contract note). AuthContext and the cached `/me` are then updated so the router re-runs
 * against the new role.
 */
export function useSelectRole() {
  const queryClient = useQueryClient();
  const [, dispatch] = useAuth();

  return useMutation({
    mutationFn: (role: PublicRole) => authApi.selectRole({ role }),
    onSuccess: async (me) => {
      const refreshToken = getClientCookie(COOKIE_NAMES.REFRESH_TOKEN);
      if (refreshToken) {
        try {
          persistAuthTokens(await authApi.refresh({ refreshToken }));
        } catch {
          // A failed rotation surfaces on the next `/me`/gated call via the fetch layer; the
          // role is already persisted server-side, so don't block the flow on it.
        }
      }
      dispatch({ type: 'LOG_IN', user: { id: me.id, phone: me.phone, roles: toAppRoles(me.roles) } });
      queryClient.setQueryData(authKeys.me(), me);
    },
  });
}
