"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.scanDirectoryInbox = scanDirectoryInbox;
exports.archiveInboxFile = archiveInboxFile;
exports.scanFileInbox = scanFileInbox;
exports.pollP2pRailTransactions = pollP2pRailTransactions;
exports.pollFinGatewayMessages = pollFinGatewayMessages;
const fs_1 = require("fs");
const path_1 = require("path");
const inboundParser_1 = require("../parsers/inboundParser");
const INBOX_EXTENSIONS = /\.(fin|swift|xml|txt|json|as4|mx|telex|ktt)$/i;
function scanDirectoryInbox(inboxDir, sourcePrefix, defaultFormat) {
    const messages = [];
    let entries = [];
    try {
        entries = (0, fs_1.readdirSync)(inboxDir);
    }
    catch {
        return messages;
    }
    for (const name of entries.sort()) {
        const full = (0, path_1.join)(inboxDir, name);
        if (!(0, fs_1.statSync)(full).isFile())
            continue;
        if (name.startsWith('.'))
            continue;
        if (!INBOX_EXTENSIONS.test(name))
            continue;
        const payload = (0, fs_1.readFileSync)(full, 'utf8');
        const lower = name.toLowerCase();
        let format = defaultFormat ?? (0, inboundParser_1.detectInboundFormat)(payload);
        if (lower.endsWith('.xml') || lower.endsWith('.mx') || lower.endsWith('.as4'))
            format = 'iso20022';
        if (lower.endsWith('.json'))
            format = 'json_broadcast';
        if (lower.endsWith('.telex') || lower.endsWith('.ktt'))
            format = 'ktt';
        messages.push({
            source: `${sourcePrefix}:${full}`,
            format,
            payload,
            metadata: { fileName: name, filePath: full },
        });
    }
    return messages;
}
function archiveInboxFile(filePath, archiveDir) {
    (0, fs_1.mkdirSync)(archiveDir, { recursive: true });
    const base = filePath.split('/').pop() ?? 'message';
    (0, fs_1.renameSync)(filePath, (0, path_1.join)(archiveDir, `${Date.now()}-${base}`));
}
function scanFileInbox(inboxDir) {
    return scanDirectoryInbox(inboxDir, 'file');
}
async function pollP2pRailTransactions(options) {
    const url = `${options.baseUrl.replace(/\/$/, '')}${options.path ?? '/api/transactions'}`;
    const headers = { Accept: 'application/json' };
    if (options.bearerToken)
        headers.Authorization = `Bearer ${options.bearerToken}`;
    if (options.apiKey)
        headers['X-API-Key'] = options.apiKey;
    const res = await fetch(url, { headers });
    if (!res.ok) {
        throw new Error(`P2P rail poll failed: ${res.status} ${res.statusText}`);
    }
    const body = (await res.json());
    const rows = Array.isArray(body) ? body : body?.data ?? [];
    const out = [];
    for (const row of rows) {
        const obj = row;
        const id = String(obj.id ?? obj.transactionId ?? obj.reference ?? '');
        if (options.sinceId && id && id <= options.sinceId)
            continue;
        const payload = typeof obj.payload === 'string'
            ? obj.payload
            : typeof obj.swiftMessage === 'string'
                ? obj.swiftMessage
                : typeof obj.message === 'string'
                    ? obj.message
                    : JSON.stringify(obj);
        out.push({
            source: `p2p:${id || 'unknown'}`,
            format: (0, inboundParser_1.detectInboundFormat)(payload),
            payload,
            metadata: obj,
        });
    }
    return out;
}
async function pollFinGatewayMessages(options) {
    const url = `${options.baseUrl.replace(/\/$/, '')}${options.path ?? '/api/messages'}`;
    const headers = { Accept: 'application/json' };
    if (options.bearerToken)
        headers.Authorization = `Bearer ${options.bearerToken}`;
    const res = await fetch(url, { headers });
    if (!res.ok) {
        throw new Error(`FIN gateway poll failed: ${res.status} ${res.statusText}`);
    }
    const body = (await res.json());
    const rows = Array.isArray(body)
        ? body
        : body?.messages ??
            body?.data ??
            [];
    const out = [];
    for (const row of rows) {
        const obj = row;
        const id = String(obj.id ?? obj.messageId ?? obj.reference ?? '');
        if (options.sinceId && id && id <= options.sinceId)
            continue;
        const payload = typeof obj.finMessage === 'string'
            ? obj.finMessage
            : typeof obj.swiftMessage === 'string'
                ? obj.swiftMessage
                : typeof obj.payload === 'string'
                    ? obj.payload
                    : typeof obj.body === 'string'
                        ? obj.body
                        : JSON.stringify(obj);
        out.push({
            source: `fin:${id || 'unknown'}`,
            format: (0, inboundParser_1.detectInboundFormat)(payload),
            payload,
            metadata: obj,
        });
    }
    return out;
}
//# sourceMappingURL=inboundAdapters.js.map