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

const validate = (req, res, next) => {
  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    return res.status(400).json({
      success: false,
      errors: errors.array().map((err) => ({
        field: err.path,
        message: err.msg,
      })),
    });
  }
  next();
};

/**
 * Create event validation
 */
const createEventValidation = [
  body("title")
    .trim()
    .notEmpty()
    .withMessage("Event title is required")
    .isLength({ min: 3, max: 200 })
    .withMessage("Title must be between 3 and 200 characters"),
  body("description")
    .trim()
    .notEmpty()
    .withMessage("Event description is required")
    .isLength({ min: 10, max: 1000 })
    .withMessage("Description must be between 10 and 1000 characters"),
  body("date")
    .notEmpty()
    .withMessage("Event date is required")
    .isISO8601()
    .withMessage("Date must be a valid ISO 8601 date")
    .custom((value) => {
      if (new Date(value) < new Date()) {
        throw new Error("Event date must be in the future");
      }
      return true;
    }),
  body("location")
    .trim()
    .notEmpty()
    .withMessage("Event location is required")
    .isLength({ min: 3, max: 200 })
    .withMessage("Location must be between 3 and 200 characters"),
  validate,
];

/**
 * Event ID validation
 */
const eventIdValidation = [
  param("id")
    .notEmpty()
    .withMessage("Event ID is required")
    .matches(/^(event_[a-zA-Z0-9]+|[0-9a-fA-F]{24})$/)
    .withMessage("Invalid event ID format"),
  validate,
];

module.exports = {
  createEventValidation,
  eventIdValidation,
  validate,
};
