/**
 * Setup Validation Rules
 * Input validation rules for system setup endpoint
 */

// Import express-validator for request validation
const { body, validationResult } = require('express-validator');
// Import custom validation error class
const { ValidationError } = require('../../../utils/errors');

/**
 * Validation middleware wrapper
 * Checks validation results and returns errors if validation fails
 * @param {Object} req - Express request object
 * @param {Object} res - Express response object
 * @param {Function} next - Express next middleware function
 */
const validate = (req, res, next) => {
  // Get validation errors from request
  const errors = validationResult(req);
  
  // If validation errors exist, return error response
  if (!errors.isEmpty()) {
    // Format validation errors
    const formattedErrors = errors.array().map((error) => ({
      field: error.path || error.param, // Field name
      message: error.msg, // Error message
      value: error.value, // Invalid value
    }));
    
    // Throw validation error with formatted errors
    throw new ValidationError('Validation failed', formattedErrors);
  }
  
  // If validation passes, proceed to next middleware
  next();
};

/**
 * Setup validation rules
 * Validates admin user data for system initialization
 */
const validateSetup = [
  // Validate username field
  body('username')
    .trim() // Remove whitespace
    .notEmpty() // Username is required
    .withMessage('Username is required') // Error message
    .isLength({ min: 3, max: 100 }) // Username length validation
    .withMessage('Username must be between 3 and 100 characters') // Error message
    .matches(/^[a-zA-Z0-9_]+$/) // Username can only contain letters, numbers, and underscores
    .withMessage('Username can only contain letters, numbers, and underscores'), // Error message
  
  // Validate email field
  body('email')
    .trim() // Remove whitespace
    .notEmpty() // Email is required
    .withMessage('Email is required') // Error message
    .isEmail() // Validate email format
    .withMessage('Invalid email format') // Error message
    .normalizeEmail(), // Normalize email (lowercase, etc.)
  
  // Validate password field
  body('password')
    .notEmpty() // Password is required
    .withMessage('Password is required') // Error message
    .isLength({ min: 6 }) // Minimum password length
    .withMessage('Password must be at least 6 characters'), // Error message
  
  // Validate full_name field
  body('full_name')
    .trim() // Remove whitespace
    .notEmpty() // Full name is required
    .withMessage('Full name is required') // Error message
    .isLength({ max: 150 }) // Maximum length
    .withMessage('Full name must not exceed 150 characters'), // Error message
  
  // Validate pin_code field (optional)
  body('pin_code')
    .optional() // Field is optional
    .isLength({ min: 4, max: 6 }) // PIN code length (4-6 digits)
    .withMessage('PIN code must be between 4 and 6 characters') // Error message
    .isNumeric() // PIN code must be numeric
    .withMessage('PIN code must be numeric'), // Error message
  
  // Run validation middleware
  validate,
];

// Export validation rules
module.exports = {
  validateSetup, // Setup validation rules
};

