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

/**
 * Nurse EVV check-in. On success it **invalidates** the booking detail (timeline + the embedded session
 * flips to `in_progress`), the today feed (the row's CTA state), and the bookings lists, and primes the
 * per-session EVV cache with the returned verification so the banner is instant. No client-side status or
 * money math — the server response is the single source. `bookingId` is passed alongside the input so the
 * invalidation is surgical (the verification payload carries only the session id).
 *
 * A GPS mismatch is advisory (`checkInAddressMatch = false`) and still succeeds — the banner warns, it
 * never blocks. Fetch-layer errors (401/403/5xx) are toasted by `clientFetch`; the caller surfaces only
 * domain-specific 4xx (e.g. a `409` not-startable).
 */
export function useCheckInVisit() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: ({ input }: { input: CheckInVisitInput; bookingId: number }) => bookingsApi.checkInVisit(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() });
    },
  });
}
