import type { RequestHandler } from 'express';
import type { Schema } from 'joi';
import { errorResponse } from '../utils/response.js';

// Schema (not ObjectSchema) so this also accepts Joi.alternatives(), used
// where a body is one of a few distinct shapes (e.g. suspend vs reactivate).
export default function validate(schema: Schema): RequestHandler {
  return (req, res, next) => {
    const { value, error } = schema.validate(req.body, { abortEarly: false });

    if (error) {
      const errors = error.details.map((detail) => ({
        field: detail.path.join('.'),
        message: detail.message,
      }));
      return void errorResponse(res, 'Validation failed', 400, errors);
    }

    req.body = value;
    next();
  };
}
