"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 database_1 = require("../../utils/database");
const RepositoryManager_1 = require("../../repositories/RepositoryManager");
const os = __importStar(require("os"));
const path = __importStar(require("path"));
const fs = __importStar(require("fs"));
(0, globals_1.describe)('Backward Compatibility Tests', () => {
    let dbManager;
    let tempDbPath;
    let repositories;
    let testSessionId;
    let _server;
    // Mock handler function to test actual handler logic
    async function callContextGet(args) {
        // This simulates the actual handler logic from index.ts
        const { key, category, channel, channels, sessionId: specificSessionId, includeMetadata, sort, limit, offset, createdAfter, createdBefore, keyPattern, priorities, } = args;
        const targetSessionId = specificSessionId || testSessionId;
        // Use enhanced query for complex queries or when we need pagination
        if (sort !== undefined ||
            limit !== undefined ||
            offset ||
            createdAfter ||
            createdBefore ||
            keyPattern ||
            priorities ||
            channel ||
            channels ||
            includeMetadata ||
            (!key && !category) // If listing all items without filters, use pagination
        ) {
            const result = repositories.contexts.queryEnhanced({
                sessionId: targetSessionId,
                key,
                category,
                channel,
                channels,
                sort,
                limit,
                offset,
                createdAfter,
                createdBefore,
                keyPattern,
                priorities,
                includeMetadata,
            });
            if (result.items.length === 0) {
                return { content: [{ type: 'text', text: 'No matching context found' }] };
            }
            // Return enhanced format
            const response = {
                items: result.items,
                pagination: {
                    total: result.totalCount,
                    returned: result.items.length,
                    offset: offset || 0,
                    hasMore: false, // Simplified for test
                    nextOffset: null,
                },
            };
            return {
                content: [{ type: 'text', text: JSON.stringify(response, null, 2) }],
            };
        }
        // Backward compatible simple queries
        let rows;
        if (key) {
            const item = repositories.contexts.getAccessibleByKey(targetSessionId, key);
            rows = item ? [item] : [];
        }
        else {
            rows = repositories.contexts.getAccessibleItems(targetSessionId, { category });
        }
        if (rows.length === 0) {
            return { content: [{ type: 'text', text: 'No matching context found' }] };
        }
        if (key && rows.length === 1) {
            // Single item requested - return just the value
            const item = rows[0];
            return { content: [{ type: 'text', text: item.value }] };
        }
        // Multiple items - return formatted list
        const items = rows
            .map((r) => `• [${r.priority}] ${r.key}: ${r.value.substring(0, 100)}${r.value.length > 100 ? '...' : ''}`)
            .join('\n');
        return {
            content: [{ type: 'text', text: `Found ${rows.length} context items:\n\n${items}` }],
        };
    }
    (0, globals_1.beforeEach)(() => {
        tempDbPath = path.join(os.tmpdir(), `test-backward-compat-${Date.now()}.db`);
        dbManager = new database_1.DatabaseManager({
            filename: tempDbPath,
            maxSize: 10 * 1024 * 1024,
            walMode: true,
        });
        repositories = new RepositoryManager_1.RepositoryManager(dbManager);
        // Create test session
        const session = repositories.sessions.create({ name: 'Test Session' });
        testSessionId = session.id;
        // Create test data
        repositories.contexts.save(testSessionId, {
            key: 'single.item',
            value: 'This is a single item value',
            category: 'test',
            priority: 'normal',
        });
        repositories.contexts.save(testSessionId, {
            key: 'category.item1',
            value: 'Category test item 1',
            category: 'testcat',
            priority: 'high',
        });
        repositories.contexts.save(testSessionId, {
            key: 'category.item2',
            value: 'Category test item 2',
            category: 'testcat',
            priority: 'normal',
        });
        // Create many items to test pagination
        for (let i = 0; i < 150; i++) {
            repositories.contexts.save(testSessionId, {
                key: `bulk.item.${i.toString().padStart(3, '0')}`,
                value: `Bulk item value ${i}`,
                category: 'bulk',
                priority: i % 2 === 0 ? 'high' : 'normal',
            });
        }
    });
    (0, globals_1.afterEach)(() => {
        dbManager.close();
        try {
            fs.unlinkSync(tempDbPath);
            fs.unlinkSync(`${tempDbPath}-wal`);
            fs.unlinkSync(`${tempDbPath}-shm`);
        }
        catch (_e) {
            // Ignore
        }
    });
    (0, globals_1.describe)('Single Item Retrieval (Backward Compatible)', () => {
        (0, globals_1.it)('should return just the value for single item by key', async () => {
            const result = await callContextGet({ key: 'single.item' });
            (0, globals_1.expect)(result.content[0].text).toBe('This is a single item value');
            // Should NOT include pagination or JSON structure
            (0, globals_1.expect)(result.content[0].text).not.toContain('pagination');
            (0, globals_1.expect)(result.content[0].text).not.toContain('{');
        });
        (0, globals_1.it)('should return "No matching context found" for non-existent key', async () => {
            const result = await callContextGet({ key: 'non.existent' });
            (0, globals_1.expect)(result.content[0].text).toBe('No matching context found');
        });
    });
    (0, globals_1.describe)('Category Filtering (Backward Compatible)', () => {
        (0, globals_1.it)('should return formatted list for category filter only', async () => {
            const result = await callContextGet({ category: 'testcat' });
            (0, globals_1.expect)(result.content[0].text).toContain('Found 2 context items:');
            (0, globals_1.expect)(result.content[0].text).toContain('• [high] category.item1:');
            (0, globals_1.expect)(result.content[0].text).toContain('• [normal] category.item2:');
            // Should NOT include pagination
            (0, globals_1.expect)(result.content[0].text).not.toContain('pagination');
        });
    });
    (0, globals_1.describe)('Enhanced Queries (New Format)', () => {
        (0, globals_1.it)('should return paginated format when listing all items', async () => {
            const result = await callContextGet({});
            const parsed = JSON.parse(result.content[0].text);
            (0, globals_1.expect)(parsed).toHaveProperty('items');
            (0, globals_1.expect)(parsed).toHaveProperty('pagination');
            (0, globals_1.expect)(parsed.pagination.total).toBe(153); // All test items
            (0, globals_1.expect)(parsed.pagination.returned).toBe(100); // Default limit
        });
        (0, globals_1.it)('should return paginated format when using limit', async () => {
            const result = await callContextGet({ category: 'bulk', limit: 10 });
            const parsed = JSON.parse(result.content[0].text);
            (0, globals_1.expect)(parsed).toHaveProperty('items');
            (0, globals_1.expect)(parsed).toHaveProperty('pagination');
            (0, globals_1.expect)(parsed.items).toHaveLength(10);
            (0, globals_1.expect)(parsed.pagination.returned).toBe(10);
        });
        (0, globals_1.it)('should return paginated format when using sort', async () => {
            const result = await callContextGet({ category: 'bulk', sort: 'key_asc' });
            const parsed = JSON.parse(result.content[0].text);
            (0, globals_1.expect)(parsed).toHaveProperty('items');
            (0, globals_1.expect)(parsed).toHaveProperty('pagination');
            (0, globals_1.expect)(parsed.items[0].key).toBe('bulk.item.000');
        });
        (0, globals_1.it)('should return paginated format when using includeMetadata', async () => {
            const result = await callContextGet({ key: 'single.item', includeMetadata: true });
            const parsed = JSON.parse(result.content[0].text);
            (0, globals_1.expect)(parsed).toHaveProperty('items');
            (0, globals_1.expect)(parsed).toHaveProperty('pagination');
            (0, globals_1.expect)(parsed.items).toHaveLength(1);
            (0, globals_1.expect)(parsed.items[0]).toHaveProperty('size');
            (0, globals_1.expect)(parsed.items[0]).toHaveProperty('created_at');
        });
    });
    (0, globals_1.describe)('Mixed Scenarios', () => {
        (0, globals_1.it)('should use simple format for key+category filter', async () => {
            // Even with both key and category, if key is specified, use simple format
            const result = await callContextGet({ key: 'single.item', category: 'test' });
            (0, globals_1.expect)(result.content[0].text).toBe('This is a single item value');
            (0, globals_1.expect)(result.content[0].text).not.toContain('pagination');
        });
        (0, globals_1.it)('should use enhanced format when channel is specified', async () => {
            const result = await callContextGet({ category: 'test', channel: 'general' });
            const parsed = JSON.parse(result.content[0].text);
            (0, globals_1.expect)(parsed).toHaveProperty('pagination');
        });
    });
});
