import { useMutation, useQueryClient } from '@tanstack/react-query';
import { patientRecordsApi } from '../apis';
import { recordKeys } from '../keys';
import type { CreateVisitNoteRequest, WriteVisitNoteResult } from '../types';

/**
 * The **nurse** append of a visit note (append-only — the nurse never edits the family record). Bound to one
 * patient. On success we invalidate the patient's **history** (every page) so the appended note appears in the
 * longitudinal timeline at once. The mutation returns only the write result; the history refetch is the source
 * of truth. Domain 4xx (`400` empty body, `403` no clinical access) surface to the caller's `onError`.
 */
export function useCreateVisitNote(patientId: number) {
  const queryClient = useQueryClient();
  return useMutation<WriteVisitNoteResult, unknown, CreateVisitNoteRequest>({
    mutationFn: (body) => patientRecordsApi.createVisitNote(patientId, body),
    onSuccess: () => {
      // Prefix invalidation: [...histories(), patientId] matches every page of this patient's history.
      queryClient.invalidateQueries({ queryKey: [...recordKeys.histories(), patientId] });
    },
  });
}
