/**
 * Simple Zod Validation Pipe for NestJS
 * Just uses Zod as-is with clean error formatting
 */

import type { PipeTransform, ArgumentMetadata } from "@nestjs/common";
import { Injectable, BadRequestException } from "@nestjs/common";
import type { ZodSchema } from "zod";
import { ZodError } from "zod";

@Injectable()
export class ZodValidationPipe implements PipeTransform {
  constructor(private readonly schema: ZodSchema) {}

  transform(value: unknown, _metadata: ArgumentMetadata): unknown {
    try {
      return this.schema.parse(value);
    } catch (error) {
      if (error instanceof ZodError) {
        const errors = error.issues.map(issue => ({
          field: issue.path.join(".") || "root",
          message: issue.message,
          code: issue.code,
        }));

        throw new BadRequestException({
          message: "Validation failed",
          errors,
          statusCode: 400,
        });
      }

      const message = error instanceof Error ? error.message : "Validation failed";
      throw new BadRequestException(message);
    }
  }
}

/**
 * Factory function to create Zod pipe (main export)
 */
export const ZodPipe = (schema: ZodSchema) => new ZodValidationPipe(schema);

/**
 * Alternative factory function
 */
export const createZodPipe = (schema: ZodSchema) => new ZodValidationPipe(schema);
