"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;
    };
})();
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 database_1 = require("../../utils/database");
const validation_1 = require("../../utils/validation");
(0, globals_1.describe)('Security - Input Validation Tests', () => {
    let tempDir;
    let dbManager;
    (0, globals_1.beforeEach)(() => {
        tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'mcp-test-'));
        const tempDbPath = path.join(tempDir, 'test.db');
        dbManager = new database_1.DatabaseManager({
            filename: tempDbPath,
            walMode: false,
        });
    });
    (0, globals_1.afterEach)(() => {
        dbManager.close();
        fs.rmSync(tempDir, { recursive: true, force: true });
    });
    (0, globals_1.describe)('Basic SQL Injection Prevention', () => {
        (0, globals_1.it)('should prevent SQL injection in key parameter', () => {
            const db = dbManager.getDatabase();
            const sessionId = 'test-session';
            db.prepare('INSERT INTO sessions (id, name) VALUES (?, ?)').run(sessionId, 'Test');
            const maliciousKey = "key'; DROP TABLE sessions; --";
            db.prepare(`
        INSERT INTO context_items (id, session_id, key, value, category, priority)
        VALUES (?, ?, ?, ?, ?, ?)
      `).run('item-1', sessionId, maliciousKey, 'value', 'test', 'normal');
            const tables = db
                .prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='sessions'")
                .all();
            (0, globals_1.expect)(tables.length).toBe(1);
            const item = db.prepare('SELECT key FROM context_items WHERE id = ?').get('item-1');
            (0, globals_1.expect)(item.key).toBe(maliciousKey);
        });
        (0, globals_1.it)('should sanitize search queries', () => {
            const maliciousQuery = "test' OR '1'='1";
            const validatedQuery = (0, validation_1.validateSearchQuery)(maliciousQuery);
            (0, globals_1.expect)(validatedQuery).toBe('test OR 1=1');
        });
    });
    (0, globals_1.describe)('Basic Validation', () => {
        (0, globals_1.it)('should validate keys', () => {
            (0, globals_1.expect)(() => (0, validation_1.validateKey)('')).toThrow();
            (0, globals_1.expect)(() => (0, validation_1.validateKey)('valid-key')).not.toThrow();
        });
        (0, globals_1.it)('should validate values', () => {
            (0, globals_1.expect)(() => (0, validation_1.validateValue)('valid value')).not.toThrow();
            // Empty values might be allowed, so just test that function exists
            (0, globals_1.expect)(typeof validation_1.validateValue).toBe('function');
        });
    });
    (0, globals_1.describe)('Resource Management', () => {
        (0, globals_1.it)('should handle small bulk operations', () => {
            const db = dbManager.getDatabase();
            const sessionId = 'test-session';
            db.prepare('INSERT INTO sessions (id, name) VALUES (?, ?)').run(sessionId, 'Test');
            const insertStmt = db.prepare(`
        INSERT INTO context_items (id, session_id, key, value, category, priority)
        VALUES (?, ?, ?, ?, ?, ?)
      `);
            const insertMany = db.transaction(() => {
                for (let i = 0; i < 5; i++) {
                    insertStmt.run(`bulk-${i}`, sessionId, `key-${i}`, `value-${i}`, 'test', 'normal');
                }
            });
            const start = Date.now();
            insertMany();
            const elapsed = Date.now() - start;
            (0, globals_1.expect)(elapsed).toBeLessThan(1000);
            const count = db
                .prepare('SELECT COUNT(*) as count FROM context_items WHERE session_id = ?')
                .get(sessionId);
            (0, globals_1.expect)(count.count).toBe(5);
        });
    });
});
