import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
import { dirname, join } from 'node:path';
import { randomUUID } from 'node:crypto';
import { config } from '../config.js';
function storePath(dataDir = config.session.dataDir) {
    return join(dataDir, 'connectors.json');
}
function emptyStore() {
    return { version: 1, connectors: [] };
}
function normalizeStore(raw) {
    if (!raw || typeof raw !== 'object' || Array.isArray(raw))
        return emptyStore();
    const r = raw;
    return {
        version: 1,
        connectors: Array.isArray(r.connectors)
            ? r.connectors.filter((c) => !!c && typeof c === 'object' && typeof c.id === 'string')
            : [],
    };
}
export function readConnectorStore(dataDir = config.session.dataDir) {
    const fp = storePath(dataDir);
    if (!existsSync(fp))
        return emptyStore();
    try {
        return normalizeStore(JSON.parse(readFileSync(fp, 'utf-8')));
    }
    catch {
        return emptyStore();
    }
}
function writeConnectorStore(dataDir, store) {
    const fp = storePath(dataDir);
    mkdirSync(dirname(fp), { recursive: true });
    const tmp = `${fp}.${process.pid}.${randomUUID()}.tmp`;
    writeFileSync(tmp, JSON.stringify(normalizeStore(store), null, 2) + '\n', { encoding: 'utf-8', mode: 0o600 });
    renameSync(tmp, fp);
}
export function listConnectors(dataDir = config.session.dataDir) {
    return readConnectorStore(dataDir).connectors;
}
export function getConnector(id, dataDir = config.session.dataDir) {
    if (!id)
        return null;
    return listConnectors(dataDir).find(c => c.id === id) ?? null;
}
export function upsertConnector(connector, dataDir = config.session.dataDir) {
    if (!connector.id)
        throw new Error('connector id is required');
    const now = new Date().toISOString();
    const store = readConnectorStore(dataDir);
    const idx = store.connectors.findIndex(c => c.id === connector.id);
    const prior = idx >= 0 ? store.connectors[idx] : undefined;
    const next = {
        ...connector,
        createdAt: connector.createdAt || prior?.createdAt || now,
        updatedAt: now,
    };
    if (idx >= 0)
        store.connectors[idx] = next;
    else
        store.connectors.push(next);
    writeConnectorStore(dataDir, store);
    return next;
}
export function deleteConnector(id, dataDir = config.session.dataDir) {
    const store = readConnectorStore(dataDir);
    const before = store.connectors.length;
    store.connectors = store.connectors.filter(c => c.id !== id);
    if (store.connectors.length === before)
        return false;
    writeConnectorStore(dataDir, store);
    return true;
}
export function newConnectorId() {
    return `conn_${randomUUID()}`;
}
//# sourceMappingURL=connector-store.js.map