import {
  ArgumentsHost,
  Catch,
  ExceptionFilter,
  HttpException,
  HttpStatus,
  Injectable,
  Logger,
} from '@nestjs/common';
import type { Response } from 'express';
import { Inject } from '@nestjs/common';
import { APP_CONFIG, type AppConfig } from '../../config/app.config.js';

type ErrorBody = {
  success: false;
  statusCode: number;
  message: string | string[];
  error: string;
};

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

  constructor(@Inject(APP_CONFIG) private readonly config: AppConfig) {}

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

    const { statusCode, message, error } = this.normalize(exception);

    if (statusCode >= 500) {
      this.logger.error(
        this.safeErrorMessage(exception),
        exception instanceof Error ? exception.stack : undefined,
      );
    } else {
      this.logger.warn(this.safeErrorMessage(exception));
    }

    const body: ErrorBody = {
      success: false,
      statusCode,
      message,
      error,
    };

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

  private normalize(exception: unknown): {
    statusCode: number;
    message: string | string[];
    error: string;
  } {
    if (exception instanceof HttpException) {
      const statusCode = exception.getStatus();
      const response = exception.getResponse();

      if (typeof response === 'string') {
        return {
          statusCode,
          message: response,
          error: HttpStatus[statusCode] ?? 'Error',
        };
      }

      if (typeof response === 'object' && response !== null) {
        const payload = response as {
          message?: string | string[];
          error?: string;
        };

        return {
          statusCode,
          message: payload.message ?? exception.message,
          error: payload.error ?? HttpStatus[statusCode] ?? 'Error',
        };
      }

      return {
        statusCode,
        message: exception.message,
        error: HttpStatus[statusCode] ?? 'Error',
      };
    }

    const isProduction = this.config.nodeEnv === 'production';
    return {
      statusCode: HttpStatus.INTERNAL_SERVER_ERROR,
      message: isProduction
        ? 'Internal server error'
        : this.safeErrorMessage(exception),
      error: 'Internal Server Error',
    };
  }

  private safeErrorMessage(exception: unknown): string {
    if (!(exception instanceof Error)) {
      return 'Unexpected error';
    }

    const message = exception.message;
    if (
      /password|secret|token|authorization|database_url|connection string/i.test(
        message,
      )
    ) {
      return 'Unexpected error';
    }

    return message;
  }
}
