"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.processSwiftInbound = processSwiftInbound;
const uuid_1 = require("uuid");
const swift_1 = require("../adapters/swift");
const config_1 = require("../config");
const settlement_store_1 = require("../store/settlement-store");
const external_transfer_1 = require("./external-transfer");
/** Inbound MT103/MT102 → settlement workflow */
async function processSwiftInbound(raw) {
    await (0, swift_1.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 = {
        idempotencyKey: refMatch?.[1]?.trim() || `SWIFT-IN-${(0, uuid_1.v4)()}`,
        officeId: (0, config_1.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 = {
            settlementId: (0, uuid_1.v4)(),
            idempotencyKey: req.idempotencyKey,
            phase: 'RECEIVED',
            request: req,
            errors: ['Parsed inbound SWIFT — manual IBAN review required'],
            createdAt: new Date().toISOString(),
            updatedAt: new Date().toISOString(),
        };
        settlement_store_1.settlementStore.save(stub);
        return stub;
    }
    return (0, external_transfer_1.processExternalTransfer)(req);
}
