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 street validation
 */
const createStreetValidation = [
  body("name")
    .trim()
    .notEmpty()
    .withMessage("Street name is required")
    .isLength({ min: 2, max: 200 })
    .withMessage("Street name must be between 2 and 200 characters"),
  body("location")
    .notEmpty()
    .withMessage("Location is required")
    .isObject()
    .withMessage("Location must be an object"),
  body("location.type")
    .equals("Point")
    .withMessage("Location type must be 'Point'"),
  body("location.coordinates")
    .isArray({ min: 2, max: 2 })
    .withMessage("Coordinates must be an array with longitude and latitude"),
  body("location.coordinates.*")
    .isFloat()
    .withMessage("Coordinates must be valid numbers"),
  validate,
];

/**
 * Street ID validation
 */
const streetIdValidation = [
  param("id")
    .notEmpty()
    .withMessage("Street ID is required")
    .isString()
    .withMessage("Street ID must be a string"),
  validate,
];

module.exports = {
  createStreetValidation,
  streetIdValidation,
  validate,
};
