const express = require('express');
const { verifyToken } = require('../middleware/authentication');

const router = express.Router();

// Get WebSocket connection info
router.get('/info', verifyToken, (req, res) => {
  const io = global.io;
  
  if (!io) {
    return res.status(500).json({
      success: false,
      message: 'WebSocket server not initialized'
    });
  }

  res.json({
    success: true,
    websocket: {
      connected_clients: io.engine.clientsCount,
      transport_types: ['websocket', 'polling'],
      endpoint: '/socket.io/',
      authentication_required: true
    },
    rooms: {
      user_rooms: `user_${req.user.id || req.user.userId}`,
      available_services: [
        'user-auth', 'template-manager', 'requirement-processor',
        'tech-stack-selector', 'architecture-designer', 'code-generator',
        'test-generator', 'deployment-manager', 'dashboard', 'self-improving-generator'
      ]
    }
  });
});

// Broadcast message to specific service subscribers
router.post('/broadcast/service/:serviceName', verifyToken, (req, res) => {
  const { serviceName } = req.params;
  const { message, type = 'info' } = req.body;
  const io = global.io;

  if (!io) {
    return res.status(500).json({
      success: false,
      message: 'WebSocket server not initialized'
    });
  }

  const serviceRoom = `service_${serviceName}`;
  io.to(serviceRoom).emit('service_broadcast', {
    service: serviceName,
    message,
    type,
    from: req.user.email || req.user.id,
    timestamp: new Date().toISOString()
  });

  res.json({
    success: true,
    message: `Broadcast sent to ${serviceName} subscribers`,
    room: serviceRoom
  });
});

// Broadcast message to specific project
router.post('/broadcast/project/:projectId', verifyToken, (req, res) => {
  const { projectId } = req.params;
  const { message, type = 'info' } = req.body;
  const io = global.io;

  if (!io) {
    return res.status(500).json({
      success: false,
      message: 'WebSocket server not initialized'
    });
  }

  const projectRoom = `project_${projectId}`;
  io.to(projectRoom).emit('project_broadcast', {
    projectId,
    message,
    type,
    from: req.user.email || req.user.id,
    timestamp: new Date().toISOString()
  });

  res.json({
    success: true,
    message: `Broadcast sent to project ${projectId}`,
    room: projectRoom
  });
});

// Send notification to specific user
router.post('/notify/:userId', verifyToken, (req, res) => {
  const { userId } = req.params;
  const { message, type = 'info', title } = req.body;
  const io = global.io;

  if (!io) {
    return res.status(500).json({
      success: false,
      message: 'WebSocket server not initialized'
    });
  }

  const userRoom = `user_${userId}`;
  io.to(userRoom).emit('notification', {
    title,
    message,
    type,
    from: req.user.email || req.user.id,
    timestamp: new Date().toISOString()
  });

  res.json({
    success: true,
    message: `Notification sent to user ${userId}`,
    room: userRoom
  });
});

module.exports = router;
