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

/**
 * Creates sla_notification_dispatches — idempotent audit log for SLA emails/alerts.
 * Safe to run multiple times.
 */
async function migrate() {
    const { sequelize } = db as { sequelize: { authenticate: () => Promise<void>; query: (sql: string) => Promise<unknown>; close: () => Promise<void> } };
    await sequelize.authenticate();
    console.log('Database connected.');

    const statements = [
        `CREATE TABLE IF NOT EXISTS sla_notification_dispatches (
            id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
            "trackingId" UUID NOT NULL REFERENCES sla_tracking(id) ON DELETE CASCADE,
            "thresholdKey" VARCHAR(128) NOT NULL,
            "dispatchType" VARCHAR(32) NOT NULL,
            "templateCode" VARCHAR(64),
            "stageName" VARCHAR(255),
            "reminderId" UUID,
            "escalationLevel" INTEGER,
            "recipientCount" INTEGER NOT NULL DEFAULT 0,
            "sentAt" TIMESTAMPTZ NOT NULL DEFAULT NOW(),
            status VARCHAR(24) NOT NULL DEFAULT 'sent',
            "createdAt" TIMESTAMPTZ NOT NULL DEFAULT NOW(),
            "updatedAt" TIMESTAMPTZ NOT NULL DEFAULT NOW()
        )`,
        `CREATE UNIQUE INDEX IF NOT EXISTS sla_notification_dispatches_tracking_threshold_uq
            ON sla_notification_dispatches ("trackingId", "thresholdKey")`,
        `CREATE INDEX IF NOT EXISTS sla_notification_dispatches_tracking_sent_idx
            ON sla_notification_dispatches ("trackingId", "sentAt")`,
        `CREATE INDEX IF NOT EXISTS sla_notification_dispatches_type_idx
            ON sla_notification_dispatches ("dispatchType")`
    ];

    for (const sql of statements) {
        console.log('Running:', sql.split('\n')[0].slice(0, 72) + '...');
        await sequelize.query(sql);
    }

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

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