const Joi = require('joi');

const roleValidationSchema = Joi.object({
  name: Joi.string()
  .required()
  .max(100)
  .trim()
  .messages({
    'any.required': 'Role name is required.',
    'string.empty': 'Role name cannot be empty.',
    'string.max': 'Role name cannot exceed {#limit} characters.',
  }),
  displayName: Joi.string()
  .required()
  .max(100)
  .trim()
  .messages({
    'any.required': 'Display name is required.',
    'string.empty': 'Display name cannot be empty.',
    'string.max': 'Display name cannot exceed {#limit} characters.',
  }),
  description: Joi.string()
  .optional()
  .max(500)
  .trim()
  .messages({
    'string.max': 'Description cannot exceed {#limit} characters.',
}),
  permissions: Joi.array().items(
    Joi.object({
      resource: Joi.string().required(),
      actions: Joi.array().items(Joi.string().valid('view', 'add', 'edit', 'delete', 'update')).required()
    })
  )
  .optional()
  .messages({
    'array.base': 'Permissions must be an array.',
    'object.base': 'Each permission must be an object with resource and actions.'
  }),
  isActive: Joi.boolean().optional()
});

const roleValidation = (req, res, next) => {
  const { error, value } = roleValidationSchema.validate(req.body, {
    abortEarly: false, // Collect all errors instead of stopping at the first
  });
  if (error) {
    const errorMessages = error.details.map(err => err.message);
    return res.status(400).json({
      message: 'Validation failed',
      errors: errorMessages,
    });
  }
  req.body = value; // Replace the request body with the validated value
  next(); // Proceed to the next middleware or route handler
}

const updateRoleValidationSchema = roleValidationSchema.fork(['name', 'displayName'], (field) => field.optional());
const updateRoleValidation = (req, res, next) => {
  const { error, value } = updateRoleValidationSchema.validate(req.body, {
    abortEarly: false,
  });
  if (error) {
    const errorMessages = error.details.map(err => err.message);
    return res.status(400).json({
      message: 'Validation failed',
      errors: errorMessages,
    });
  }
  req.body = value;
  next();
}

module.exports = {
  roleValidation,
  updateRoleValidation
};