"use strict";
/**
 * Database instance singleton
 * Provides a shared database connection for API routes
 *
 * Issue #135: DB path resolution fix
 * Uses getEnv().CM_DB_PATH for consistent path handling across all install types
 */
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getDbInstance = getDbInstance;
exports.closeDbInstance = closeDbInstance;
const better_sqlite3_1 = __importDefault(require("better-sqlite3"));
const path_1 = __importDefault(require("path"));
const db_migrations_1 = require("./db-migrations");
const env_1 = require("../../lib/env");
let dbInstance = null;
/**
 * Get or create the database instance
 *
 * Issue #135: Now uses getEnv().CM_DB_PATH instead of direct DATABASE_PATH access
 * This ensures consistent DB path resolution for both global and local installs.
 *
 * @returns Singleton database instance
 *
 * @example
 * ```typescript
 * const db = getDbInstance();
 * const worktrees = getWorktrees(db);
 * ```
 */
function getDbInstance() {
    if (!dbInstance) {
        // Issue #135: Use getEnv() for consistent DB path resolution
        const env = (0, env_1.getEnv)();
        const dbPath = env.CM_DB_PATH;
        // Ensure the database directory exists
        // eslint-disable-next-line @typescript-eslint/no-require-imports
        const fs = require('fs');
        const dir = path_1.default.dirname(dbPath);
        if (!fs.existsSync(dir)) {
            // SEC-003: Set directory permissions to 0o700 (owner only)
            fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
        }
        dbInstance = new better_sqlite3_1.default(dbPath);
        // Issue #294: Enable foreign key enforcement BEFORE migrations
        // This ensures ON DELETE CASCADE works correctly for all tables
        dbInstance.pragma('foreign_keys = ON');
        (0, db_migrations_1.runMigrations)(dbInstance);
    }
    return dbInstance;
}
/**
 * Close the database connection
 * Mainly used for testing cleanup
 */
function closeDbInstance() {
    if (dbInstance) {
        dbInstance.close();
        dbInstance = null;
    }
}
