/**
 * Product Validation Schemas
 * 
 * Purpose: Validate product-related request data before it reaches controllers
 * Prevents invalid data from entering the system
 */

import { z } from 'zod';
import { Request, Response, NextFunction } from 'express';

export const createProductSchema = z.object({
  name: z.string().min(1).max(200),
  description: z.string().min(10).max(5000),
  price: z.number().positive(),
  category: z.string().min(1),
  stock: z.number().int().nonnegative(),
  images: z.array(z.string().url()).optional(),
});

export const updateProductSchema = createProductSchema.partial();

export function validateCreateProduct(req: Request, res: Response, next: NextFunction): void {
  try {
    createProductSchema.parse(req.body);
    next();
  } catch (error) {
    if (error instanceof z.ZodError) {
      res.status(400).json({
        success: false,
        error: 'Validation failed',
        details: error.errors,
      });
      return;
    }
    next(error);
  }
}

export function validateUpdateProduct(req: Request, res: Response, next: NextFunction): void {
  try {
    updateProductSchema.parse(req.body);
    next();
  } catch (error) {
    if (error instanceof z.ZodError) {
      res.status(400).json({
        success: false,
        error: 'Validation failed',
        details: error.errors,
      });
      return;
    }
    next(error);
  }
}
