const { validationResult } = require('express-validator');

/**
 * 验证请求参数
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 * @param {Function} next - 下一个中间件
 */
const validateRequest = (req, res, next) => {
  const errors = validationResult(req);
  
  if (!errors.isEmpty()) {
    return res.status(400).json({
      success: false,
      message: '参数验证失败',
      errors: errors.array().map(error => ({
        field: error.path || error.param,
        message: error.msg,
        value: error.value
      }))
    });
  }
  
  next();
};

/**
 * 检查必需字段
 * @param {Array} requiredFields - 必需字段数组
 * @returns {Function} 中间件函数
 */
const requireFields = (requiredFields) => {
  return (req, res, next) => {
    const missingFields = [];
    
    for (const field of requiredFields) {
      if (!req.body[field] && req.body[field] !== 0) {
        missingFields.push(field);
      }
    }
    
    if (missingFields.length > 0) {
      return res.status(400).json({
        success: false,
        message: '缺少必需字段',
        missingFields
      });
    }
    
    next();
  };
};

/**
 * 验证数字范围
 * @param {string} field - 字段名
 * @param {number} min - 最小值
 * @param {number} max - 最大值
 * @returns {Function} 验证函数
 */
const validateNumberRange = (field, min = 0, max = Number.MAX_SAFE_INTEGER) => {
  return (req, res, next) => {
    const value = req.body[field];
    
    if (value !== undefined) {
      const num = Number(value);
      
      if (isNaN(num)) {
        return res.status(400).json({
          success: false,
          message: `${field} 必须是有效数字`
        });
      }
      
      if (num < min || num > max) {
        return res.status(400).json({
          success: false,
          message: `${field} 必须在 ${min} 到 ${max} 之间`
        });
      }
    }
    
    next();
  };
};

/**
 * 验证邮箱格式
 * @param {string} email - 邮箱地址
 * @returns {boolean} 是否有效
 */
const isValidEmail = (email) => {
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  return emailRegex.test(email);
};

/**
 * 验证手机号格式
 * @param {string} phone - 手机号
 * @returns {boolean} 是否有效
 */
const isValidPhone = (phone) => {
  const phoneRegex = /^1[3-9]\d{9}$/;
  return phoneRegex.test(phone);
};

/**
 * 清理和验证字符串
 * @param {string} str - 输入字符串
 * @param {Object} options - 选项
 * @returns {string} 清理后的字符串
 */
const sanitizeString = (str, options = {}) => {
  if (typeof str !== 'string') {
    return '';
  }
  
  let result = str.trim();
  
  if (options.maxLength) {
    result = result.substring(0, options.maxLength);
  }
  
  if (options.removeHtml) {
    result = result.replace(/<[^>]*>/g, '');
  }
  
  return result;
};

module.exports = {
  validateRequest,
  requireFields,
  validateNumberRange,
  isValidEmail,
  isValidPhone,
  sanitizeString
};