"use strict";
/**
 * LicenseStore — per-machine persistence for an activated OpenLife Business
 * license. Mirrors GovernanceConsentStore: atomic writes for the state file,
 * append-only JSONL for the audit trail.
 *
 * Files (both gitignored and excluded from the npm package):
 *   - `.openlife/license.json`         → the cached SignedLicense (or absent = Community)
 *   - `.openlife/license-events.jsonl` → activate / refresh / deactivate / expire events
 *
 * This store does NO verification — it only reads/writes bytes. Trust decisions
 * belong to LicenseManager so the two concerns stay testable in isolation.
 */
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.LicenseStore = void 0;
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const AtomicWriter_1 = require("./util/AtomicWriter");
class LicenseStore {
    root;
    licenseFile;
    eventsFile;
    constructor(root = process.cwd()) {
        this.root = root;
        const dir = path.join(this.root, '.openlife');
        this.licenseFile = path.join(dir, 'license.json');
        this.eventsFile = path.join(dir, 'license-events.jsonl');
        fs.mkdirSync(dir, { recursive: true });
    }
    /** The cached signed license, or null when none is activated (Community). */
    current() {
        if (!fs.existsSync(this.licenseFile))
            return null;
        try {
            return JSON.parse(fs.readFileSync(this.licenseFile, 'utf-8'));
        }
        catch {
            return null;
        }
    }
    /** Persist an activated/refreshed license and record an audit event. */
    save(token, type = 'activate') {
        (0, AtomicWriter_1.writeJsonAtomic)(this.licenseFile, token);
        this.appendEvent({
            type,
            keyId: token.payload.keyId,
            tier: token.payload.tier,
            at: new Date().toISOString(),
        });
    }
    /** Remove the cached license (revert to Community) and record the event. */
    clear(note) {
        const prev = this.current();
        if (fs.existsSync(this.licenseFile))
            fs.rmSync(this.licenseFile);
        this.appendEvent({
            type: 'deactivate',
            keyId: prev?.payload.keyId,
            tier: prev?.payload.tier,
            at: new Date().toISOString(),
            note,
        });
    }
    /** Append one line to the audit trail. */
    appendEvent(event) {
        (0, AtomicWriter_1.appendJsonlAtomic)(this.eventsFile, event);
    }
    /** Full audit trail, oldest first. Empty when none exists. */
    events() {
        if (!fs.existsSync(this.eventsFile))
            return [];
        return fs
            .readFileSync(this.eventsFile, 'utf-8')
            .split('\n')
            .filter((l) => l.trim().length > 0)
            .map((l) => JSON.parse(l));
    }
}
exports.LicenseStore = LicenseStore;
