import { Request, Response } from 'express';
import db from '../../database/models/index.js';
const { SLAConfiguration, SLATracking, SLABreach } = db;

export const updateConfig = async (req: Request, res: Response) => {
    const transaction = await db.sequelize.transaction();
    try {
        const { id } = req.params;
        const { activityName, tatHours, tatUnit, isActive, reminders, escalationConfigs } = req.body;

        const config = await SLAConfiguration.findByPk(id);
        if (!config) {
            await transaction.rollback();
            return res.status(404).json({ success: false, message: 'SLA Configuration not found' });
        }

        await config.update({ activityName, tatHours, tatUnit, isActive }, { transaction });

        // Update Reminders: Clear and recreate
        await db.SLAReminder.destroy({ where: { slaConfigId: id }, transaction });
        if (reminders && reminders.length > 0) {
            await db.SLAReminder.bulkCreate(
                reminders.map((r: any) => ({ ...r, slaConfigId: id })),
                { transaction }
            );
        }

        // Update Escalations: Clear and recreate
        await db.SLAEscalationConfig.destroy({ where: { slaConfigId: id }, transaction });
        if (escalationConfigs && escalationConfigs.length > 0) {
            await db.SLAEscalationConfig.bulkCreate(
                escalationConfigs.map((e: any) => ({ ...e, slaConfigId: id })),
                { transaction }
            );
        }

        await transaction.commit();
        res.json({ success: true, message: 'SLA Configuration updated successfully' });
    } catch (error) {
        await transaction.rollback();
        console.error('Update SLA config error:', error);
        res.status(500).json({ success: false, message: 'Error updating SLA config' });
    }
};

export const getConfigs = async (req: Request, res: Response) => {
    try {
        const configs = await SLAConfiguration.findAll({
            include: [
                { model: db.SLAReminder, as: 'reminders' },
                { model: db.SLAEscalationConfig, as: 'escalationConfigs' }
            ]
        });
        res.json({ success: true, data: configs });
    } catch (error) {
        console.error('Get SLA configs error:', error);
        res.status(500).json({ success: false, message: 'Error fetching SLA configs' });
    }
};

export const getTracking = async (req: Request, res: Response) => {
    try {
        const { applicationId } = req.params;
        const tracking = await SLATracking.findAll({
            where: { applicationId },
            include: [{ model: SLABreach, as: 'breaches' }]
        });
        res.json({ success: true, data: tracking });
    } catch (error) {
        res.status(500).json({ success: false, message: 'Error fetching SLA tracking' });
    }
};

// --- Debug Endpoint ---
export const getQueueStatus = async (req: Request, res: Response) => {
    try {
        const { slaQueue } = await import('../../common/queues/sla.queue.js');
        
        // 1. Get BullMQ Stats
        const repeatableJobs = await slaQueue.getRepeatableJobs();
        const counts = await slaQueue.getJobCounts('active', 'waiting', 'completed', 'failed', 'delayed');
        
        // 2. Get Database Active Tracks (The real "pending" work)
        const activeTracks = await SLATracking.findAll({
            where: { isActive: true, endTime: null },
            attributes: ['id', 'applicationId', 'stageName', 'startTime', 'isBreached']
        });

        res.json({
            success: true,
            debug: {
                isFastMode: process.env.DEBUG_SLA_FAST_MODE === 'true',
                redis: {
                    repeatableJobs,
                    counts
                },
                database: {
                    pendingTracksCount: activeTracks.length,
                    activeTracks
                }
            }
        });
    } catch (error) {
        console.error('Debug SLA Queue error:', error);
        res.status(500).json({ success: false, message: 'Error fetching SLA debug info' });
    }
};
