// Migration: Add 'Remediate' to the ivanti_todo_queue workflow_type constraint
// Uses idempotent pattern: drop constraint IF EXISTS, then re-add with full set.
// Safe to re-run multiple times.
const pool = require('../db');

async function run() {
    console.log('Starting add_remediate_workflow_type migration...');

    // Verify prerequisite table exists
    const { rows: queueTable } = await pool.query(`
        SELECT 1 FROM information_schema.tables
        WHERE table_schema = 'public' AND table_name = 'ivanti_todo_queue'
    `);
    if (queueTable.length === 0) {
        console.error('✗ ivanti_todo_queue table does not exist. Cannot proceed.');
        process.exit(1);
    }
    console.log('✓ ivanti_todo_queue table exists');

    // Drop the existing workflow_type check constraint if it exists
    await pool.query(`
        ALTER TABLE ivanti_todo_queue
        DROP CONSTRAINT IF EXISTS ivanti_todo_queue_workflow_type_check
    `);
    console.log('✓ Dropped existing workflow_type check constraint (if any)');

    // Also drop alternative constraint name patterns
    await pool.query(`
        ALTER TABLE ivanti_todo_queue
        DROP CONSTRAINT IF EXISTS chk_workflow_type
    `);

    // Re-add the constraint with 'Remediate' included
    await pool.query(`
        ALTER TABLE ivanti_todo_queue
        ADD CONSTRAINT ivanti_todo_queue_workflow_type_check
        CHECK (workflow_type IN ('FP', 'Archer', 'CARD', 'GRANITE', 'DECOM', 'Remediate'))
    `);
    console.log('✓ Added workflow_type check constraint with Remediate included');

    console.log('Migration complete.');
    process.exit(0);
}

run().catch(err => {
    console.error('Migration failed:', err.message);
    process.exit(1);
});
