import { useMutation, useQueryClient } from '@tanstack/react-query';
import { refundsApi } from '../apis';
import { invalidateAfterCancellation } from '../invalidations';
import type { CancelBookingInput } from '../types';

/**
 * Submit a customer-initiated cancellation. On success the returned refund is primed into its `byBooking`
 * key and the affected booking + refund caches are invalidated (so the booking-detail screen reflects the
 * new cancelled/refund state without a manual refetch, and the refund-status screen renders warm). A `409`
 * (outside-policy / already-cancelled / nothing-refundable) surfaces inline via `mutation.error` — the
 * fetch layer already toasts 401/403/5xx, so this hook never double-toasts.
 */
export function useCancelBooking() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: (input: CancelBookingInput) => refundsApi.cancelBooking(input),
    onSuccess: (refund, input) => invalidateAfterCancellation(queryClient, input.bookingId, refund),
  });
}
