import {
  ExceptionFilter,
  Catch,
  ArgumentsHost,
  HttpException,
  HttpStatus,
  Logger,
} from '@nestjs/common';
import { Request, Response } from 'express';
import { DomainException } from '../exceptions/domain.exception';
import { ApplicationException } from '../exceptions/application.exception';

@Catch()
export class GlobalExceptionFilter implements ExceptionFilter {
  private readonly logger = new Logger(GlobalExceptionFilter.name);

  catch(exception: unknown, host: ArgumentsHost): void {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse<Response>();
    const request = ctx.getRequest<Request>();

    let statusCode = HttpStatus.INTERNAL_SERVER_ERROR;
    let message = 'Internal server error';
    let error = 'Internal Server Error';

    if (exception instanceof HttpException) {
      statusCode = exception.getStatus();
      const exceptionResponse = exception.getResponse();
      message = typeof exceptionResponse === 'string'
        ? exceptionResponse
        : (exceptionResponse as any).message || message;
      error = HttpStatus[statusCode] || error;
    } else if (exception instanceof DomainException) {
      statusCode = HttpStatus.UNPROCESSABLE_ENTITY;
      message = exception.message;
      error = 'Domain Error';
    } else if (exception instanceof ApplicationException) {
      statusCode = HttpStatus.BAD_REQUEST;
      message = exception.message;
      error = 'Application Error';
    } else if (exception instanceof Error) {
      message = process.env.NODE_ENV === 'production' ? 'Internal server error' : exception.message;
    }

    if (statusCode >= 500) {
      this.logger.error(`[${request.method}] ${request.url} - ${statusCode} - ${message}`,
        exception instanceof Error ? exception.stack : undefined);
    } else if (statusCode >= 400) {
      this.logger.warn(`[${request.method}] ${request.url} - ${statusCode} - ${message}`);
    }

    response.status(statusCode).json({
      statusCode,
      timestamp: new Date().toISOString(),
      path: request.url,
      method: request.method,
      message,
      error,
    });
  }
}
