"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const database_1 = require("../walls/06-memory/database/database");
const TEST_PROJECT = 'test-sync';
describe('Sync Engine', () => {
    beforeAll(() => {
        const db = (0, database_1.getDb)();
        db.prepare('DELETE FROM memory_events WHERE project = ?').run(TEST_PROJECT);
        db.prepare('DELETE FROM sync_state WHERE project = ?').run(TEST_PROJECT);
        db.prepare('DELETE FROM sync_conflicts WHERE project = ?').run(TEST_PROJECT);
    });
    test('exportMemory creates encrypted payload', () => {
        const { exportMemory } = require('../walls/06-memory/stores/sync-engine');
        const payload = exportMemory(TEST_PROJECT);
        expect(payload.version).toBe(1);
        expect(payload.algorithm).toBe('aes-256-gcm');
        expect(payload.project).toBe(TEST_PROJECT);
        expect(payload.checksum).toBeTruthy();
        expect(payload.encryptedData).toBeTruthy();
        expect(payload.iv).toBeTruthy();
        expect(payload.tag).toBeTruthy();
        expect(payload.eventCount).toBeGreaterThanOrEqual(0);
    });
    test('exportMemory captures events', () => {
        const db = (0, database_1.getDb)();
        db.prepare(`INSERT INTO memory_events (project, type, topic, summary, importance, created_at)
      VALUES (?, 'verification', 'test', 'sync test event', 5, datetime('now'))`).run(TEST_PROJECT);
        const { exportMemory } = require('../walls/06-memory/stores/sync-engine');
        const payload = exportMemory(TEST_PROJECT);
        expect(payload.eventCount).toBeGreaterThanOrEqual(1);
    });
    test('importMemory restores events', () => {
        const { exportMemory, importMemory } = require('../walls/06-memory/stores/sync-engine');
        const payload = exportMemory(TEST_PROJECT);
        const targetProject = 'test-sync-import';
        const db = (0, database_1.getDb)();
        db.prepare('DELETE FROM memory_events WHERE project = ?').run(targetProject);
        const result = importMemory(payload, targetProject);
        expect(result.errors.length).toBe(0);
        expect(result.added).toBeGreaterThanOrEqual(1);
        const imported = db.prepare('SELECT COUNT(*) as c FROM memory_events WHERE project = ?').get(targetProject);
        expect(imported.c).toBeGreaterThanOrEqual(1);
        db.prepare('DELETE FROM memory_events WHERE project = ?').run(targetProject);
    });
    test('computeDiff handles empty remote', () => {
        const { exportMemory, computeDiff } = require('../walls/06-memory/stores/sync-engine');
        const remote = exportMemory('nonexistent-project');
        const diff = computeDiff(TEST_PROJECT, remote);
        expect(Array.isArray(diff.localOnly)).toBe(true);
        expect(Array.isArray(diff.remoteOnly)).toBe(true);
        expect(Array.isArray(diff.conflicts)).toBe(true);
        expect(diff.bothPresent).toBe(0);
    });
    test('resolveConflicts with local-wins strategy', () => {
        const { resolveConflicts } = require('../walls/06-memory/stores/sync-engine');
        const conflicts = [
            { eventId: 1, localSummary: 'a', remoteSummary: 'b', localTimestamp: '2024-01-01', remoteTimestamp: '2024-01-02', localImportance: 5, remoteImportance: 3, resolved: false },
        ];
        const resolved = resolveConflicts(conflicts, 'local-wins');
        expect(resolved[0].resolved).toBe(true);
        expect(resolved[0].resolution).toBe('local-wins');
    });
    test('resolveConflicts with importance strategy', () => {
        const { resolveConflicts } = require('../walls/06-memory/stores/sync-engine');
        const conflicts = [
            { eventId: 2, localSummary: 'low', remoteSummary: 'high', localTimestamp: '2024-01-01', remoteTimestamp: '2024-01-01', localImportance: 3, remoteImportance: 8, resolved: false },
        ];
        const resolved = resolveConflicts(conflicts, 'importance');
        expect(resolved[0].resolution).toBe('remote-wins');
    });
    test('resolveConflicts with timestamp strategy', () => {
        const { resolveConflicts } = require('../walls/06-memory/stores/sync-engine');
        const conflicts = [
            { eventId: 3, localSummary: 'old', remoteSummary: 'new', localTimestamp: '2024-01-01', remoteTimestamp: '2024-06-01', localImportance: 5, remoteImportance: 5, resolved: false },
        ];
        const resolved = resolveConflicts(conflicts, 'timestamp');
        expect(resolved[0].resolution).toBe('remote-wins');
    });
    test('getSyncStatus returns valid status', () => {
        const { getSyncStatus } = require('../walls/06-memory/stores/sync-engine');
        const status = getSyncStatus(TEST_PROJECT);
        expect(status).toHaveProperty('lastSyncAt');
        expect(status).toHaveProperty('pendingUpload');
        expect(status).toHaveProperty('conflicts');
        expect(status).toHaveProperty('encryptionKeySet');
        expect(typeof status.encryptionKeySet).toBe('boolean');
    });
    test('saveSyncSnapshot creates sync state record', () => {
        const { saveSyncSnapshot, getLatestSnapshot } = require('../walls/06-memory/stores/sync-engine');
        saveSyncSnapshot(TEST_PROJECT);
        const snapshot = getLatestSnapshot(TEST_PROJECT);
        expect(snapshot).not.toBeNull();
        expect(snapshot.project).toBe(TEST_PROJECT);
        expect(snapshot.checksum).toBeTruthy();
        expect(snapshot.eventIds.length).toBeGreaterThanOrEqual(1);
    });
    test('markEventsSynced updates synced flag', () => {
        const db = (0, database_1.getDb)();
        const { markEventsSynced, getUnsyncedEvents } = require('../walls/06-memory/stores/sync-engine');
        const unsynced = getUnsyncedEvents(TEST_PROJECT, 5);
        if (unsynced.length > 0) {
            const ids = unsynced.map((e) => e.id);
            markEventsSynced(ids);
            const stillUnsynced = getUnsyncedEvents(TEST_PROJECT, 5);
            const remaining = stillUnsynced.filter((e) => ids.includes(e.id));
            expect(remaining.length).toBe(0);
        }
    });
    test('importMemory with corrupted payload returns errors', () => {
        const { importMemory } = require('../walls/06-memory/stores/sync-engine');
        const corrupted = {
            version: 1,
            algorithm: 'aes-256-gcm',
            project: 'corrupt',
            timestamp: new Date().toISOString(),
            checksum: 'bad',
            encryptedData: 'AAAA',
            iv: 'AAAA',
            tag: 'AAAA',
            compression: 'gzip',
            eventCount: 0,
        };
        const result = importMemory(corrupted, 'test-corrupt');
        expect(result.errors.length).toBeGreaterThanOrEqual(1);
    });
});
//# sourceMappingURL=sync-engine.test.js.map