import { v4 as uuidv4 } from 'uuid';
import type { ExternalTransferRequest, SettlementRecord } from '@dbis/settlement-core';
import { forwardSwiftToListener } from '../adapters/swift';
import { settlementOfficeId } from '../config';
import { settlementStore } from '../store/settlement-store';
import { processExternalTransfer } from './external-transfer';

/** Inbound MT103/MT102 → settlement workflow */
export async function processSwiftInbound(raw: string): Promise<SettlementRecord> {
  await forwardSwiftToListener(raw);

  const isMt102 = /\bMT102\b|:23:/.test(raw) || /:32B:/.test(raw);
  const refMatch = raw.match(/:20:([^\n]+)/);
  const amtMatch = raw.match(/:32[AB]:(\d{6})([A-Z]{3})([\d,]+)/);
  const ibanMatch = raw.match(/\/([A-Z]{2}\d{2}[A-Z0-9]+)/);
  const bnfMatch = raw.match(/:59:[^\n]*\n([^\n:]+)/);
  const remMatch = raw.match(/:70:([^\n]+)/);

  const req: ExternalTransferRequest = {
    idempotencyKey: refMatch?.[1]?.trim() || `SWIFT-IN-${uuidv4()}`,
    officeId: settlementOfficeId(),
    valueDate: new Date().toISOString().slice(0, 10),
    currency: amtMatch?.[2] ?? 'USD',
    amount: (amtMatch?.[3] ?? '0').replace(',', '.'),
    creditorIban: ibanMatch?.[1] ?? '',
    beneficiaryName: bnfMatch?.[1]?.trim() ?? 'Inbound beneficiary',
    remittanceInfo: remMatch?.[1]?.trim() ?? 'Inbound SWIFT settlement',
    moneyLayers: isMt102 ? ['M1', 'M2'] : ['M0', 'M1'],
    rail: 'SWIFT',
    swiftMessageKind: isMt102 ? 'MT102' : 'MT103',
    rwaVerbiage: { assetClass: 'RWA', tokenLineId: 'USD-M1', externalTransferRoll: true },
  };

  if (!req.creditorIban) {
    const stub: SettlementRecord = {
      settlementId: uuidv4(),
      idempotencyKey: req.idempotencyKey,
      phase: 'RECEIVED',
      request: req,
      errors: ['Parsed inbound SWIFT — manual IBAN review required'],
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString(),
    };
    settlementStore.save(stub);
    return stub;
  }

  return processExternalTransfer(req);
}
