import { useMutation, useQueryClient } from '@tanstack/react-query';
import { bookingsApi } from '../apis';
import { bookingKeys } from '../keys';
import type { CheckOutVisitInput } from '../types';

/**
 * Nurse EVV check-out — must follow an open check-in (a `400 no_open_check_in` otherwise, surfaced by the
 * caller, not the fetch layer). On success the session flips to `completed` and, when it's the last
 * session, the booking completes + the dispute window opens — all server-driven. It invalidates the same
 * keys as check-in so the timeline, session row, and today feed reflect the new server state; no
 * client-side payout-eligibility math (`payoutEligibleAt` is server truth).
 */
export function useCheckOutVisit() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: ({ input }: { input: CheckOutVisitInput; bookingId: number }) => bookingsApi.checkOutVisit(input),
    onSuccess: (verification, { input, bookingId }) => {
      queryClient.setQueryData(bookingKeys.sessionEvv(input.bookingSessionId), verification);
      queryClient.invalidateQueries({ queryKey: bookingKeys.bookingDetail(bookingId) });
      queryClient.invalidateQueries({ queryKey: bookingKeys.sessionEvv(input.bookingSessionId) });
      queryClient.invalidateQueries({ queryKey: bookingKeys.todayLists() });
      queryClient.invalidateQueries({ queryKey: bookingKeys.lists() });
    },
  });
}
