import Database from "better-sqlite3";
import { getDbPath } from "../utils/paths.js";
import { runMigrations, getSchemaVersion } from "./migrator.js";
import { migrations } from "./migrations.js";
let _db = null;
/**
 * Opens (or creates) the SQLite database at the daemon.db path,
 * enables WAL mode and foreign keys, and runs pending migrations.
 *
 * Returns the same instance on subsequent calls (singleton).
 */
export function openDatabase(dbPath) {
    if (_db)
        return _db;
    const path = dbPath ?? getDbPath();
    const db = new Database(path);
    // Enable WAL for better concurrent read performance
    db.pragma("journal_mode = WAL");
    // Enable foreign key enforcement
    db.pragma("foreign_keys = ON");
    runMigrations(db, migrations);
    _db = db;
    return db;
}
/**
 * Closes the database connection and resets the singleton.
 */
export function closeDatabase() {
    if (_db) {
        _db.close();
        _db = null;
    }
}
/**
 * Returns the current schema version from the _migrations table or user_version pragma.
 */
export function getDatabaseVersion(db) {
    return getSchemaVersion(db);
}
export { Database };
//# sourceMappingURL=database.js.map