"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.encryptedKeyStore = exports.EncryptedKeyStore = void 0;
const path_1 = require("path");
const config_js_1 = require("../../utils/config.js");
const crypto_js_1 = require("../../utils/crypto.js");
const logger_js_1 = require("../../utils/logger.js");
const file_ops_js_1 = require("./file-ops.js");
const log = (0, logger_js_1.createModuleLogger)('encrypted-store');
class EncryptedKeyStore {
    filePath;
    masterKey;
    constructor(dataDir, masterKey) {
        const dir = dataDir || config_js_1.config.dataDir;
        this.filePath = (0, path_1.resolve)(dir, 'config', 'api-keys.enc.json');
        this.masterKey = masterKey ?? config_js_1.config.encryptionKey;
    }
    async init() {
        await (0, file_ops_js_1.ensureDir)((0, path_1.resolve)(this.filePath, '..'));
        const existing = await (0, file_ops_js_1.readJSON)(this.filePath);
        if (!existing) {
            await (0, file_ops_js_1.atomicWriteJSON)(this.filePath, { version: 1, keys: {} });
        }
    }
    async setKey(name, value) {
        if (!this.masterKey)
            throw new Error('ENCRYPTION_KEY is not configured');
        const store = await this.loadStore();
        const now = new Date().toISOString();
        store.keys[name] = {
            encrypted: (0, crypto_js_1.encrypt)(value, this.masterKey),
            createdAt: store.keys[name]?.createdAt || now,
            updatedAt: now,
        };
        await (0, file_ops_js_1.atomicWriteJSON)(this.filePath, store);
        log.info({ name }, 'Key saved');
    }
    async getKey(name) {
        if (!this.masterKey)
            throw new Error('ENCRYPTION_KEY is not configured');
        const store = await this.loadStore();
        const entry = store.keys[name];
        if (!entry)
            return null;
        return (0, crypto_js_1.decrypt)(entry.encrypted, this.masterKey);
    }
    async deleteKey(name) {
        const store = await this.loadStore();
        if (!store.keys[name])
            return false;
        delete store.keys[name];
        await (0, file_ops_js_1.atomicWriteJSON)(this.filePath, store);
        log.info({ name }, 'Key deleted');
        return true;
    }
    async listKeys() {
        if (!this.masterKey)
            throw new Error('ENCRYPTION_KEY is not configured');
        const store = await this.loadStore();
        const result = [];
        for (const [name, entry] of Object.entries(store.keys)) {
            try {
                const value = (0, crypto_js_1.decrypt)(entry.encrypted, this.masterKey);
                const masked = value.length > 4 ? '****' + value.slice(-4) : '****';
                result.push({ name, maskedValue: masked, createdAt: entry.createdAt, updatedAt: entry.updatedAt });
            }
            catch {
                result.push({ name, maskedValue: '****[decrypt error]', createdAt: entry.createdAt, updatedAt: entry.updatedAt });
            }
        }
        return result;
    }
    async hasKey(name) {
        const store = await this.loadStore();
        return name in store.keys;
    }
    async loadStore() {
        const store = await (0, file_ops_js_1.readJSON)(this.filePath);
        return store || { version: 1, keys: {} };
    }
}
exports.EncryptedKeyStore = EncryptedKeyStore;
exports.encryptedKeyStore = new EncryptedKeyStore();
//# sourceMappingURL=encryption.js.map