import { useMutation, useQueryClient } from '@tanstack/react-query';
import { paymentApi } from '../apis';
import { paymentKeys } from '../keys';
import { invalidateAfterPaymentSuccess } from '../invalidations';
import type { ConfirmGatewayReturnInput } from '../types';

/**
 * Report the return from the gateway and read the outcome. On the real path the PSP already confirmed
 * via the webhook, so this is a read; in the mock it is the capture trigger. When the outcome is already
 * `succeeded`, the affected booking/request caches are invalidated here (the booking flips to confirmed
 * by cache invalidation, never a blanket refetch); a still-`pending` outcome is primed into the outcome
 * key so the pending-callback poll (`usePaymentOutcome`) starts from fresh data.
 */
export function useConfirmGatewayReturn() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: (input: ConfirmGatewayReturnInput) => paymentApi.confirmGatewayReturn(input),
    onSuccess: (outcome) => {
      queryClient.setQueryData(paymentKeys.outcome(outcome.bookingRequestId), outcome);
      if (outcome.transactionStatus === 'succeeded') {
        invalidateAfterPaymentSuccess(queryClient, outcome.bookingRequestId, outcome.bookingId);
      }
    },
  });
}
