import { Request, Response } from 'express';
import type { AuthRequest } from '../../types/express.types.js';
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' });
    }
};

export const getOperationsDashboard = async (req: AuthRequest, res: Response) => {
    try {
        const module = typeof req.query.module === 'string' ? req.query.module : undefined;
        const breachedOnly = String(req.query.breachedOnly || 'false') === 'true';
        const mineOnly = String(req.query.mineOnly || 'false') === 'true';
        const { SlaOperationsService } = await import('../../services/SlaOperationsService.js');
        const data = await SlaOperationsService.getDashboard({
            module,
            breachedOnly,
            mineOnly,
            userRoleCode: req.user?.roleCode
        });
        res.json({ success: true, data });
    } catch (error) {
        console.error('SLA operations dashboard error:', error);
        res.status(500).json({ success: false, message: 'Error loading SLA operations dashboard' });
    }
};

export const getBatchStatus = async (req: AuthRequest, res: Response) => {
    try {
        const items = Array.isArray(req.body?.items) ? req.body.items : [];
        const refs = items
            .filter((i: any) => i?.entityType && i?.entityId)
            .map((i: any) => ({ entityType: String(i.entityType), entityId: String(i.entityId) }));
        const { SlaStatusService } = await import('../../services/SlaStatusService.js');
        const data = await SlaStatusService.getBatchStatus(refs);
        res.json({ success: true, data });
    } catch (error) {
        console.error('SLA batch status error:', error);
        res.status(500).json({ success: false, message: 'Error fetching SLA status' });
    }
};

export const exportOperationsCsv = async (req: AuthRequest, res: Response) => {
    try {
        const module = typeof req.query.module === 'string' ? req.query.module : undefined;
        const mineOnly = String(req.query.mineOnly || 'false') === 'true';
        const { SlaOperationsService } = await import('../../services/SlaOperationsService.js');
        const data = await SlaOperationsService.getDashboard({
            module,
            mineOnly,
            userRoleCode: req.user?.roleCode
        });
        const csv = SlaOperationsService.toCsv(data);
        res.setHeader('Content-Type', 'text/csv');
        res.setHeader('Content-Disposition', `attachment; filename="sla-queue-${Date.now()}.csv"`);
        res.send(csv);
    } catch (error) {
        console.error('SLA export error:', error);
        res.status(500).json({ success: false, message: 'Error exporting SLA queue' });
    }
};

// --- Debug Endpoint ---
export const getQuestionnaireReminderSettings = async (_req: Request, res: Response) => {
    try {
        const { getQuestionnaireReminderSettings } = await import(
            '../../services/questionnaireReminderSettings.js'
        );
        const data = await getQuestionnaireReminderSettings();
        res.json({ success: true, data });
    } catch (error) {
        console.error('Get questionnaire reminder settings error:', error);
        res.status(500).json({ success: false, message: 'Error loading questionnaire reminder settings' });
    }
};

export const updateQuestionnaireReminderSettings = async (req: Request, res: Response) => {
    try {
        const { saveQuestionnaireReminderSettings } = await import(
            '../../services/questionnaireReminderSettings.js'
        );
        const { enabled, firstAfterDays, intervalDays, maxCount } = req.body || {};
        const data = await saveQuestionnaireReminderSettings({
            enabled: enabled !== undefined ? Boolean(enabled) : undefined,
            firstAfterDays: firstAfterDays !== undefined ? Number(firstAfterDays) : undefined,
            intervalDays: intervalDays !== undefined ? Number(intervalDays) : undefined,
            maxCount: maxCount !== undefined ? Number(maxCount) : undefined
        });
        res.json({ success: true, data, message: 'Questionnaire reminder settings saved' });
    } catch (error) {
        console.error('Update questionnaire reminder settings error:', error);
        res.status(500).json({ success: false, message: 'Error saving questionnaire reminder settings' });
    }
};

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' });
    }
};
