import { Request, Response, NextFunction } from 'express';
import { ZodSchema, ZodError } from 'zod';
import { ResponseHandler } from '../utils/responseHandler';

export const validateRequest = (schema: ZodSchema) => {
  return (req: Request, res: Response, next: NextFunction) => {
    try {
      schema.parse({
        body: req.body,
        query: req.query,
        params: req.params,
      });
      next();
    } catch (error) {
      if (error instanceof ZodError) {
        const errorMessage = error.errors.map(err => err.message).join(', ');
        ResponseHandler.validationError(res, 'Validation failed', errorMessage);
      } else {
        const errorMessage = error instanceof Error ? error.message : 'Unknown error';
        ResponseHandler.error(res, 'Validation error', 400, errorMessage);
      }
    }
  };
};

export const validateBody = (schema: ZodSchema) => {
  return (req: Request, res: Response, next: NextFunction) => {
    try {
      req.body = schema.parse(req.body);
      next();
    } catch (error) {
      if (error instanceof ZodError) {
        const errorMessage = error.errors.map(err => err.message).join(', ');
        ResponseHandler.validationError(res, 'Request body validation failed', errorMessage);
      } else {
        const errorMessage = error instanceof Error ? error.message : 'Unknown error';
        ResponseHandler.error(res, 'Validation error', 400, errorMessage);
      }
    }
  };
};

export const validateQuery = (schema: ZodSchema) => {
  return (req: Request, res: Response, next: NextFunction) => {
    try {
      req.query = schema.parse(req.query);
      next();
    } catch (error) {
      if (error instanceof ZodError) {
        const errorMessage = error.errors.map(err => err.message).join(', ');
        ResponseHandler.validationError(res, 'Query parameters validation failed', errorMessage);
      } else {
        const errorMessage = error instanceof Error ? error.message : 'Unknown error';
        ResponseHandler.error(res, 'Validation error', 400, errorMessage);
      }
    }
  };
};

export const validateParams = (schema: ZodSchema) => {
  return (req: Request, res: Response, next: NextFunction) => {
    try {
      req.params = schema.parse(req.params);
      next();
    } catch (error) {
      if (error instanceof ZodError) {
        const errorMessage = error.errors.map(err => err.message).join(', ');
        ResponseHandler.validationError(res, 'URL parameters validation failed', errorMessage);
      } else {
        const errorMessage = error instanceof Error ? error.message : 'Unknown error';
        ResponseHandler.error(res, 'Validation error', 400, errorMessage);
      }
    }
  };
};
