import { useQuery } from '@tanstack/react-query';
import { patientsApi } from '../apis';
import { patientKeys } from '../keys';
import { PATIENTS_STALE_TIME } from '../constants';

/**
 * A single patient by id — the identity header for the E2 record viewer (name, age/gender, conditions).
 * Keyed on `patientKeys.detail(id)` so it shares/warms the same cache the list primes. A missing/cross-tenant
 * id `404`s (surfaced as the query error); the caller renders a not-found state. `enabled` lets the E2 viewer
 * defer the fetch until the clinical-access check passes.
 */
export function usePatient(id: number, options?: { enabled?: boolean }) {
  return useQuery({
    queryKey: patientKeys.detail(id),
    queryFn: () => patientsApi.get(id),
    enabled: (options?.enabled ?? true) && id > 0,
    staleTime: PATIENTS_STALE_TIME,
  });
}
