const axios = require('axios');
const logger = require('../utils/logger');

// Health check middleware
const healthCheck = async (req, res, next) => {
  // Skip health check for actual health endpoint
  if (req.path === '/health') {
    return next();
  }

  // Check external services health
  const externalServices = {
    techStackSelector: process.env.TECH_STACK_SELECTOR_HEALTH_URL || 'http://tech-stack-selector:8002/health',
    templateManager: process.env.TEMPLATE_MANAGER_HEALTH_URL || 'http://template-manager:8009/health'
  };

  const healthStatus = {
    unison: 'healthy',
    externalServices: {},
    timestamp: new Date().toISOString()
  };

  // Check each external service
  for (const [serviceName, url] of Object.entries(externalServices)) {
    try {
      const response = await axios.get(url, {
        timeout: parseInt(process.env.HEALTH_CHECK_TIMEOUT) || 5000,
        headers: {
          'User-Agent': 'Unison-HealthCheck/1.0'
        }
      });
      
      healthStatus.externalServices[serviceName] = {
        status: 'healthy',
        responseTime: response.headers['x-response-time'] || 'unknown',
        lastChecked: new Date().toISOString()
      };
    } catch (error) {
      logger.warn({
        message: `External service ${serviceName} health check failed`,
        service: serviceName,
        url: url,
        error: error.message
      });
      
      healthStatus.externalServices[serviceName] = {
        status: 'unhealthy',
        error: error.message,
        lastChecked: new Date().toISOString()
      };
    }
  }

  // Store health status in request for use in routes
  req.healthStatus = healthStatus;
  
  next();
};

module.exports = healthCheck;
