import Database from 'better-sqlite3';
import { chmodSync, existsSync } from 'fs';
let db = null;
export function initDb(dbPath) {
    const isNew = !existsSync(dbPath);
    db = new Database(dbPath);
    db.pragma('journal_mode = WAL');
    db.pragma('foreign_keys = ON');
    db.pragma('busy_timeout = 5000');
    // SEC: Restrict database file permissions to owner-only (mode 600).
    // The license database contains user records, keys, and balances.
    // SQLite creates files with default umask (often 644), which would allow
    // any process in the container to read sensitive billing data.
    // Also restrict the WAL and SHM journal files if they exist.
    try {
        chmodSync(dbPath, 0o600);
        if (existsSync(`${dbPath}-wal`))
            chmodSync(`${dbPath}-wal`, 0o600);
        if (existsSync(`${dbPath}-shm`))
            chmodSync(`${dbPath}-shm`, 0o600);
        if (isNew) {
            console.error(`[DB] Created ${dbPath} with restricted permissions (mode 600)`);
        }
    }
    catch {
        // Non-fatal: permission change may fail on read-only filesystems or
        // when running as a different user. Log but continue.
        console.error(`[DB] WARN: Could not set restrictive permissions on ${dbPath}`);
    }
}
export function getDb() {
    if (!db)
        throw new Error('Database not initialized. Call initDb() first.');
    return db;
}
/**
 * Execute a SQL query with compatible interface.
 * Returns { rows: T[], rowCount: number }.
 * Detects SELECT/WITH/RETURNING to use .all(), otherwise .run().
 */
export function query(sql, params) {
    const stmt = getDb().prepare(sql);
    const isRead = /^\s*(SELECT|WITH)\b/i.test(sql) || /\bRETURNING\b/i.test(sql);
    if (isRead) {
        const rows = (params ? stmt.all(...params) : stmt.all());
        return { rows, rowCount: rows.length };
    }
    const result = params ? stmt.run(...params) : stmt.run();
    return { rows: [], rowCount: result.changes };
}
export function withTransaction(fn) {
    const transaction = getDb().transaction(fn);
    return transaction();
}
export function closeDb() {
    if (db) {
        db.close();
        db = null;
    }
}
//# sourceMappingURL=db.js.map