import 'dotenv/config';
import db from '../src/database/models/index.js';

/**
 * Aligns sla_tracking with SLATracking model (entity columns + metadata for reminder state).
 * Safe to run multiple times (IF NOT EXISTS).
 */
async function migrate() {
    const { sequelize } = db as any;
    await sequelize.authenticate();
    console.log('Database connected.');

    const statements = [
        `ALTER TABLE sla_tracking ADD COLUMN IF NOT EXISTS "entityType" VARCHAR(255)`,
        `ALTER TABLE sla_tracking ADD COLUMN IF NOT EXISTS "entityId" UUID`,
        `ALTER TABLE sla_tracking ADD COLUMN IF NOT EXISTS metadata JSONB DEFAULT '{}'::jsonb`,
        // Backfill entity columns for legacy rows that only had applicationId
        `UPDATE sla_tracking SET "entityType" = 'application' WHERE "entityType" IS NULL AND "applicationId" IS NOT NULL`,
        `UPDATE sla_tracking SET "entityId" = "applicationId" WHERE "entityId" IS NULL AND "applicationId" IS NOT NULL`
    ];

    for (const sql of statements) {
        console.log('Running:', sql.slice(0, 80) + '...');
        await sequelize.query(sql);
    }

    console.log('sla_tracking schema migration complete.');
    await sequelize.close();
}

migrate().catch((err) => {
    console.error(err);
    process.exit(1);
});
