// Migration: Add bu_teams column to users table
// Stores comma-separated BU team identifiers per user (e.g. 'STEAM,ACCESS-ENG')
// Existing users get empty string (admin must assign teams post-migration)
// Idempotent — safe to run multiple times
const sqlite3 = require('sqlite3').verbose();
const path = require('path');

const DB_FILE = path.join(__dirname, '..', 'cve_database.db');

/**
 * 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) => {
        db.serialize(() => {
            // Check if bu_teams column already exists
            db.all("PRAGMA table_info(users)", (err, columns) => {
                if (err) {
                    reject(err);
                    return;
                }

                const hasBuTeams = columns.some(col => col.name === 'bu_teams');

                if (hasBuTeams) {
                    console.log('✓ bu_teams column already exists — skipping migration');
                    resolve();
                    return;
                }

                console.log('Adding bu_teams column to users table...');

                db.run(
                    `ALTER TABLE users ADD COLUMN bu_teams TEXT NOT NULL DEFAULT ''`,
                    (err) => {
                        if (err) {
                            reject(err);
                            return;
                        }
                        console.log('✓ Added bu_teams column (default: empty string)');
                        console.log('  Note: Admin must assign teams to existing users via user management UI');
                        resolve();
                    }
                );
            });
        });
    });
}

// Run directly if executed as a script
if (require.main === module) {
    const db = new sqlite3.Database(DB_FILE);
    runMigration(db)
        .then(() => {
            console.log('Migration complete.');
            db.close();
        })
        .catch((err) => {
            console.error('Migration failed:', err.message);
            db.close();
            process.exit(1);
        });
}

module.exports = { runMigration };
