import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
import { dirname, join } from 'node:path';
import { decryptJson, encryptJson } from '../middleware/crypto.js';
const DEFAULT_CONFIG = {
    pushAnalysisEnabled: true,
    pullRequestAnalysisEnabled: true,
    fast: false,
    incrementalOnPush: true
};
function storePath() {
    const base = process.env.TUTANUS_DATA_DIR || join(process.cwd(), '.tutanus-data');
    return join(base, 'installations.json');
}
function isStringRecord(val) {
    if (typeof val !== 'object' || val === null)
        return false;
    return Object.values(val).every(v => typeof v === 'string');
}
function isInstallationConfig(val) {
    if (typeof val !== 'object' || val === null)
        return false;
    const v = val;
    return typeof v.installationId === 'number' && typeof v.updatedAt === 'number';
}
function loadAll() {
    const path = storePath();
    if (!existsSync(path))
        return {};
    try {
        const raw = readFileSync(path, 'utf-8');
        const parsed = JSON.parse(raw);
        if (!isStringRecord(parsed))
            return {};
        const result = {};
        for (const [key, val] of Object.entries(parsed)) {
            try {
                const decrypted = decryptJson(val);
                if (isInstallationConfig(decrypted)) {
                    result[key] = decrypted;
                }
            }
            catch {
                try {
                    const fallback = JSON.parse(val);
                    if (isInstallationConfig(fallback)) {
                        result[key] = fallback;
                    }
                }
                catch {
                    return {};
                }
            }
        }
        return result;
    }
    catch {
        return {};
    }
}
function saveAll(data) {
    const path = storePath();
    mkdirSync(dirname(path), { recursive: true });
    const encrypted = {};
    for (const [key, val] of Object.entries(data)) {
        encrypted[key] = encryptJson(val);
    }
    writeFileSync(path, JSON.stringify(encrypted, null, 2), 'utf-8');
}
export function obterConfigInstalacao(installationId) {
    const all = loadAll();
    const key = String(installationId);
    return all[key] ?? {
        installationId,
        ...DEFAULT_CONFIG,
        updatedAt: Date.now()
    };
}
export function salvarConfigInstalacao(partial) {
    const all = loadAll();
    const key = String(partial.installationId);
    const atual = all[key] ?? {
        installationId: partial.installationId,
        ...DEFAULT_CONFIG,
        updatedAt: Date.now()
    };
    const merged = {
        ...atual,
        ...partial,
        installationId: partial.installationId,
        updatedAt: Date.now()
    };
    all[key] = merged;
    saveAll(all);
    return merged;
}
export function listarConfigsInstalacao() {
    return Object.values(loadAll()).sort((a, b) => b.updatedAt - a.updatedAt);
}
//# sourceMappingURL=installation-store.js.map