import Database from 'better-sqlite3';
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { runMigrations } from './migrations.js';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
let db = null;
/** Migrate DB from old location (server/data/) to new location (.expxagents/data/) */
function migrateOldDb(newDbPath) {
    if (fs.existsSync(newDbPath))
        return; // new DB already exists
    // Old location: server/data/opensquad.db (relative to this file's __dirname)
    const oldDbPath = path.join(__dirname, '..', 'data', 'opensquad.db');
    if (!fs.existsSync(oldDbPath))
        return; // no old DB to migrate
    try {
        fs.copyFileSync(oldDbPath, newDbPath);
        console.log(`[db] Migrated database from ${oldDbPath} to ${newDbPath}`);
    }
    catch (err) {
        console.warn(`[db] Failed to migrate old database: ${err}`);
    }
}
export function getDb(dataDir) {
    if (db)
        return db;
    fs.mkdirSync(dataDir, { recursive: true });
    const dbPath = path.join(dataDir, 'opensquad.db');
    migrateOldDb(dbPath);
    db = new Database(dbPath);
    runMigrations(db);
    return db;
}
export function closeDb() {
    if (db) {
        db.close();
        db = null;
    }
}
//# sourceMappingURL=connection.js.map