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

// Handle validation errors
const handleValidationErrors = (req, res, next) => {
  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    return res.status(400).json({
      success: false,
      message: 'Validation failed',
      errors: errors.array()
    });
  }
  next();
};

// Phone number validation
const validatePhoneNumber = () => {
  return body('phone_number')
    .notEmpty()
    .withMessage('Phone number is required')
    .isLength({ min: 8, max: 15 })
    .withMessage('Phone number must be between 8 and 15 digits')
    .matches(/^\d+$/)
    .withMessage('Phone number must contain only digits');
};

// OTP validation
const validateOTP = () => {
  return body('otp')
    .notEmpty()
    .withMessage('OTP is required')
    .isLength({ min: 4, max: 8 })
    .withMessage('OTP must be between 4 and 8 digits')
    .matches(/^\d+$/)
    .withMessage('OTP must contain only digits');
};

// User registration validation
const validateUserRegistration = () => {
  return [
    validatePhoneNumber(),
    body('email')
      .optional()
      .isEmail()
      .withMessage('Please provide a valid email address')
      .normalizeEmail(),
    body('first_name')
      .notEmpty()
      .withMessage('First name is required')
      .isLength({ min: 2, max: 50 })
      .withMessage('First name must be between 2 and 50 characters')
      .trim(),
    body('last_name')
      .notEmpty()
      .withMessage('Last name is required')
      .isLength({ min: 2, max: 50 })
      .withMessage('Last name must be between 2 and 50 characters')
      .trim(),
    body('role')
      .optional()
      .isIn(['main_admin', 'admin', 'user'])
      .withMessage('Invalid role specified')
  ];
};

// Login validation
const validateLogin = () => {
  return [
    validatePhoneNumber()
  ];
};

// OTP verification validation
const validateOTPVerification = () => {
  return [
    validatePhoneNumber(),
    validateOTP()
  ];
};

// Project validation
const validateProject = () => {
  return [
    body('name')
      .notEmpty()
      .withMessage('Project name is required')
      .isLength({ min: 3, max: 255 })
      .withMessage('Project name must be between 3 and 255 characters')
      .trim(),
    body('description')
      .optional()
      .isLength({ max: 1000 })
      .withMessage('Description cannot exceed 1000 characters')
      .trim(),
    body('status')
      .optional()
      .isIn(['planning', 'active', 'on_hold', 'completed', 'cancelled'])
      .withMessage('Invalid project status'),
    body('priority')
      .optional()
      .isIn(['low', 'medium', 'high', 'critical'])
      .withMessage('Invalid priority level'),
    body('start_date')
      .optional()
      .isISO8601()
      .withMessage('Invalid start date format'),
    body('end_date')
      .optional()
      .isISO8601()
      .withMessage('Invalid end date format'),
    body('budget')
      .optional()
      .isFloat({ min: 0 })
      .withMessage('Budget must be a positive number')
  ];
};

// Task validation
const validateTask = () => {
  return [
    body('title')
      .notEmpty()
      .withMessage('Task title is required')
      .isLength({ min: 3, max: 255 })
      .withMessage('Task title must be between 3 and 255 characters')
      .trim(),
    body('description')
      .optional()
      .isLength({ max: 2000 })
      .withMessage('Description cannot exceed 2000 characters')
      .trim(),
    body('status')
      .optional()
      .isIn(['todo', 'in_progress', 'review', 'done', 'cancelled', 'To Do', 'In Progress', 'Review', 'Done', 'Cancelled'])
      .withMessage('Invalid task status'),
    body('priority')
      .optional()
      .isIn(['low', 'medium', 'high', 'critical', 'Low', 'Medium', 'High', 'Critical'])
      .withMessage('Invalid priority level'),
    body('type')
      .optional()
      .isIn(['feature', 'bug', 'improvement', 'documentation'])
      .withMessage('Invalid task type'),
    body('story_points')
      .optional()
      .isInt({ min: 1, max: 100 })
      .withMessage('Story points must be between 1 and 100'),
    body('estimated_hours')
      .optional()
      .isFloat({ min: 0.1, max: 999.99 })
      .withMessage('Estimated hours must be between 0.1 and 999.99'),
    body('due_date')
      .optional()
      .isISO8601()
      .withMessage('Invalid due date format')
  ];
};

// Sprint validation
const validateSprint = () => {
  return [
    body('name')
      .notEmpty()
      .withMessage('Sprint name is required')
      .isLength({ min: 3, max: 255 })
      .withMessage('Sprint name must be between 3 and 255 characters')
      .trim(),
    body('description')
      .optional()
      .isLength({ max: 1000 })
      .withMessage('Description cannot exceed 1000 characters')
      .trim(),
    body('start_date')
      .notEmpty()
      .withMessage('Start date is required')
      .isISO8601()
      .withMessage('Invalid start date format'),
    body('end_date')
      .notEmpty()
      .withMessage('End date is required')
      .isISO8601()
      .withMessage('Invalid end date format'),
    body('goal')
      .optional()
      .isLength({ max: 500 })
      .withMessage('Goal cannot exceed 500 characters')
      .trim()
  ];
};

// ID parameter validation
const validateId = (paramName = 'id') => {
  return param(paramName)
    .isInt({ min: 1 })
    .withMessage(`${paramName} must be a positive integer`);
};

// Pagination validation
const validatePagination = () => {
  return [
    query('page')
      .optional()
      .isInt({ min: 1 })
      .withMessage('Page must be a positive integer'),
    query('limit')
      .optional()
      .isInt({ min: 1, max: 100 })
      .withMessage('Limit must be between 1 and 100')
  ];
};

module.exports = {
  handleValidationErrors,
  validatePhoneNumber,
  validateOTP,
  validateUserRegistration,
  validateLogin,
  validateOTPVerification,
  validateProject,
  validateTask,
  validateSprint,
  validateId,
  validatePagination
};
