import { useEffect } from 'react';

import { useAuth } from '@/context/auth';

import { useMe } from './useMe';
import { toAppRoles } from '../routing';

/**
 * Hydrate AuthContext with the real roles from `/me` for an already-authenticated session (a
 * returning user whose server-seeded state only knows `isAuthenticated`). Runs once per `/me`
 * result — the shells read `currentUser.roles` to pick chrome, so this keeps that single source
 * of truth fresh without a second role store. Mount it once, high in the authenticated tree.
 */
export function useSessionRoleSync(): void {
  const [, dispatch] = useAuth();
  const { data: me } = useMe();

  useEffect(() => {
    if (!me) return;
    dispatch({
      type: 'LOG_IN',
      // `roleCodes` preserves the server's fine-grained codes for the f15 admin-capability gate;
      // the collapsed `roles` still drive shell chrome.
      user: { id: me.id, phone: me.phone, roles: toAppRoles(me.roles), roleCodes: me.roles },
    });
  }, [me, dispatch]);
}
