import { Injectable, PipeTransform } from '@nestjs/common';
import { ZodSchema } from 'zod';
import { logger } from '../../config';

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

  transform(value: unknown) {
    let parsedValue: unknown = value;

    // If it's a string, try to parse it as JSON
    if (typeof value === 'string') {
      try {
        parsedValue = JSON.parse(value);
        // eslint-disable-next-line @typescript-eslint/no-unused-vars
      } catch (err) {
        logger.error('zod validation pipe error ' + err);
        // Not valid JSON, return as is
        return value;
      }
    }

    // Only validate if it's an object
    if (typeof parsedValue === 'object' && parsedValue !== null) {
      const result = this.schema.safeParse(parsedValue);
      if (!result.success) {
        logger.error('zod validation pipe error ' + result.error);
        throw result.error;
      }
      logger.log('zod validation pipe success ' + result.data);
      return result.data;
    }

    // If it's not an object after parsing, just return as is
    return parsedValue;
  }
}
