import { Injectable } from '@angular/core';
import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http';

import { environment } from '../../environments/environment';
import { Observable } from 'rxjs';
import { SecurityService } from '../logic/services/security.service';

@Injectable()
export class AuthBearerInterceptor implements HttpInterceptor {

  private handleWithBearer(token: string, req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const request = req.clone({setHeaders: {'Authorization': `Bearer ${token}` }, withCredentials: true});
    return next.handle(request);
  }

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    if (req.url.startsWith(`${environment.api}/security/auth`)) {
      return next.handle(req.clone({withCredentials: true}));
    }

    const token = SecurityService.auth ? SecurityService.auth.accessToken : null;
    return this.handleWithBearer(token, req, next);
  }
}
