import { ErrorHandler, Injectable } from '@angular/core';
import { ApmErrorHandler } from '@elastic/apm-rum-angular';
import { Feature } from '@msfa-enums/feature.enum';
import { environment } from '@msfa-environment';
import { CustomError } from '@msfa-models/error/custom-error';
import { ErrorService } from '@msfa-services/error.service';

@Injectable()
export class CustomErrorHandler implements ErrorHandler {
  private _elasticConfig = environment.elastic;
  private _activeFeatures = environment.activeFeatures;
  constructor(private errorService: ErrorService, public apmErrorHandler: ApmErrorHandler) {}

  handleError(customError: CustomError & { ngDebugContext: unknown }): void {
    if (!customError.avoidToast) {
      this.errorService.add(customError);
    }

    if (this._elasticConfig && this._activeFeatures.includes(Feature.LOGGING)) {
      this.apmErrorHandler.handleError(customError);
    }
  }
}
