"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.recordSwap = recordSwap;
exports.updateSwap = updateSwap;
exports.listSwaps = listSwaps;
exports.swapStats = swapStats;
const fs_1 = __importDefault(require("fs"));
const path_1 = __importDefault(require("path"));
const uuid_1 = require("uuid");
const base = process.env.DBIS_SWAP_MONITOR_DIR ||
    path_1.default.resolve(__dirname, '../../../data/dbis-exchange/swap-monitor');
function dir() {
    if (!fs_1.default.existsSync(base))
        fs_1.default.mkdirSync(base, { recursive: true });
    return base;
}
function recordSwap(entry) {
    const now = new Date().toISOString();
    const rec = { id: (0, uuid_1.v4)(), createdAt: now, updatedAt: now, ...entry };
    fs_1.default.writeFileSync(path_1.default.join(dir(), `${rec.id}.json`), JSON.stringify(rec, null, 2));
    return rec;
}
function updateSwap(id, patch) {
    const p = path_1.default.join(dir(), `${id}.json`);
    if (!fs_1.default.existsSync(p))
        return null;
    const rec = JSON.parse(fs_1.default.readFileSync(p, 'utf8'));
    const updated = { ...rec, ...patch, updatedAt: new Date().toISOString() };
    fs_1.default.writeFileSync(p, JSON.stringify(updated, null, 2));
    return updated;
}
function listSwaps(limit = 100) {
    return fs_1.default
        .readdirSync(dir())
        .filter((f) => f.endsWith('.json'))
        .slice(0, limit)
        .map((f) => JSON.parse(fs_1.default.readFileSync(path_1.default.join(dir(), f), 'utf8')))
        .sort((a, b) => b.createdAt.localeCompare(a.createdAt));
}
function swapStats() {
    const all = listSwaps(5000);
    const dayAgo = Date.now() - 86400000;
    return {
        total: all.length,
        confirmed: all.filter((s) => s.status === 'CONFIRMED').length,
        failed: all.filter((s) => s.status === 'FAILED').length,
        last24h: all.filter((s) => new Date(s.createdAt).getTime() > dayAgo).length,
    };
}
