"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.chain138ExplorerBase = chain138ExplorerBase;
exports.chain138ExplorerTxUrl = chain138ExplorerTxUrl;
exports.chain138TxHashFromLogTopic = chain138TxHashFromLogTopic;
exports.enrichRegistryLogsEnvelope = enrichRegistryLogsEnvelope;
const ethers_1 = require("ethers");
/** Base URL for Chain 138 Blockscout (no trailing slash). */
function chain138ExplorerBase() {
    const fromEnv = process.env.CHAIN138_EXPLORER_URL || process.env.CHECKPOINT_CHAIN138_EXPLORER_URL;
    if (fromEnv)
        return fromEnv.replace(/\/$/, '');
    const api = process.env.CHECKPOINT_BLOCKSCOUT_API || 'https://explorer.d-bis.org/api/v2';
    try {
        const u = new URL(api);
        return `${u.protocol}//${u.host}`;
    }
    catch {
        return 'https://explorer.d-bis.org';
    }
}
/** Full explorer link for a Chain 138 transaction hash. */
function chain138ExplorerTxUrl(txHash, base) {
    const root = (base ?? chain138ExplorerBase()).replace(/\/$/, '');
    const hash = txHash.startsWith('0x') ? txHash : `0x${txHash}`;
    return `${root}/tx/${hash}`;
}
/** topic1 on ParticipantCredited/Debited is bytes32 chain138TxHash. */
function chain138TxHashFromLogTopic(topic) {
    if (!topic)
        return null;
    try {
        return ethers_1.ethers.hexlify(topic);
    }
    catch {
        return null;
    }
}
function enrichRegistryLogsEnvelope(envelope, explorerBase) {
    const base = explorerBase ?? chain138ExplorerBase();
    if (!envelope || typeof envelope !== 'object') {
        return { raw: envelope, decoded: [] };
    }
    const e = envelope;
    if (e.status !== '1' || !Array.isArray(e.result)) {
        return { raw: envelope, decoded: [] };
    }
    const decoded = [];
    for (const log of e.result) {
        const chain138TxHash = chain138TxHashFromLogTopic(log.topics?.[1]);
        if (!chain138TxHash || !log.transactionHash)
            continue;
        decoded.push({
            chain138TxHash,
            chain138ExplorerUrl: chain138ExplorerTxUrl(chain138TxHash, base),
            mainnetTxHash: log.transactionHash,
            mainnetExplorerUrl: `https://etherscan.io/tx/${log.transactionHash}`,
            blockNumber: String(log.blockNumber ?? ''),
            logIndex: String(log.logIndex ?? ''),
        });
    }
    return { raw: envelope, decoded };
}
