/*
 * Copyright (C) 2018 Robert Bosch GmbH Copyright (C) 2018 Robert Bosch Manufacturing Solutions GmbH, Germany. All rights reserved.
 */

import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http';
import { Inject } from '@angular/core';
import { Observable } from 'rxjs';
import { first, mergeMap } from 'rxjs/operators';
import { AUTH_OPTIONS } from './auth-options.token';
import { IAuthModuleConfig } from './auth.options';
import { AuthenticationService } from './services/authentication.service';

export class AuthInterceptor implements HttpInterceptor {
  constructor(
    @Inject(AUTH_OPTIONS) private config: IAuthModuleConfig,
    private authenticationService: AuthenticationService
  ) {}

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return this.getToken().pipe(
      mergeMap((token) => {
        if (
          !token ||
          req.headers.has(this.config.headerName) ||
          req.url.includes('oauth/token') ||
          (!!this.config.addAuthHeader && !this.config.addAuthHeader(req))
        ) {
          return next.handle(req);
        }

        const cloned = req.clone({
          headers: req.headers.set(this.config.headerName, `${this.config.authScheme} ${token}`),
        });

        return next.handle(cloned);
      })
    );
  }

  private getToken(): Observable<string | undefined> {
    return this.authenticationService.getAccessToken().pipe(first());
  }
}
