import { ArgumentsHost, Catch, HttpException, Logger } from '@nestjs/common'
import { BaseExceptionFilter } from '@nestjs/core'

import { ZodSerializationException, ZodValidationException } from 'nestjs-zod'
import z from 'zod'

@Catch(HttpException)
export class ZodExceptionFilter extends BaseExceptionFilter {
  private readonly logger = new Logger(ZodExceptionFilter.name)

  override catch(exception: HttpException, host: ArgumentsHost) {
    if (exception instanceof ZodValidationException) {
      const zodError = exception.getZodError()
      if (zodError instanceof z.ZodError) {
        // Extract meaningful error messages from Zod errors
        const errors = zodError.issues.map((issue) => ({
          path: issue.path.join('.'),
          message: issue.message,
        }))
        this.logger.warn('ZodValidationException: ' + JSON.stringify(errors))

        // Create a more informative response
        const response = host.switchToHttp().getResponse()
        response.status(400).send({
          statusCode: 400,
          message: 'Validation failed',
          errors,
        })
        return
      }
    }

    if (exception instanceof ZodSerializationException) {
      const zodError = exception.getZodError()
      if (zodError instanceof z.ZodError) {
        this.logger.error('ZodSerializationException: ' + zodError.message)
      }
    }

    super.catch(exception, host)
  }
}
