"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.settlementStore = exports.SettlementStore = void 0;
const fs_1 = __importDefault(require("fs"));
const path_1 = __importDefault(require("path"));
const config_1 = require("../config");
const baseDir = process.env.SETTLEMENT_STORE_DIR ||
    path_1.default.resolve(__dirname, '../../../data/settlement-store');
function storeDir() {
    const dir = path_1.default.join(baseDir, (0, config_1.settlementStoreSubdir)());
    if (!fs_1.default.existsSync(dir))
        fs_1.default.mkdirSync(dir, { recursive: true });
    return dir;
}
class SettlementStore {
    save(record) {
        const dir = storeDir();
        fs_1.default.writeFileSync(path_1.default.join(dir, `${record.settlementId}.json`), JSON.stringify(record, null, 2));
        fs_1.default.writeFileSync(path_1.default.join(dir, `key-${record.idempotencyKey}.json`), record.settlementId);
    }
    getById(id) {
        const p = path_1.default.join(storeDir(), `${id}.json`);
        if (!fs_1.default.existsSync(p))
            return null;
        return JSON.parse(fs_1.default.readFileSync(p, 'utf8'));
    }
    getByIdempotencyKey(key) {
        const ref = path_1.default.join(storeDir(), `key-${key}.json`);
        if (!fs_1.default.existsSync(ref))
            return null;
        const id = fs_1.default.readFileSync(ref, 'utf8').trim();
        return this.getById(id);
    }
    list(limit = 50) {
        const dir = storeDir();
        return fs_1.default
            .readdirSync(dir)
            .filter((f) => f.endsWith('.json') && !f.startsWith('key-'))
            .slice(0, limit)
            .map((f) => JSON.parse(fs_1.default.readFileSync(path_1.default.join(dir, f), 'utf8')));
    }
}
exports.SettlementStore = SettlementStore;
exports.settlementStore = new SettlementStore();
