// Migration: Add Jira API sync columns to jira_tickets table
// Adds jira_id, jira_status, and last_synced_at columns to support
// live synchronization with Jira Data Center REST API.
// Idempotent — safe to run multiple times.

const sqlite3 = require('sqlite3').verbose();
const path = require('path');

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

console.log('Starting Jira sync columns migration...');

const newColumns = [
    { name: 'jira_id', sql: 'ALTER TABLE jira_tickets ADD COLUMN jira_id TEXT' },
    { name: 'jira_status', sql: 'ALTER TABLE jira_tickets ADD COLUMN jira_status TEXT' },
    { name: 'last_synced_at', sql: 'ALTER TABLE jira_tickets ADD COLUMN last_synced_at DATETIME' }
];

db.all('PRAGMA table_info(jira_tickets)', (err, columns) => {
    if (err) {
        console.error('Could not inspect jira_tickets:', err.message);
        console.log('Run migrate_jira_tickets.js first to create the table.');
        db.close();
        return;
    }

    const existingNames = new Set(columns.map(c => c.name));
    let pending = 0;

    db.serialize(() => {
        newColumns.forEach(({ name, sql }) => {
            if (existingNames.has(name)) {
                console.log(`✓ jira_tickets.${name} already exists — skipping`);
            } else {
                pending++;
                db.run(sql, (runErr) => {
                    if (runErr) {
                        console.error(`✗ Failed to add ${name}:`, runErr.message);
                    } else {
                        console.log(`✓ Added jira_tickets.${name}`);
                    }
                    pending--;
                    if (pending === 0) finish();
                });
            }
        });

        // Create index on jira_id for lookups
        db.run('CREATE INDEX IF NOT EXISTS idx_jira_tickets_jira_id ON jira_tickets(jira_id)', (idxErr) => {
            if (idxErr) console.error('Index error:', idxErr.message);
            else console.log('✓ jira_id index created');
        });

        if (pending === 0) finish();
    });
});

function finish() {
    db.close(() => {
        console.log('Migration complete!');
    });
}
