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

/**
 * Approve / retry a refund (the console's action on a channel-declined `failed` refund, or an
 * approval-gated `requested` one). The result carries the booking id, so on success we invalidate that
 * booking's refund + previews via the shared helper. Domain 4xx (`404` not found, `409` not awaiting
 * approval) surface via `mutation.error`.
 */
export function useApproveRefund() {
  const queryClient = useQueryClient();
  return useMutation<AdminRefundResult, unknown, number>({
    mutationFn: (refundId) => refundsApi.approveRefund(refundId),
    onSuccess: (result) => invalidateAfterAdminRefund(queryClient, result.bookingId),
  });
}
