import { ErrorHandler, Injectable } from '@angular/core';
import { ApmErrorHandler, ApmService } 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';

interface ApmError {
  id: string;
  name: string;
  message: string;
  type: string;
  method: string;
  timestamp: Date;
}
@Injectable()
export class CustomErrorHandler implements ErrorHandler {
  private _elasticConfig = environment.elastic;
  private _activeFeatures = environment.activeFeatures;
  constructor(
    private errorService: ErrorService,
    public apmErrorHandler: ApmErrorHandler,
    private apmService: ApmService
  ) {}

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

    if (this._elasticConfig && this._activeFeatures.includes(Feature.LOGGING)) {
      const { id, method, name, type, message, timestamp, data } = customError;
      const apmError: ApmError = { id, method, name, type, message, timestamp };

      this.apmService.apm.addLabels({ id, method, data });
      this.apmService.apm.captureError(apmError);
    }
  }
}
