import { Request, Response, NextFunction } from 'express';
import { validationResult } from 'express-validator';
import { AppError } from './error.js';
import { ERROR_CODES, HTTP_STATUS } from '@media-manager/shared';

export function validateRequest(req: Request, _res: Response, next: NextFunction): void {
  const errors = validationResult(req);
  
  if (!errors.isEmpty()) {
    const messages = errors.array().map(err => {
      if ('msg' in err) {
        return err.msg;
      }
      return 'Validation error';
    });
    
    throw new AppError(
      messages.join(', '),
      HTTP_STATUS.BAD_REQUEST,
      ERROR_CODES.VALIDATION
    );
  }
  
  next();
}
