const Joi = require('joi');
const logger = require('../utils/logger');

// Request validation middleware
const requestValidator = (req, res, next) => {
  // Skip validation for health checks and root endpoint
  if (req.path === '/health' || req.path === '/') {
    return next();
  }

  // Validate request body for POST/PUT requests
  if (['POST', 'PUT', 'PATCH'].includes(req.method) && req.body) {
    // Basic validation for unified recommendation request - simplified
    if (req.path.includes('/unified')) {
      const schema = Joi.object({
        domain: Joi.string().min(1).max(100).optional(),
        budget: Joi.number().positive().optional(),
        preferredTechnologies: Joi.array().items(Joi.string().min(1).max(50)).optional(),
        templateId: Joi.string().uuid().optional(),
        includeSimilar: Joi.boolean().optional(),
        includeKeywords: Joi.boolean().optional(),
        forceRefresh: Joi.boolean().optional()
      });

      const { error } = schema.validate(req.body);
      if (error) {
        logger.warn({
          message: 'Request validation failed',
          error: error.details[0].message,
          body: req.body,
          path: req.path
        });
        return res.status(400).json({
          success: false,
          error: 'Invalid request data',
          details: error.details[0].message
        });
      }
    }
  }

  next();
};

module.exports = requestValidator;
