"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.TestDatabaseHelper = void 0;
const database_js_1 = require("../utils/database.js");
const better_sqlite3_1 = __importDefault(require("better-sqlite3"));
const path = __importStar(require("path"));
const os = __importStar(require("os"));
const fs = __importStar(require("fs"));
/**
 * Test helper for managing database connections and cleanup
 */
class TestDatabaseHelper {
    static instances = [];
    static rawDatabases = [];
    /**
     * Create a test database with automatic cleanup tracking
     */
    static createTestDatabase() {
        const tempDbPath = path.join(os.tmpdir(), `test-db-${Date.now()}-${Math.random()}.db`);
        const dbManager = new database_js_1.DatabaseManager({ filename: tempDbPath });
        this.instances.push(dbManager);
        return dbManager;
    }
    /**
     * Create a raw database connection with automatic cleanup tracking
     */
    static createRawDatabase(filename) {
        const tempDbPath = filename || path.join(os.tmpdir(), `test-raw-db-${Date.now()}-${Math.random()}.db`);
        const db = new better_sqlite3_1.default(tempDbPath);
        this.rawDatabases.push(db);
        return db;
    }
    /**
     * Clean up all tracked database instances
     */
    static async cleanupAll() {
        // Close DatabaseManager instances
        await Promise.all(this.instances.map(async (db) => {
            try {
                db.close();
            }
            catch (error) {
                console.warn('Error closing DatabaseManager:', error);
            }
        }));
        // Close raw Database instances
        for (const db of this.rawDatabases) {
            try {
                if (db.open) {
                    db.close();
                }
            }
            catch (error) {
                console.warn('Error closing raw Database:', error);
            }
        }
        // Clean up temporary files
        this.instances = [];
        this.rawDatabases = [];
    }
    /**
     * Register a database for cleanup without creating it
     */
    static registerForCleanup(db) {
        if (db instanceof database_js_1.DatabaseManager) {
            this.instances.push(db);
        }
        else {
            this.rawDatabases.push(db);
        }
    }
    /**
     * Clean up WAL and SHM files for a database
     */
    static cleanupDbFiles(dbPath) {
        try {
            if (fs.existsSync(dbPath))
                fs.unlinkSync(dbPath);
            if (fs.existsSync(`${dbPath}-wal`))
                fs.unlinkSync(`${dbPath}-wal`);
            if (fs.existsSync(`${dbPath}-shm`))
                fs.unlinkSync(`${dbPath}-shm`);
        }
        catch (error) {
            console.warn('Error cleaning up database files:', error);
        }
    }
}
exports.TestDatabaseHelper = TestDatabaseHelper;
// Initialize global arrays
global.testDatabases = global.testDatabases || [];
global.testProcesses = global.testProcesses || [];
