// Migration: Add ivanti_fp_submissions table
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 ivanti_fp_submissions migration...');

db.serialize(() => {
    db.run(`
        CREATE TABLE IF NOT EXISTS ivanti_fp_submissions (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            user_id INTEGER NOT NULL,
            username TEXT NOT NULL,
            ivanti_workflow_batch_id INTEGER,
            ivanti_generated_id TEXT,
            workflow_name TEXT NOT NULL,
            reason TEXT NOT NULL,
            description TEXT,
            expiration_date TEXT NOT NULL,
            scope_override TEXT NOT NULL DEFAULT 'Authorized',
            finding_ids_json TEXT NOT NULL,
            queue_item_ids_json TEXT NOT NULL,
            attachment_count INTEGER DEFAULT 0,
            attachment_results_json TEXT,
            status TEXT NOT NULL DEFAULT 'success' CHECK(status IN ('success', 'partial', 'failed')),
            error_message TEXT,
            created_at DATETIME DEFAULT CURRENT_TIMESTAMP
        )
    `, (err) => {
        if (err) console.error('Error creating table:', err);
        else console.log('✓ ivanti_fp_submissions table created');
    });

    db.run(
        'CREATE INDEX IF NOT EXISTS idx_fp_submissions_user ON ivanti_fp_submissions(user_id)',
        (err) => {
            if (err) console.error('Error creating index:', err);
            else console.log('✓ user_id index created');
        }
    );

    db.run(
        'CREATE INDEX IF NOT EXISTS idx_fp_submissions_ivanti_id ON ivanti_fp_submissions(ivanti_generated_id)',
        (err) => {
            if (err) console.error('Error creating index:', err);
            else console.log('✓ ivanti_generated_id index created');
        }
    );

    console.log('✓ Migration statements queued');
});

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