import { Request, Response, NextFunction } from 'express';
import { ZodSchema, ZodError } from 'zod';
import { AppError } from './error-handler';

export function validate(schema: ZodSchema, source: 'body' | 'query' | 'params' = 'body') {
  return (req: Request, _res: Response, next: NextFunction) => {
    try {
      const data = schema.parse(req[source]);
      req[source] = data;
      next();
    } catch (err) {
      if (err instanceof ZodError) {
        // Sanitize validation errors - only expose field count, not detailed messages
        const fieldCount = err.errors.length;
        throw new AppError(400, `Invalid request data: ${fieldCount} field(s) failed validation`, 'VALIDATION_ERROR');
      }
      throw err;
    }
  };
}
