/**
 * Shared payload factory for referral.clawback outbox events.
 * Reused by webhook producer (T2), refund workflow (T3), and reconciliation (T8).
 */

export type ClawbackPayload = {
  reason: string;
  refundAmountAgorot: number;
  refundFraction: number;
  refundEventId: string;
  purchaseId?: string;
  chargeId?: string;
  disputeId?: string;
};

type ChargeArgs = {
  sourceType: 'charge';
  chargeId: string;
  purchaseId: string | null;
  refundEventId: string;
  refundFraction: number;
  refundAmountAgorot: number;
};

type DisputeArgs = {
  sourceType: 'dispute';
  disputeId: string;
  purchaseId: string | null;
  refundEventId: string;
  refundFraction: number;
  refundAmountAgorot: number;
};

type RefundArgs = {
  sourceType: 'refund';
  purchaseId: string | null;
  refundEventId: string;
  refundFraction: number;
  refundAmountAgorot: number;
};

type ClawbackArgs = ChargeArgs | DisputeArgs | RefundArgs;

export function buildClawbackPayload(args: ClawbackArgs): ClawbackPayload {
  const base: ClawbackPayload = {
    refundAmountAgorot: args.refundAmountAgorot,
    refundFraction: args.refundFraction,
    refundEventId: args.refundEventId,
    reason:
      args.sourceType === 'charge'
        ? 'charge.refunded'
        : args.sourceType === 'dispute'
          ? 'charge.dispute.closed'
          : 'refund_workflow',
  };

  if (args.purchaseId) {
    base.purchaseId = args.purchaseId;
  }

  if (args.sourceType === 'charge') {
    base.chargeId = args.chargeId;
  } else if (args.sourceType === 'dispute') {
    base.disputeId = args.disputeId;
  }

  return base;
}
