"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 });
const globals_1 = require("@jest/globals");
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const os = __importStar(require("os"));
const better_sqlite3_1 = __importDefault(require("better-sqlite3"));
const database_1 = require("../../utils/database");
(0, globals_1.describe)('Database Initialization Tests', () => {
    let tempDir;
    let tempDbPath;
    (0, globals_1.beforeEach)(() => {
        tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'mcp-test-'));
        tempDbPath = path.join(tempDir, 'test.db');
    });
    (0, globals_1.afterEach)(() => {
        fs.rmSync(tempDir, { recursive: true, force: true });
    });
    (0, globals_1.it)('should create sessions table with working_directory column on fresh database', () => {
        const dbManager = new database_1.DatabaseManager({ filename: tempDbPath });
        const db = dbManager.getDatabase();
        // Check that sessions table has working_directory column
        const columns = db.prepare('PRAGMA table_info(sessions)').all();
        const columnNames = columns.map((col) => col.name);
        (0, globals_1.expect)(columnNames).toContain('working_directory');
        dbManager.close();
    });
    (0, globals_1.it)('should add working_directory column to existing database without it', () => {
        // Create database with old schema
        const db = new better_sqlite3_1.default(tempDbPath);
        db.exec(`
      CREATE TABLE sessions (
        id TEXT PRIMARY KEY,
        name TEXT,
        description TEXT,
        branch TEXT,
        parent_id TEXT,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
      );
    `);
        db.close();
        // Now open with DatabaseManager which should run migrations
        const dbManager = new database_1.DatabaseManager({ filename: tempDbPath });
        const migratedDb = dbManager.getDatabase();
        // Check that working_directory column was added
        const columns = migratedDb.prepare('PRAGMA table_info(sessions)').all();
        const columnNames = columns.map((col) => col.name);
        (0, globals_1.expect)(columnNames).toContain('working_directory');
        dbManager.close();
    });
    (0, globals_1.it)('should handle duplicate table creation gracefully', () => {
        const dbManager = new database_1.DatabaseManager({ filename: tempDbPath });
        const db = dbManager.getDatabase();
        // Try to create sessions table again (like the bug in index.ts)
        (0, globals_1.expect)(() => {
            db.exec(`
        CREATE TABLE sessions (
          id TEXT PRIMARY KEY,
          name TEXT,
          description TEXT,
          branch TEXT
        );
      `);
        }).toThrow(); // Should throw because table already exists
        // But CREATE TABLE IF NOT EXISTS should work
        (0, globals_1.expect)(() => {
            db.exec(`
        CREATE TABLE IF NOT EXISTS sessions (
          id TEXT PRIMARY KEY,
          name TEXT,
          description TEXT,
          branch TEXT
        );
      `);
        }).not.toThrow();
        // And the column should still be there
        const columns = db.prepare('PRAGMA table_info(sessions)').all();
        const columnNames = columns.map((col) => col.name);
        (0, globals_1.expect)(columnNames).toContain('working_directory');
        dbManager.close();
    });
    (0, globals_1.it)('should allow INSERT with working_directory column', () => {
        const dbManager = new database_1.DatabaseManager({ filename: tempDbPath });
        const db = dbManager.getDatabase();
        // This should work
        (0, globals_1.expect)(() => {
            db.prepare(`
        INSERT INTO sessions (id, name, description, branch, working_directory)
        VALUES (?, ?, ?, ?, ?)
      `).run('test-id', 'Test Session', 'Test Description', 'main', '/path/to/project');
        }).not.toThrow();
        // Verify the data
        const session = db.prepare('SELECT * FROM sessions WHERE id = ?').get('test-id');
        (0, globals_1.expect)(session.working_directory).toBe('/path/to/project');
        dbManager.close();
    });
});
