import type { SlaCatalogEntry } from '../config/slaStageCatalog.js';
import { ONBOARDING_SLA_DEPRECATED_ACTIVITIES } from '../config/slaStageCatalog.js';

/** Default reminders / escalations per SRS §9.4.5 (T-24h, T-4h; L1 +4h, L2 +12h, L3 +24h). */
export async function applySlaConfigChildren(
    db: any,
    configId: string,
    transaction: any
) {
    await db.SLAReminder.destroy({ where: { slaConfigId: configId }, transaction });
    await db.SLAEscalationConfig.destroy({ where: { slaConfigId: configId }, transaction });

    await db.SLAReminder.bulkCreate(
        [
            { slaConfigId: configId, timeValue: 1, timeUnit: 'days', isEnabled: true },
            { slaConfigId: configId, timeValue: 4, timeUnit: 'hours', isEnabled: true }
        ],
        { transaction }
    );

    await db.SLAEscalationConfig.bulkCreate(
        [
            { slaConfigId: configId, level: 1, timeValue: 4, timeUnit: 'hours', notifyRole: 'ZBH' },
            { slaConfigId: configId, level: 2, timeValue: 12, timeUnit: 'hours', notifyRole: 'DD Lead' },
            { slaConfigId: configId, level: 3, timeValue: 24, timeUnit: 'hours', notifyRole: 'NBH' }
        ],
        { transaction }
    );
}

export async function seedSlaCatalogEntries(
    db: any,
    entries: SlaCatalogEntry[],
    transaction?: any
) {
    for (const item of entries) {
        const [config, created] = await db.SLAConfiguration.findOrCreate({
            where: { activityName: item.activityName },
            defaults: {
                activityName: item.activityName,
                ownerRole: item.ownerRole,
                tatHours: item.tatHours,
                tatUnit: item.tatUnit,
                isActive: true
            },
            transaction
        });

        if (!created) {
            await config.update(
                {
                    ownerRole: item.ownerRole,
                    tatHours: item.tatHours,
                    tatUnit: item.tatUnit
                },
                { transaction }
            );
        }

        await applySlaConfigChildren(db, config.id, transaction);
    }

    if (ONBOARDING_SLA_DEPRECATED_ACTIVITIES.length > 0) {
        await db.SLAConfiguration.update(
            { isActive: false },
            {
                where: { activityName: [...ONBOARDING_SLA_DEPRECATED_ACTIVITIES] },
                transaction
            }
        );
    }
}
