import type { QueryClient } from '@tanstack/react-query';
import { bookingKeys } from '@/services/bookings/keys';
import { bookingRequestKeys } from '@/services/bookingRequests/keys';
import { paymentKeys } from './keys';

/**
 * The one cache transition a successful capture causes: the request flipped `converted` and a confirmed
 * booking now exists. Invalidate exactly the affected keys — the request detail + inboxes, the bookings
 * lists (a new row), the specific booking detail when known, and this request's checkout summary/outcome
 * — never a blanket refetch (phase rule: the booking flips to confirmed *by cache invalidation*, no
 * refetch storm). Shared by `useConfirmGatewayReturn` (immediate success) and the pending-callback poll
 * (late success).
 */
export function invalidateAfterPaymentSuccess(
  queryClient: QueryClient,
  bookingRequestId: number,
  bookingId: number | null,
): void {
  queryClient.invalidateQueries({ queryKey: bookingRequestKeys.detail(bookingRequestId) });
  queryClient.invalidateQueries({ queryKey: bookingRequestKeys.lists() });
  queryClient.invalidateQueries({ queryKey: bookingKeys.lists() });
  if (bookingId != null) {
    queryClient.invalidateQueries({ queryKey: bookingKeys.bookingDetail(bookingId) });
  }
  queryClient.invalidateQueries({ queryKey: paymentKeys.summary(bookingRequestId) });
  queryClient.invalidateQueries({ queryKey: paymentKeys.outcome(bookingRequestId) });
}
