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

// 监管任务验证规则
const validateSupervisionTask = [
  body('applicationId')
    .notEmpty()
    .withMessage('申请单号不能为空')
    .isLength({ min: 1, max: 50 })
    .withMessage('申请单号长度应在1-50字符之间'),
    
  body('policyId')
    .notEmpty()
    .withMessage('保单编号不能为空')
    .isLength({ min: 1, max: 50 })
    .withMessage('保单编号长度应在1-50字符之间'),
    
  body('productName')
    .notEmpty()
    .withMessage('产品名称不能为空')
    .isLength({ min: 1, max: 100 })
    .withMessage('产品名称长度应在1-100字符之间'),
    
  body('customerName')
    .notEmpty()
    .withMessage('客户姓名不能为空')
    .isLength({ min: 1, max: 50 })
    .withMessage('客户姓名长度应在1-50字符之间'),
    
  body('taskType')
    .isIn(['new_application', 'task_guidance', 'batch_operation'])
    .withMessage('任务类型必须是: new_application, task_guidance, batch_operation'),
    
  body('documentType')
    .optional()
    .isLength({ max: 20 })
    .withMessage('证件类型长度不能超过20字符'),
    
  body('documentNumber')
    .optional()
    .isLength({ max: 50 })
    .withMessage('证件号码长度不能超过50字符'),
    
  body('applicableAmount')
    .optional()
    .isFloat({ min: 0 })
    .withMessage('适用金额必须是非负数'),
    
  body('priority')
    .optional()
    .isIn(['low', 'medium', 'high', 'urgent'])
    .withMessage('优先级必须是: low, medium, high, urgent'),
    
  body('assignedTo')
    .optional()
    .isInt({ min: 1 })
    .withMessage('分配用户ID必须是正整数'),
    
  body('dueDate')
    .optional()
    .isISO8601()
    .withMessage('截止日期格式不正确'),
    
  body('remarks')
    .optional()
    .isLength({ max: 1000 })
    .withMessage('备注长度不能超过1000字符'),

  // 验证结果处理
  (req, res, next) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({
        success: false,
        message: '数据验证失败',
        errors: errors.array()
      });
    }
    next();
  }
];

// 批量操作验证规则
const validateBatchOperation = [
  body('ids')
    .isArray({ min: 1 })
    .withMessage('必须提供至少一个ID'),
    
  body('ids.*')
    .isInt({ min: 1 })
    .withMessage('ID必须是正整数'),
    
  body('operation')
    .isIn(['assign', 'updateStatus', 'delete'])
    .withMessage('操作类型必须是: assign, updateStatus, delete'),
    
  body('data')
    .if(body('operation').equals('assign'))
    .custom((value) => {
      if (!value || !value.assignedTo) {
        throw new Error('分配操作必须提供assignedTo字段');
      }
      if (!Number.isInteger(value.assignedTo) || value.assignedTo < 1) {
        throw new Error('assignedTo必须是正整数');
      }
      return true;
    }),
    
  body('data')
    .if(body('operation').equals('updateStatus'))
    .custom((value) => {
      if (!value || !value.status) {
        throw new Error('状态更新操作必须提供status字段');
      }
      if (!['pending', 'processing', 'completed', 'rejected'].includes(value.status)) {
        throw new Error('status必须是: pending, processing, completed, rejected');
      }
      return true;
    }),

  // 验证结果处理
  (req, res, next) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({
        success: false,
        message: '数据验证失败',
        errors: errors.array()
      });
    }
    next();
  }
];

// 监管任务更新验证规则
const validateSupervisionTaskUpdate = [
  body('status')
    .optional()
    .isIn(['pending', 'processing', 'completed', 'rejected'])
    .withMessage('状态必须是: pending, processing, completed, rejected'),
    
  body('priority')
    .optional()
    .isIn(['low', 'medium', 'high', 'urgent'])
    .withMessage('优先级必须是: low, medium, high, urgent'),
    
  body('assignedTo')
    .optional()
    .isInt({ min: 1 })
    .withMessage('分配用户ID必须是正整数'),
    
  body('dueDate')
    .optional()
    .isISO8601()
    .withMessage('截止日期格式不正确'),
    
  body('remarks')
    .optional()
    .isLength({ max: 1000 })
    .withMessage('备注长度不能超过1000字符'),
    
  body('supervisionDataCount')
    .optional()
    .isInt({ min: 0 })
    .withMessage('监管生成数量必须是非负整数'),

  // 验证结果处理
  (req, res, next) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({
        success: false,
        message: '数据验证失败',
        errors: errors.array()
      });
    }
    next();
  }
];

module.exports = {
  validateSupervisionTask,
  validateBatchOperation,
  validateSupervisionTaskUpdate
};