import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { SELECTED_ORGANIZATION_NUMBER_KEY } from '@msfa-constants/local-storage-keys';
import { environment } from '@msfa-environment';
import { AuthenticationService } from '@msfa-services/api/authentication.service';
import { Observable } from 'rxjs';

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
  constructor(private authenticationService: AuthenticationService) {}

  private get authorizationToken(): { Authorization: string } | null {
    const bearerToken = this.authenticationService.currentAuthorizationToken;

    return bearerToken ? { Authorization: `Bearer ${bearerToken}` } : null;
  }

  private get selectedOrganizationNumber(): { orgnr: string } | null {
    const orgnr = localStorage.getItem(SELECTED_ORGANIZATION_NUMBER_KEY);

    return orgnr ? { orgnr } : null;
  }

  intercept(req: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
    const clonedRequest: HttpRequest<unknown> = req.clone({
      setHeaders: { ...environment.api.headers, ...this.authorizationToken, ...this.selectedOrganizationNumber },
    });

    return next.handle(clonedRequest);
  }
}
