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

/**
 * Initiate (create + immediately execute) a ticket-linked admin refund. On success the customer-facing refund
 * read, the booking, every admin preview, and the linked support ticket are invalidated so the console and the
 * customer's status both reflect the outcome without a manual refetch. Domain 4xx (`400` invalid amount, `404`
 * no captured payment, `409` over-refund, `400` channel refused) surface via `mutation.error` for the panel to
 * render inline; the fetch layer already toasts 401/403/5xx, so this hook never double-toasts. A `failed`
 * result (channel declined) is a **success** here (the request completed) — the panel offers the retry.
 */
export function useInitiateRefund() {
  const queryClient = useQueryClient();
  return useMutation<AdminRefundResult, unknown, InitiateRefundInput>({
    mutationFn: (input) => refundsApi.initiateRefund(input),
    onSuccess: (_result, input) => invalidateAfterAdminRefund(queryClient, input.bookingId, input.ticketId),
  });
}
