import { keepPreviousData, useQuery } from '@tanstack/react-query';
import { patientRecordsApi } from '../apis';
import { recordKeys } from '../keys';
import { PATIENT_RECORDS_GC_TIME, RECORD_HISTORY_PAGE_SIZE, RECORD_HISTORY_STALE_TIME } from '../constants';

/**
 * The patient-scoped longitudinal visit-note history (newest-first, paged) — REAL b14 `care_records` GET.
 * Read-only; it **persists across nurse changes** (keyed to the patient, not a booking). The page is part of
 * the query key so paging never refetches a page already in cache; `keepPreviousData` avoids an empty flash.
 * A nurse note append invalidates these keys so the new note appears at once.
 */
export function usePatientHistory(patientId: number, page: number, options?: { enabled?: boolean }) {
  return useQuery({
    queryKey: recordKeys.history(patientId, page),
    queryFn: () => patientRecordsApi.getPatientHistory(patientId, { page, pageSize: RECORD_HISTORY_PAGE_SIZE }),
    enabled: (options?.enabled ?? true) && patientId > 0,
    staleTime: RECORD_HISTORY_STALE_TIME,
    gcTime: PATIENT_RECORDS_GC_TIME,
    placeholderData: keepPreviousData,
  });
}
