import { useMutation, useQueryClient } from '@tanstack/react-query';
import type { Paginated } from '@/lib/api/types';
import { patientsApi } from '../apis';
import { patientKeys } from '../keys';
import type { CreatePatientInput, Patient } from '../types';

/**
 * Creates a patient. Splices the new row into every cached list immediately (so the E1 list
 * and the Home onboarding-gate reflect it without waiting for a refetch — no transient
 * "0 patients" window that would bounce the user back to onboarding), then invalidates to
 * reconcile. Domain 400s (missing/invalid gender, future birth date) surface via
 * `mutation.error`; the fetch layer owns 401/403/5xx toasts.
 */
export function useCreatePatient() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: (input: CreatePatientInput) => patientsApi.create(input),
    onSuccess: (patient) => {
      queryClient.setQueriesData<Paginated<Patient>>({ queryKey: patientKeys.lists() }, (old) =>
        old ? { ...old, items: [patient, ...old.items], total: old.total + 1 } : old,
      );
      queryClient.invalidateQueries({ queryKey: patientKeys.lists() });
    },
  });
}
