const express = require('express');
const router = express.Router();
const auth = require('../middleware/auth');
const CareerGuidanceWebSocket = require('../websocketserver1');

// Store WebSocket server instance
let careerGuidanceWS = null;

// Initialize WebSocket server
const initializeCareerGuidanceWS = (server) => {
    if (!careerGuidanceWS) {
        careerGuidanceWS = new CareerGuidanceWebSocket(server);
    }
    return careerGuidanceWS;
};

// Health check endpoint for career guidance WebSocket
router.get('/health', (req, res) => {
    try {
        if (!careerGuidanceWS) {
            return res.status(503).json({
                success: false,
                message: 'Career Guidance WebSocket server not initialized',
                status: 'offline'
            });
        }

        const stats = {
            totalConnections: careerGuidanceWS.stats.totalConnections,
            activeConnections: careerGuidanceWS.stats.activeConnections,
            currentClients: careerGuidanceWS.getConnectedClientsCount(),
            totalMessages: careerGuidanceWS.stats.totalMessages,
            errors: careerGuidanceWS.stats.errors
        };

        res.json({
            success: true,
            message: 'Career Guidance WebSocket server is running',
            status: 'online',
            stats: stats,
            timestamp: new Date().toISOString()
        });
    } catch (error) {
        console.error('Career Guidance WebSocket health check error:', error);
        res.status(500).json({
            success: false,
            message: 'Health check failed',
            error: error.message
        });
    }
});

// Get connected clients info
router.get('/clients', auth, (req, res) => {
    try {
        if (!careerGuidanceWS) {
            return res.status(503).json({
                success: false,
                message: 'Career Guidance WebSocket server not initialized'
            });
        }

        const clients = careerGuidanceWS.getClientInfo();
        
        res.json({
            success: true,
            message: 'Connected clients retrieved successfully',
            clients: clients,
            totalClients: clients.length,
            timestamp: new Date().toISOString()
        });
    } catch (error) {
        console.error('Get clients error:', error);
        res.status(500).json({
            success: false,
            message: 'Failed to get connected clients',
            error: error.message
        });
    }
});

// Broadcast message to all connected clients
router.post('/broadcast', auth, (req, res) => {
    try {
        const { message, type = 'announcement' } = req.body;

        if (!message) {
            return res.status(400).json({
                success: false,
                message: 'Message content is required'
            });
        }

        if (!careerGuidanceWS) {
            return res.status(503).json({
                success: false,
                message: 'Career Guidance WebSocket server not initialized'
            });
        }

        const broadcastMessage = {
            type: type,
            message: message,
            timestamp: new Date().toISOString(),
            from: 'admin'
        };

        careerGuidanceWS.broadcast(broadcastMessage);

        res.json({
            success: true,
            message: 'Broadcast message sent successfully',
            broadcastMessage: broadcastMessage
        });
    } catch (error) {
        console.error('Broadcast error:', error);
        res.status(500).json({
            success: false,
            message: 'Failed to broadcast message',
            error: error.message
        });
    }
});

// Get WebSocket server statistics
router.get('/stats', auth, (req, res) => {
    try {
        if (!careerGuidanceWS) {
            return res.status(503).json({
                success: false,
                message: 'Career Guidance WebSocket server not initialized'
            });
        }

        const stats = {
            totalConnections: careerGuidanceWS.stats.totalConnections,
            activeConnections: careerGuidanceWS.stats.activeConnections,
            currentClients: careerGuidanceWS.getConnectedClientsCount(),
            totalMessages: careerGuidanceWS.stats.totalMessages,
            errors: careerGuidanceWS.stats.errors,
            uptime: process.uptime(),
            memoryUsage: process.memoryUsage()
        };

        res.json({
            success: true,
            message: 'Statistics retrieved successfully',
            stats: stats,
            timestamp: new Date().toISOString()
        });
    } catch (error) {
        console.error('Get stats error:', error);
        res.status(500).json({
            success: false,
            message: 'Failed to get statistics',
            error: error.message
        });
    }
});

// Test career guidance endpoint (for testing without WebSocket)
router.post('/test-guidance', auth, async (req, res) => {
    try {
        const { userId, occupation } = req.body;

        if (!userId || !occupation) {
            return res.status(400).json({
                success: false,
                message: 'Both userId and occupation are required'
            });
        }

        // Create a mock client for testing
        const mockClient = {
            user: req.user,
            ws: {
                readyState: 1, // OPEN state
                send: (data) => console.log('Mock WebSocket send:', data)
            }
        };

        // Initialize WebSocket if not already done
        if (!careerGuidanceWS) {
            return res.status(503).json({
                success: false,
                message: 'Career Guidance WebSocket server not initialized. Please restart the server.'
            });
        }

        // Generate career guidance
        const careerGuidance = await careerGuidanceWS.generateCareerGuidance(userId, occupation);

        res.json({
            success: true,
            message: 'Career guidance generated successfully',
            data: careerGuidance,
            timestamp: new Date().toISOString()
        });

    } catch (error) {
        console.error('Test career guidance error:', error);
        res.status(500).json({
            success: false,
            message: 'Failed to generate career guidance',
            error: error.message
        });
    }
});

// WebSocket connection info endpoint
router.get('/connection-info', (req, res) => {
    try {
        if (!careerGuidanceWS) {
            return res.status(503).json({
                success: false,
                message: 'Career Guidance WebSocket server not initialized'
            });
        }

        const connectionInfo = {
            serverPath: '/ws/career-guidance',
            supportedMessageTypes: ['career_guidance', 'ping'],
            authentication: 'JWT token required',
            maxPayload: '16MB',
            compression: 'disabled'
        };

        res.json({
            success: true,
            message: 'WebSocket connection information',
            connectionInfo: connectionInfo,
            timestamp: new Date().toISOString()
        });
    } catch (error) {
        console.error('Get connection info error:', error);
        res.status(500).json({
            success: false,
            message: 'Failed to get connection information',
            error: error.message
        });
    }
});

// Export the initialization function
router.initializeCareerGuidanceWS = initializeCareerGuidanceWS;

module.exports = router;
