import type { ExternalTransferRequest, SwiftMessageKind, TradeFinanceInstrument } from './types';

/** OMNL central-bank external transfer verbiage roll (audit + operator copy) */
export function rollExternalTransferVerbiage(req: ExternalTransferRequest): string {
  const lines = [
    '=== OMNL CENTRAL BANK — EXTERNAL TRANSFER VERBIAGE ROLL ===',
    `Settlement ref: ${req.idempotencyKey}`,
    `Value date: ${req.valueDate}`,
    `Amount: ${req.amount} ${req.currency}`,
    `Rail: ${req.rail}`,
    `Money layers: ${req.moneyLayers.join(' + ')}`,
    `Beneficiary: ${req.beneficiaryName}`,
    `Creditor IBAN: ${req.creditorIban}`,
  ];
  if (req.creditorBic) lines.push(`Creditor BIC: ${req.creditorBic}`);
  if (req.debtorIban) lines.push(`Debtor IBAN: ${req.debtorIban}`);
  if (req.orderingName) lines.push(`Ordering party: ${req.orderingName}`);
  lines.push(`Remittance: ${req.remittanceInfo}`);
  if (req.swiftMessageKind) lines.push(`SWIFT message: ${req.swiftMessageKind}`);
  if (req.tradeFinance) {
    lines.push(
      `Trade finance: ${req.tradeFinance.instrument} ref ${req.tradeFinance.reference}`,
    );
  }
  if (req.rwaVerbiage?.externalTransferRoll) {
    lines.push(
      `RWA roll: ${req.rwaVerbiage.assetClass} → line ${req.rwaVerbiage.tokenLineId}`,
    );
  }
  if (req.convertToCrypto?.enabled) {
    lines.push(
      `Post-settlement crypto conversion: chain ${req.convertToCrypto.targetChainId} → ${req.convertToCrypto.recipientAddress}`,
    );
  }
  lines.push(
    '',
    'DISCLAIMER: Internal OMNL operator verbiage — not SWIFT NET transmission.',
    'Fineract SoR + ISO 20022 archive bind settlement finality.',
  );
  return lines.join('\n');
}

export function buildMt103Narrative(req: ExternalTransferRequest): string {
  return `/BNF/${req.beneficiaryName}//${req.remittanceInfo}`.slice(0, 140);
}

export function buildMt102Narrative(req: ExternalTransferRequest): string {
  const tf = req.tradeFinance ? `/${req.tradeFinance.instrument}/${req.tradeFinance.reference}` : '';
  return `/BNF/${req.beneficiaryName}${tf}//${req.remittanceInfo}`.slice(0, 140);
}

export function swiftKindForRequest(req: ExternalTransferRequest): SwiftMessageKind {
  if (req.swiftMessageKind) return req.swiftMessageKind;
  if (req.tradeFinance?.instrument === 'LS' || req.tradeFinance?.instrument === 'DLC') {
    return 'MT102';
  }
  return 'MT103';
}
