const express = require('express');
const { healthMonitor } = require('../middleware/serviceHealth');

const router = express.Router();

// Get comprehensive service health status
router.get('/services', (req, res) => {
  const status = healthMonitor.getServiceStatus();
  res.json({
    success: true,
    ...status
  });
});

// Get health status for a specific service
router.get('/service/:serviceName', (req, res) => {
  const { serviceName } = req.params;
  const serviceStatus = healthMonitor.serviceStatus[serviceName];
  
  if (!serviceStatus) {
    return res.status(404).json({
      success: false,
      message: `Service ${serviceName} not found`,
      available_services: Object.keys(healthMonitor.serviceStatus)
    });
  }
  
  res.json({
    success: true,
    service: serviceName,
    ...serviceStatus
  });
});

// Trigger manual health check for all services
router.post('/check', async (req, res) => {
  try {
    const serviceTargets = {
      USER_AUTH_URL: process.env.USER_AUTH_URL || 'http://localhost:8011',
      TEMPLATE_MANAGER_URL: process.env.TEMPLATE_MANAGER_URL || 'http://localhost:8009',
      REQUIREMENT_PROCESSOR_URL: process.env.REQUIREMENT_PROCESSOR_URL || 'http://localhost:8001',
      TECH_STACK_SELECTOR_URL: process.env.TECH_STACK_SELECTOR_URL || 'http://localhost:8002',
      ARCHITECTURE_DESIGNER_URL: process.env.ARCHITECTURE_DESIGNER_URL || 'http://localhost:8003',
      CODE_GENERATOR_URL: process.env.CODE_GENERATOR_URL || 'http://localhost:8004',
      TEST_GENERATOR_URL: process.env.TEST_GENERATOR_URL || 'http://localhost:8005',
      DEPLOYMENT_MANAGER_URL: process.env.DEPLOYMENT_MANAGER_URL || 'http://localhost:8006',
      DASHBOARD_URL: process.env.DASHBOARD_URL || 'http://localhost:8008',
      SELF_IMPROVING_GENERATOR_URL: process.env.SELF_IMPROVING_GENERATOR_URL || 'http://localhost:8007',
    };

    await healthMonitor.checkAllServices(serviceTargets);
    const status = healthMonitor.getServiceStatus();
    
    res.json({
      success: true,
      message: 'Health check completed',
      ...status
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: 'Health check failed',
      error: error.message
    });
  }
});

module.exports = { router };
