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

/**
 * Soft-archives a patient (`isActive=false`, never a hard delete — historical bookings must
 * survive). Optimistically removes the card from every cached list, then reconciles on
 * settle; on error the previous cache is restored.
 */
export function useArchivePatient() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: (id: number) => patientsApi.archive(id),
    onMutate: async (id) => {
      await queryClient.cancelQueries({ queryKey: patientKeys.lists() });
      const previous = queryClient.getQueriesData<Paginated<Patient>>({ queryKey: patientKeys.lists() });
      previous.forEach(([key, data]) => {
        if (!data) return;
        queryClient.setQueryData<Paginated<Patient>>(key, {
          ...data,
          items: data.items.filter((patient) => patient.id !== id),
          total: Math.max(0, data.total - 1),
        });
      });
      return { previous };
    },
    onError: (_error, _id, context) => {
      context?.previous?.forEach(([key, data]) => queryClient.setQueryData(key, data));
    },
    onSettled: () => {
      queryClient.invalidateQueries({ queryKey: patientKeys.lists() });
    },
  });
}
