import { useMutation, useQueryClient } from '@tanstack/react-query';
import { bnplApi } from '../apis';
import { invalidateAfterBnplSettlement } from '../invalidations';
import { isBnplSettlementSuccess, type AcceptBnplScheduleInput } from '../types';

/**
 * The settle-on-return mutation (the down-payment-cleared analogue of the provider webhook): reported once
 * from the return surface. On a successful settlement it **invalidates the booking + checkout + Wallet
 * queries** so the confirmed booking isn't refetched stale and D5 reflects the new plan (never a blanket
 * refetch). The booking then confirms exactly as the card path — the return page routes to the reused f9
 * confirmation.
 */
export function useAcceptBnplSchedule() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: (input: AcceptBnplScheduleInput) => bnplApi.acceptBnplSchedule(input),
    onSuccess: (result) => {
      if (isBnplSettlementSuccess(result)) {
        invalidateAfterBnplSettlement(queryClient, result.bookingRequestId, result.bookingId);
      }
    },
  });
}
