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

/** Minimum query length before searching — avoids a fan-out request per keystroke on 0–1 chars. */
const MIN_QUERY_LENGTH = 2;

/**
 * Name/phone search over the admin user directory (REQ-061, gap) — backs `UserPicker`/`NursePicker`.
 * The caller debounces `query`; this hook only gates on length so an empty/near-empty query renders no
 * options instead of the whole directory.
 */
export function useUserSearch(query: string, roleFilter?: DirectoryUserRole) {
  const trimmed = query.trim();
  return useQuery({
    queryKey: adminKeys.userSearch(trimmed, roleFilter),
    queryFn: () => adminApi.searchUsers(trimmed, roleFilter),
    enabled: trimmed.length >= MIN_QUERY_LENGTH,
    staleTime: 30 * 1000,
    gcTime: ADMIN_GC_TIME,
  });
}
