import {
  ExceptionFilter,
  Catch,
  ArgumentsHost,
  HttpException,
  HttpStatus,
} from '@nestjs/common';
import { EventBus } from '@nestjs/cqrs';
import { Response } from 'express';
import { apm } from 'src/core/apm';
import { OPERATION } from 'src/core/strings/constants/base.constants';
import { RecordErrorLog } from 'src/modules/configuration/log/domain/entities/error-log.event';

@Catch()
export class HttpExceptionFilter implements ExceptionFilter {
  constructor(private eventBus: EventBus) {}

  catch(exception: any, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse<Response>();
    let status: HttpStatus;
    let body: any;
    let exceptionResponse;

    try {
      exceptionResponse = JSON.parse(exception.message);
    } catch (error) {}

    if (exception instanceof HttpException) {
      if (Array.isArray(exception.getResponse()['message'])) {
        exception.getResponse()['message'] = exception
          .getResponse()
          ['message'].join(',');
      }

      status = exception.getStatus();
      body = exception.getResponse();
    } else if (typeof exceptionResponse == 'object') {
      status = exceptionResponse.statusCode;
      body = exceptionResponse;
    } else {
      status = HttpStatus.FORBIDDEN;
      body = {
        statusCode: HttpStatus.FORBIDDEN,
        message: exception.message,
        error: exception.name,
      };
    }

    // this.eventBus.publish(
    //   new RecordErrorLog({
    //     id: '',
    //     old: null,
    //     data: null,
    //     user: null,
    //     description: '',
    //     module: null,
    //     op: OPERATION.CREATE,
    //   }),
    // );

    response.status(status).json(body);
  }
}
