"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getAppliedMigrations = getAppliedMigrations;
exports.getPendingMigrations = getPendingMigrations;
exports.runMigrations = runMigrations;
exports.getMigrationStatus = getMigrationStatus;
const database_1 = require("./database");
const MIGRATIONS = [
    {
        version: 1,
        name: 'sync-tables',
        description: 'Add sync_state and sync_conflicts tables + synced column',
        up: [
            `ALTER TABLE memory_events ADD COLUMN synced INTEGER DEFAULT 0`,
        ],
    },
    {
        version: 2,
        name: 'performance-indexes',
        description: 'Add composite indexes for query performance',
        up: [
            `CREATE INDEX IF NOT EXISTS idx_memory_events_project_type_time ON memory_events(project, type, created_at DESC)`,
            `CREATE INDEX IF NOT EXISTS idx_memory_events_project_imp_time ON memory_events(project, importance DESC, created_at DESC)`,
            `CREATE INDEX IF NOT EXISTS idx_memory_events_project_summary_time ON memory_events(project, summary, created_at)`,
            `CREATE INDEX IF NOT EXISTS idx_memory_events_synced ON memory_events(synced)`,
        ],
    },
    {
        version: 3,
        name: 'missing-tables',
        description: 'Add verification_runs, publish_events, memory_topics, FTS5',
        up: [
            `CREATE TABLE IF NOT EXISTS verification_runs (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        project TEXT NOT NULL, build_id TEXT, branch TEXT, status TEXT NOT NULL,
        tests_total INTEGER DEFAULT 0, tests_passed INTEGER DEFAULT 0,
        tests_failed INTEGER DEFAULT 0, tests_skipped INTEGER DEFAULT 0,
        duration_ms INTEGER DEFAULT 0, coverage REAL, ci_platform TEXT,
        commit_hash TEXT, commit_message TEXT, author TEXT, log_snippet TEXT,
        created_at TEXT DEFAULT (datetime('now'))
      )`,
            `CREATE TABLE IF NOT EXISTS publish_events (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        project TEXT NOT NULL, version TEXT NOT NULL, environment TEXT NOT NULL,
        status TEXT NOT NULL, duration_ms INTEGER DEFAULT 0,
        commit_hash TEXT, author TEXT, notes TEXT,
        created_at TEXT DEFAULT (datetime('now'))
      )`,
            `CREATE TABLE IF NOT EXISTS memory_topics (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        project TEXT NOT NULL, topic TEXT NOT NULL,
        event_count INTEGER DEFAULT 1,
        first_seen TEXT DEFAULT (datetime('now')),
        last_seen TEXT DEFAULT (datetime('now')),
        avg_importance REAL DEFAULT 0, files_json TEXT,
        UNIQUE(project, topic)
      )`,
            `ALTER TABLE memory_events ADD COLUMN occurrence_count INTEGER DEFAULT 1`,
            `ALTER TABLE memory_events ADD COLUMN last_seen_at TEXT`,
            `ALTER TABLE branch_snapshots ADD COLUMN open_risks TEXT`,
        ],
    },
];
function getAppliedMigrations() {
    const db = (0, database_1.getDb)();
    try {
        const rows = db.prepare('SELECT version FROM _migrations ORDER BY version').all();
        return rows.map(r => r.version);
    }
    catch {
        return [];
    }
}
function getPendingMigrations() {
    const applied = new Set(getAppliedMigrations());
    return MIGRATIONS.filter(m => !applied.has(m.version));
}
function runMigrations() {
    const db = (0, database_1.getDb)();
    const result = { applied: 0, errors: [] };
    const pending = getPendingMigrations();
    if (pending.length === 0)
        return result;
    for (const migration of pending) {
        try {
            const tx = db.transaction(() => {
                for (const sql of migration.up) {
                    try {
                        db.exec(sql);
                    }
                    catch { /* column/index may already exist */ }
                }
                db.prepare('INSERT OR IGNORE INTO _migrations (version, name) VALUES (?, ?)').run(migration.version, migration.name);
            });
            tx();
            result.applied++;
        }
        catch (err) {
            result.errors.push(`v${migration.version} ${migration.name}: ${err.message}`);
        }
    }
    return result;
}
function getMigrationStatus() {
    const applied = getAppliedMigrations();
    const pending = MIGRATIONS.filter(m => !applied.includes(m.version));
    return {
        currentVersion: applied.length > 0 ? Math.max(...applied) : 0,
        applied,
        pending: pending.length,
    };
}
//# sourceMappingURL=migrations.js.map