import { useMutation, useQueryClient } from '@tanstack/react-query';
import { payoutsApi } from '../apis';
import { payoutKeys } from '../keys';
import type { PayoutBatchSummary } from '../types';

/**
 * Open + run a payout batch for a window. **Idempotency-keyed**: the caller passes a stable `idempotencyKey`
 * per run so a retried submit converges on the same batch (never a double-run). On success we invalidate the
 * batches list so the new batch appears at the top without a manual refresh. Domain 4xx (e.g. no eligible
 * bookings) surface to the caller's `onError`.
 */
export function useRunPayoutBatch() {
  const queryClient = useQueryClient();
  return useMutation<
    PayoutBatchSummary,
    unknown,
    { periodStart: string; periodEnd: string; idempotencyKey: string }
  >({
    mutationFn: ({ periodStart, periodEnd, idempotencyKey }) =>
      payoutsApi.runPayoutBatch(periodStart, periodEnd, idempotencyKey),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: payoutKeys.adminBatchLists() });
    },
  });
}
