import {
  ArgumentsHost,
  Catch,
  ExceptionFilter,
  HttpException,
  HttpStatus,
} from '@nestjs/common';
import * as _ from 'lodash';
import { Request, Response } from 'express';

@Catch()
export class GlobalExceptionFilter implements ExceptionFilter {
  catch(exception: unknown, host: ArgumentsHost): void {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse<Response>();
    const request = ctx.getRequest<Request>();

    const httpStatus =
      exception instanceof HttpException
        ? exception.getStatus()
        : HttpStatus.INTERNAL_SERVER_ERROR;

    const message =
      exception instanceof HttpException
        ? exception.getResponse()
        : (exception as Error).message;

    const responseBody = {
      statusCode: httpStatus,
      timestamp: new Date().toISOString(),
      path: request.url,
      message,
    };

    const status =
      exception instanceof HttpException ? exception.getStatus() : 500;

    // Use lodash's get method to retrieve the 'message' property from the exception object.
    // If the 'message' property does not exist, a default message 'no message in exception - GlobalExceptionFilter' is used.
    const errMessage =
      exception instanceof HttpException
        ? JSON.stringify(exception.getResponse())
        : _.get(
            exception,
            'message',
            'no message in exception - GlobalExceptionFilter',
          );

    // ...

    // logger.error('Error in Global Exception Filter: ', {
    //   statusCode: HttpStatus.INTERNAL_SERVER_ERROR,
    //   timestamp: new Date().toISOString(),
    //   path: request.url,
    //   message: errMessage,
    // });

    response.status(status).json({ message: errMessage, ...responseBody });
  }
}
