import { Injectable } from '@angular/core';
import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http';
import { AuthService } from '../auth/auth.service';
import { EMPTY, Observable } from 'rxjs';
import moment from 'moment';
import { catchError, mergeMap } from 'rxjs/operators';
import { NotificationsService } from '../services/notifications.service';

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
  constructor(
    private auth$: AuthService,
    private notifications$: NotificationsService
  ) { }

  intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
    if (!request.url.includes('/auth/apiToken')) {
      if (this.auth$.apiTokenExpirationTime?.isBefore(moment.utc())) {
        return this.auth$.getAPITokenObservable().pipe(
          mergeMap(() => {
            return next.handle(request.clone({
              headers: request.headers.set('Authorization', `Bearer ${this.auth$.apiToken}`),
            }));
          }),
          catchError(() => {
            this.notifications$.add({
              text: "User session is expired and unable to restore. Please restart the app.",
              btn: "Restart",
              action: () => { window.location.reload(); },
              duration: 5000,
            });
            return EMPTY;
          })
        );
      } else {
        return next.handle(request.clone({
          headers: request.headers.set('Authorization', `Bearer ${this.auth$.apiToken}`),
        }));
      }
    } else {
      return next.handle(request);
    }
  }
}

