// Migration: Add Jira sync columns to jira_tickets (Postgres version)
// Adds jira_id, jira_status, last_synced_at, and created_by columns.
// These were originally added via a SQLite migration that was never ported to Postgres.
// Idempotent — safe to run multiple times.
const pool = require('../db');

async function run() {
    console.log('Adding Jira sync columns to jira_tickets (Postgres)...');

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

    await pool.query(`ALTER TABLE jira_tickets ADD COLUMN IF NOT EXISTS jira_id TEXT`);
    console.log('✓ jira_id column added (or already exists)');

    await pool.query(`ALTER TABLE jira_tickets ADD COLUMN IF NOT EXISTS jira_status TEXT`);
    console.log('✓ jira_status column added (or already exists)');

    await pool.query(`ALTER TABLE jira_tickets ADD COLUMN IF NOT EXISTS last_synced_at TIMESTAMPTZ`);
    console.log('✓ last_synced_at column added (or already exists)');

    await pool.query(`ALTER TABLE jira_tickets ADD COLUMN IF NOT EXISTS created_by INTEGER`);
    console.log('✓ created_by column added (or already exists)');

    await pool.query(`CREATE INDEX IF NOT EXISTS idx_jira_tickets_jira_id ON jira_tickets(jira_id)`);
    console.log('✓ jira_id index created (or already exists)');

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

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