// Migration: Add created_by column to cves, archer_tickets, and jira_tickets tables
// Stores the user ID of the creator for ownership-based delete checks.
// Idempotent — safe to run multiple times.
const sqlite3 = require('sqlite3').verbose();
const path = require('path');

/**
 * Run the migration against the given database instance.
 * Exported for testing with in-memory databases.
 * @param {sqlite3.Database} db
 * @returns {Promise<void>}
 */
function runMigration(db) {
    return new Promise((resolve, reject) => {
        const tables = ['cves', 'archer_tickets', 'jira_tickets'];
        let completed = 0;

        db.serialize(() => {
            tables.forEach((table) => {
                db.all(`PRAGMA table_info(${table})`, (err, columns) => {
                    if (err) {
                        // Table may not exist yet — skip gracefully
                        console.log(`⚠ Could not inspect ${table}: ${err.message} — skipping`);
                        completed++;
                        if (completed === tables.length) resolve();
                        return;
                    }

                    const hasCreatedBy = columns.some(col => col.name === 'created_by');

                    if (hasCreatedBy) {
                        console.log(`✓ ${table}.created_by already exists — skipping`);
                        completed++;
                        if (completed === tables.length) resolve();
                        return;
                    }

                    db.run(
                        `ALTER TABLE ${table} ADD COLUMN created_by INTEGER REFERENCES users(id)`,
                        (err) => {
                            if (err) {
                                reject(err);
                                return;
                            }
                            console.log(`✓ Added created_by column to ${table}`);
                            completed++;
                            if (completed === tables.length) resolve();
                        }
                    );
                });
            });
        });
    });
}

// Run directly if executed as a script
if (require.main === module) {
    const dbPath = path.join(__dirname, '..', 'cve_database.db');
    const db = new sqlite3.Database(dbPath);
    console.log('Starting add_created_by_columns migration...');

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

module.exports = { runMigration };
