import { Request, Response } from 'express';
import { sequelize } from '@config/database';
import { QueryTypes } from 'sequelize';
import logger from '@utils/logger';

/**
 * Debug endpoint to check TAT system status
 */
export const checkTatSystemStatus = async (_req: Request, res: Response) => {
  try {
    const status: any = {
      redis: {
        configured: !!process.env.REDIS_URL,
        url: process.env.REDIS_URL ? process.env.REDIS_URL.replace(/:[^:]*@/, ':****@') : 'Not configured',
        testMode: process.env.TAT_TEST_MODE === 'true'
      },
      database: {
        connected: false,
        tatAlertsTableExists: false,
        totalAlerts: 0,
        recentAlerts: []
      },
      config: {
        workStartHour: process.env.WORK_START_HOUR || '9',
        workEndHour: process.env.WORK_END_HOUR || '18',
        tatTestMode: process.env.TAT_TEST_MODE || 'false'
      }
    };

    // Check database connection
    try {
      await sequelize.authenticate();
      status.database.connected = true;
    } catch (error) {
      status.database.connected = false;
      status.database.error = 'Database connection failed';
    }

    // Check if tat_alerts table exists
    try {
      const tables = await sequelize.query(
        "SELECT table_name FROM information_schema.tables WHERE table_name = 'tat_alerts'",
        { type: QueryTypes.SELECT }
      );
      status.database.tatAlertsTableExists = tables.length > 0;
    } catch (error) {
      status.database.tatAlertsTableExists = false;
    }

    // Count total alerts
    if (status.database.tatAlertsTableExists) {
      try {
        const result = await sequelize.query(
          'SELECT COUNT(*) as count FROM tat_alerts',
          { type: QueryTypes.SELECT }
        );
        status.database.totalAlerts = (result[0] as any).count;

        // Get recent alerts
        const recentAlerts = await sequelize.query(`
          SELECT 
            alert_id,
            threshold_percentage,
            alert_sent_at,
            metadata->'requestNumber' as request_number,
            metadata->'approverName' as approver_name
          FROM tat_alerts
          ORDER BY alert_sent_at DESC
          LIMIT 5
        `, { type: QueryTypes.SELECT });
        
        status.database.recentAlerts = recentAlerts;
      } catch (error) {
        logger.error('Error querying tat_alerts:', error);
      }
    }

    // Check for pending approvals that need TAT monitoring
    try {
      const pendingLevels = await sequelize.query(`
        SELECT 
          w.request_number,
          al.level_number,
          al.approver_name,
          al.status,
          al.tat_start_time,
          al.tat50_alert_sent,
          al.tat75_alert_sent,
          al.tat_breached
        FROM approval_levels al
        JOIN workflow_requests w ON al.request_id = w.request_id
        WHERE al.status IN ('PENDING', 'IN_PROGRESS')
        ORDER BY al.tat_start_time DESC
        LIMIT 5
      `, { type: QueryTypes.SELECT });
      
      status.pendingApprovals = pendingLevels;
    } catch (error) {
      logger.error('Error querying pending levels:', error);
    }

    res.json({
      success: true,
      status,
      message: status.database.tatAlertsTableExists 
        ? 'TAT system configured correctly' 
        : 'TAT alerts table not found - run migrations'
    });
  } catch (error) {
    logger.error('[Debug] Error checking TAT status:', error);
    res.status(500).json({
      success: false,
      error: 'Failed to check TAT system status'
    });
  }
};

/**
 * Debug endpoint to check workflow details response
 */
export const checkWorkflowDetailsResponse = async (req: Request, res: Response): Promise<void> => {
  try {
    const { requestId } = req.params;
    
    const workflowService = require('@services/workflow.service').workflowService;
    const details = await workflowService.getWorkflowDetails(requestId);
    
    if (!details) {
      res.status(404).json({
        success: false,
        error: 'Workflow not found'
      });
      return;
    }

    // Check what's in the response
    const responseStructure = {
      hasWorkflow: !!details.workflow,
      hasApprovals: Array.isArray(details.approvals),
      approvalsCount: details.approvals?.length || 0,
      hasParticipants: Array.isArray(details.participants),
      hasDocuments: Array.isArray(details.documents),
      hasActivities: Array.isArray(details.activities),
      hasTatAlerts: Array.isArray(details.tatAlerts), // Check if tatAlerts exist
      tatAlertsCount: details.tatAlerts?.length || 0,
      tatAlerts: details.tatAlerts || [] // Return the actual alerts
    };

    res.json({
      success: true,
      structure: responseStructure,
      tatAlerts: details.tatAlerts || [],
      message: responseStructure.hasTatAlerts 
        ? `Found ${responseStructure.tatAlertsCount} TAT alerts`
        : 'No TAT alerts found for this request'
    });
  } catch (error: any) {
    logger.error('[Debug] Error checking workflow details:', error);
    res.status(500).json({
      success: false,
      error: error.message || 'Failed to check workflow details'
    });
  }
};

