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 reward validation
 */
const createRewardValidation = [
  body("name")
    .trim()
    .notEmpty()
    .withMessage("Reward name is required")
    .isLength({ min: 2, max: 100 })
    .withMessage("Name must be between 2 and 100 characters"),
  body("description")
    .trim()
    .notEmpty()
    .withMessage("Reward description is required")
    .isLength({ min: 10, max: 500 })
    .withMessage("Description must be between 10 and 500 characters"),
  body("cost")
    .notEmpty()
    .withMessage("Cost is required")
    .isInt({ min: 1, max: 100000 })
    .withMessage("Cost must be a positive integer between 1 and 100000"),
  body("isPremium")
    .optional()
    .isBoolean()
    .withMessage("isPremium must be a boolean"),
  validate,
];

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

module.exports = {
  createRewardValidation,
  rewardIdValidation,
  validate,
};
