import bcrypt from 'bcrypt';
import crypto from 'node:crypto';
import { SCHEMA_SQL } from './schema.js';
export function runMigrations(db) {
    db.pragma('journal_mode = WAL');
    db.pragma('foreign_keys = ON');
    db.exec(SCHEMA_SQL);
    // Add attempt column to squad_activities if it doesn't exist
    const columns = db.prepare('PRAGMA table_info(squad_activities)').all();
    const hasAttempt = columns.some((c) => c.name === 'attempt');
    if (!hasAttempt) {
        db.exec('ALTER TABLE squad_activities ADD COLUMN attempt INTEGER DEFAULT 1');
    }
    // Add result, started_at, finished_at to kanban_tasks if missing
    const kanbanCols = db.prepare('PRAGMA table_info(kanban_tasks)').all();
    if (kanbanCols.length > 0) {
        const hasResult = kanbanCols.some((c) => c.name === 'result');
        if (!hasResult) {
            db.exec('ALTER TABLE kanban_tasks ADD COLUMN result TEXT');
            db.exec('ALTER TABLE kanban_tasks ADD COLUMN started_at TEXT');
            db.exec('ALTER TABLE kanban_tasks ADD COLUMN finished_at TEXT');
        }
    }
    // Add pipeline columns to kanban_tasks if missing
    const kanbanColsForPipeline = db.prepare('PRAGMA table_info(kanban_tasks)').all();
    if (kanbanColsForPipeline.length > 0) {
        const hasStepId = kanbanColsForPipeline.some((c) => c.name === 'step_id');
        if (!hasStepId) {
            db.exec('ALTER TABLE kanban_tasks ADD COLUMN step_id TEXT');
            db.exec('ALTER TABLE kanban_tasks ADD COLUMN agent_id TEXT');
            db.exec('ALTER TABLE kanban_tasks ADD COLUMN agent_name TEXT');
            db.exec('ALTER TABLE kanban_tasks ADD COLUMN activity_id TEXT REFERENCES squad_activities(id) ON DELETE SET NULL');
            db.exec("ALTER TABLE kanban_tasks ADD COLUMN triggered_by TEXT DEFAULT 'dashboard'");
        }
        db.exec('CREATE INDEX IF NOT EXISTS idx_kanban_tasks_activity ON kanban_tasks(activity_id)');
        db.exec('CREATE INDEX IF NOT EXISTS idx_kanban_tasks_squad_activity ON kanban_tasks(squad_code, activity_id)');
    }
}
export async function seedDefaultAdmin(db) {
    const existing = db.prepare('SELECT id FROM users WHERE username = ?').get('admin');
    if (existing)
        return;
    const id = crypto.randomUUID();
    const hash = await bcrypt.hash('admin', 12);
    db.prepare('INSERT INTO users (id, username, email, password_hash, role, created_at) VALUES (?, ?, ?, ?, ?, ?)').run(id, 'admin', null, hash, 'admin', new Date().toISOString());
}
//# sourceMappingURL=migrations.js.map