import { useQuery } from '@tanstack/react-query';
import { adminApi } from '../apis';
import { adminKeys } from '../keys';
import { ADMIN_GC_TIME } from '../constants';
import type { AdminUserSummary } from '../types';

/**
 * Batch id→label resolve (REQ-061, gap) — one request for every actor/owner id a page renders (`AuditLogRow`,
 * role grants, …), never one request per row. Callers should memoize `userIds` (a stable array reference)
 * so the query key doesn't churn every render; pass a deduped list.
 */
export function useUserLookup(userIds: number[]) {
  return useQuery({
    queryKey: adminKeys.userLookup(userIds),
    queryFn: () => adminApi.lookupUsers(userIds),
    enabled: userIds.length > 0,
    staleTime: 5 * 60 * 1000,
    gcTime: ADMIN_GC_TIME,
    select: (data): Map<number, AdminUserSummary> => new Map(data.map((u) => [u.id, u])),
  });
}
