// Migration: Add return_classification_json column to ivanti_sync_anomaly_log
//
// Stores the classification breakdown for returned findings (e.g., how many
// returned due to BU reassignment back to team, severity re-escalation, etc.)
//
// Safe to re-run — uses ALTER TABLE with IF NOT EXISTS pattern.
//
// Usage: node backend/migrations/add_return_classification.js

const path    = require('path');
const sqlite3 = require('sqlite3').verbose();
const dbPath  = path.join(__dirname, '..', 'cve_database.db');
const db      = new sqlite3.Database(dbPath);

console.log('Starting return classification migration...');

function run(sql, params = []) {
    return new Promise((resolve, reject) => {
        db.run(sql, params, function (err) {
            if (err) reject(err);
            else resolve(this);
        });
    });
}

function all(sql, params = []) {
    return new Promise((resolve, reject) => {
        db.all(sql, params, (err, rows) => {
            if (err) reject(err);
            else resolve(rows || []);
        });
    });
}

async function migrate() {
    // Check if column already exists
    const columns = await all(`PRAGMA table_info(ivanti_sync_anomaly_log)`);
    const hasColumn = columns.some(c => c.name === 'return_classification_json');

    if (!hasColumn) {
        await run(`ALTER TABLE ivanti_sync_anomaly_log ADD COLUMN return_classification_json TEXT NOT NULL DEFAULT '{}'`);
        console.log('✓ Added return_classification_json column to ivanti_sync_anomaly_log');
    } else {
        console.log('✓ return_classification_json column already exists — skipping');
    }
}

migrate()
    .then(() => {
        console.log('Migration complete.');
        db.close();
    })
    .catch((err) => {
        console.error('Migration failed:', err);
        db.close();
        process.exit(1);
    });
