import { PaymentCurrency, PaymentMethod, Payout } from '../../store/models';

export interface RefundInfo {
  reason?: string;
  livemode: number;
  amount: string;
  contract: string;
  chainType: string;
  chainApiHost: string;
}

/**
 * Build refund info from payout record
 * Extracts contract, chain type, and chain API host from payout's associated payment method and currency
 */
export async function buildRefundInfoFromPayout(payout: Payout, reason?: string): Promise<RefundInfo> {
  const paymentMethod = await PaymentMethod.findByPk(payout.payment_method_id);
  if (!paymentMethod) {
    throw new Error(`PaymentMethod not found: ${payout.payment_method_id} | Payout ID: ${payout.id}`);
  }

  const paymentCurrency = await PaymentCurrency.findByPk(payout.currency_id);
  if (!paymentCurrency?.contract) {
    throw new Error(`PaymentCurrency not found: ${payout.currency_id} | Payout ID: ${payout.id}`);
  }

  const chainType = paymentMethod.type;
  const chainSettings = paymentMethod.settings[chainType as keyof typeof paymentMethod.settings] as
    | {
        api_host: string;
      }
    | undefined;
  const chainApiHost = chainSettings?.api_host || '';
  if (!chainApiHost) {
    throw new Error(
      `Chain API host not found for payment method: ${paymentMethod.id} | Chain type: ${chainType} | Payout ID: ${payout.id}`
    );
  }

  return {
    livemode: payout.livemode ? 1 : 0,
    amount: payout.amount,
    contract: paymentCurrency.contract,
    chainType,
    chainApiHost,
    reason,
  };
}
