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

/**
 * Re-submit a single `failed` payout to the bank rail. **Idempotency-keyed**: a re-fired retry with the same
 * key never re-pays. On success we invalidate the owning batch's detail (the row flips `failed → paid`, and
 * if it was the batch's last failure the batch re-settles `partially_failed → completed`) and the batches
 * list (its status may have changed).
 */
export function useRetryPayout() {
  const queryClient = useQueryClient();
  return useMutation<void, unknown, { payoutId: number; idempotencyKey: string; batchId: number }>({
    mutationFn: ({ payoutId, idempotencyKey }) => payoutsApi.retryPayout(payoutId, idempotencyKey),
    onSuccess: (_data, { batchId }) => {
      queryClient.invalidateQueries({ queryKey: [...payoutKeys.adminBatchDetails(), batchId] });
      queryClient.invalidateQueries({ queryKey: payoutKeys.adminBatchLists() });
    },
  });
}
