"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.EscrowTabServer = void 0;
const fs = __importStar(require("node:fs"));
const path = __importStar(require("node:path"));
const types_1 = require("./types");
const escrow_1 = require("./escrow");
class EscrowTabServer {
    config;
    channelsPath;
    channels = new Map();
    fundingCache = new Map();
    static FUNDING_CACHE_MS = 3_000;
    constructor(config) {
        this.config = config;
        fs.mkdirSync(config.dataDir, { recursive: true, mode: 0o700 });
        this.channelsPath = path.join(config.dataDir, "escrow-channels.json");
        if (fs.existsSync(this.channelsPath)) {
            for (const c of JSON.parse(fs.readFileSync(this.channelsPath, "utf8"))) {
                this.channels.set(c.clientPublic, c);
            }
        }
    }
    params(clientPublic) {
        return { clientPublic, serverPublic: this.config.serverPublicHex, timeout: this.config.refundTimeout };
    }
    offer() {
        return {
            x402Version: 1,
            accepts: [
                {
                    scheme: "kaspa-escrow",
                    network: this.config.networkId,
                    serverPublic: this.config.serverPublicHex,
                    refundTimeout: this.config.refundTimeout.toString(),
                    minDepositSompi: this.config.minDepositSompi.toString(),
                    pricePerRequestSompi: this.config.pricePerRequestSompi.toString(),
                    description: this.config.description,
                },
            ],
        };
    }
    async fundedSompi(address) {
        const cached = this.fundingCache.get(address);
        if (cached && Date.now() - cached[1] < EscrowTabServer.FUNDING_CACHE_MS)
            return cached[0];
        const rpc = await this.config.rpc();
        const { entries } = await rpc.getUtxosByAddresses([address]);
        const total = entries.reduce((acc, e) => acc + BigInt(e?.amount ?? e?.entry?.amount ?? 0), 0n);
        this.fundingCache.set(address, [total, Date.now()]);
        return total;
    }
    /** Returns true when the request was answered with a 402 (no payment / insufficient). */
    async gate(req, res) {
        const raw = req.headers[types_1.X_PAYMENT_HEADER];
        let header;
        if (typeof raw === "string") {
            try {
                header = (0, types_1.decodePaymentHeader)(raw);
            }
            catch {
                header = undefined;
            }
        }
        if (!header || header.scheme !== "kaspa-escrow" || !header.clientPublic) {
            return this.reply402(res);
        }
        const price = this.config.pricePerRequestSompi;
        const channel = this.channels.get(header.clientPublic) ?? {
            clientPublic: header.clientPublic,
            servedCount: 0,
            authorizedSompi: "0",
            voucherHex: "",
        };
        const required = BigInt(channel.servedCount + 1) * price;
        const voucherAmount = BigInt(header.voucherAmountSompi);
        // 1. voucher must cryptographically authorize at least the running total.
        if (voucherAmount < required || !(0, escrow_1.verifyVoucher)(header.clientPublic, voucherAmount, header.voucherHex)) {
            return this.reply402(res);
        }
        // 2. the escrow must actually hold at least the authorized amount, so the
        //    server's claim will succeed.
        const escrowAddr = (0, escrow_1.deriveEscrowAddress)(this.params(header.clientPublic), this.config.networkId);
        if ((await this.fundedSompi(escrowAddr)) < voucherAmount) {
            return this.reply402(res);
        }
        channel.servedCount += 1;
        channel.authorizedSompi = voucherAmount.toString();
        channel.voucherHex = header.voucherHex;
        this.channels.set(header.clientPublic, channel);
        this.persist();
        res.setHeader("x-payment-authorized-sompi", channel.authorizedSompi);
        res.setHeader("x-payment-served", String(channel.servedCount));
        return false;
    }
    reply402(res) {
        res.statusCode = 402;
        res.setHeader("content-type", "application/json");
        res.end(JSON.stringify(this.offer()));
        return true;
    }
    /** Claim earned funds from one client's escrow using its latest voucher.
     *  Fee is estimated from the node unless overridden. */
    async claim(clientPublic, destination, feeSompi) {
        const channel = this.channels.get(clientPublic);
        if (!channel || channel.authorizedSompi === "0")
            throw new Error(`no vouchers from client ${clientPublic}`);
        const authorized = BigInt(channel.authorizedSompi);
        return (0, escrow_1.claimEscrow)(this.config.wallet(), this.params(clientPublic), this.config.serverPrivateHex, { amountSompi: authorized, voucherHex: channel.voucherHex }, authorized, destination, feeSompi);
    }
    /** Claim from every client with outstanding vouchers. */
    async claimAll(destination) {
        const out = [];
        for (const channel of this.channels.values()) {
            if (channel.authorizedSompi === "0")
                continue;
            const txid = await this.claim(channel.clientPublic, destination);
            out.push({ clientPublic: channel.clientPublic, txid, amountSompi: channel.authorizedSompi });
        }
        return out;
    }
    persist() {
        fs.writeFileSync(this.channelsPath, JSON.stringify([...this.channels.values()]), { mode: 0o600 });
    }
}
exports.EscrowTabServer = EscrowTabServer;
