/**
 * Migration: create sla_notification_dispatches
 *
 * Folds the legacy `scripts/migrate-sla-notification-dispatches.ts` script
 * into the new versioned migrations system. Creates the idempotent dispatch
 * audit log used to dedupe SLA emails/alerts per tracking entry + threshold.
 *
 * Fresh `npm run migrate` runs already build this table from
 * `SLANotificationDispatch` model — this migration exists so environments
 * that predate the model can catch up via `npm run migrate:up`.
 */

import type { Sequelize, Transaction } from 'sequelize';

export interface MigrationContext {
    sequelize: Sequelize;
    transaction: Transaction;
}

const migration = {
    async up({ sequelize, transaction }: MigrationContext): Promise<void> {
        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) {
            await sequelize.query(sql, { transaction });
        }
    }
};

export default migration;
