import { Request, Response, NextFunction } from "express";
import { body, validationResult, query, param } from "express-validator";
import { catchAsyncError } from "../../middlewares/catchAsyncError";

export const validateCreateProduct = [
  body("name")
    .trim()
    .isLength({ min: 3, max: 100 })
    .withMessage("Product name must be between 3 and 100 characters"),
  
  body("description")
    .trim()
    .isLength({ min: 10 })
    .withMessage("Description must be at least 10 characters"),
  
  body("slug")
    .optional()
    .matches(/^[a-z0-9]+(?:-[a-z0-9]+)*$/)
    .withMessage("Slug must contain only lowercase letters, numbers, and hyphens"),
  
  body("category_id")
    .optional()
    .isUUID()
    .withMessage("Invalid category ID"),
  
  body("tags")
    .optional()
    .isArray()
    .withMessage("Tags must be an array"),
  
  body("version")
    .optional()
    .matches(/^v?[0-9]+\.[0-9]+\.[0-9]+(-[a-zA-Z0-9\.]+)?$/)
    .withMessage("Invalid version format"),
  
  body("website")
    .optional()
    .isURL()
    .withMessage("Invalid website URL"),
  
  body("github_url")
    .optional()
    .isURL()
    .withMessage("Invalid GitHub URL"),
  
  body("launch_date")
    .optional()
    .isISO8601()
    .withMessage("Invalid date format"),
  
  (req: Request, res: Response, next: NextFunction) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({
        success: false,
        errors: errors.array(),
      });
    }
    next();
  },
];

export const validateUpdateProduct = [
  param("id")
    .isUUID()
    .withMessage("Invalid product ID"),
  
  body("name")
    .optional()
    .trim()
    .isLength({ min: 3, max: 100 })
    .withMessage("Product name must be between 3 and 100 characters"),
  
  body("status")
    .optional()
    .isIn(["active", "draft", "archived", "pending"])
    .withMessage("Invalid status"),
  
  (req: Request, res: Response, next: NextFunction) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({
        success: false,
        errors: errors.array(),
      });
    }
    next();
  },
];

export const validateGetProducts = [
  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"),
  
  query("status")
    .optional()
    .isIn(["active", "draft", "archived", "pending"])
    .withMessage("Invalid status"),
  
  (req: Request, res: Response, next: NextFunction) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({
        success: false,
        errors: errors.array(),
      });
    }
    next();
  },
];