import { NgModule } from '@angular/core';
import { ApmModule, ApmService } from '@elastic/apm-rum-angular';
import { Feature } from '@msfa-enums/feature.enum';
import { environment } from '@msfa-environment';

@NgModule({
  imports: [ApmModule],
  exports: [ApmModule],
})
export class LoggingModule {
  private _elasticConfig = environment.elastic;
  private _activeFeatures = environment.activeFeatures;
  private _version = environment.version;

  constructor(private apmService: ApmService) {
    if (this._elasticConfig && this._activeFeatures.includes(Feature.LOGGING)) {
      const { serviceName, serverUrl } = this._elasticConfig;
      this.apmService.init({
        serviceName,
        serverUrl,
        environment: this.currentEnvironment,
        serviceVersion: this._version,
      });
    }
  }

  get currentEnvironment(): string {
    const defaultEnvironment = environment.elastic.environment;
    const testUrlRegEx = new RegExp(/(?:mina-sidor-fa-)(\w{1,})(?:\.tocp)/g);
    const testEnvironment = testUrlRegEx.exec(window.location.origin);

    if (testEnvironment?.length) {
      return testEnvironment[1].toUpperCase();
    }

    return defaultEnvironment;
  }
}
