import { body, validationResult } from "express-validator";

export const validate = (validations) => {
  return async (req, res, next) => {
    await Promise.all(validations.map((validation) => validation.run(req)));

    const errors = validationResult(req);
    if (errors.isEmpty()) {
      return next();
    }

    res.status(400).json({
      error: "Validation Error",
      details: errors.array().map((err) => ({
        field: err.path,
        message: err.msg,
      })),
    });
  };
};

// Auth validations
export const loginValidation = [
  body("email").isEmail().normalizeEmail().withMessage("Valid email required"),
  body("password")
    .isLength({ min: 6 })
    .withMessage("Password must be at least 6 characters"),
];

export const registerValidation = [
  body("name")
    .trim()
    .isLength({ min: 2 })
    .withMessage("Name must be at least 2 characters"),
  body("email").isEmail().normalizeEmail().withMessage("Valid email required"),
  body("password")
    .isLength({ min: 8 })
    .withMessage("Password must be at least 8 characters")
    .matches(/\d/)
    .withMessage("Password must contain at least one number"),
];

// Song validations
export const songValidation = [
  body("title").trim().notEmpty().withMessage("Title is required"),
  body("key")
    .optional()
    .isIn([
      "C",
      "C#",
      "Db",
      "D",
      "D#",
      "Eb",
      "E",
      "F",
      "F#",
      "Gb",
      "G",
      "G#",
      "Ab",
      "A",
      "A#",
      "Bb",
      "B",
    ]),
  body("tempo")
    .optional()
    .isInt({ min: 40, max: 220 })
    .withMessage("Tempo must be between 40 and 220"),
  body("lyrics").optional().isString(),
];

// List validations
export const listValidation = [
  body("name").trim().notEmpty().withMessage("Name is required"),
  body("date").optional().isISO8601().withMessage("Valid date required"),
  body("songs").optional().isArray(),
];
