import { Injectable } from '@angular/core';
import {
  HttpRequest,
  HttpHandler,
  HttpEvent,
  HttpInterceptor, HttpErrorResponse, HttpResponse
} from '@angular/common/http';
import {Observable, throwError} from 'rxjs';
import {UserService} from "./user.service";
import { Router } from '@angular/router';
import {tap} from "rxjs/operators";

@Injectable()
export class AuthInterceptor implements HttpInterceptor {

  constructor(
    private userService: UserService,
    private router: Router,
  ) {}

  intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
    const token = this.userService.getAuthToken();
    if (token !== null && token !== undefined) {
      request = request.clone({headers: request.headers.set('Authorization',
          'Bearer ' + token)});
    }
    return next.handle(request).pipe(
      tap((event: any) => {
          if (event instanceof HttpResponse) {
            /*
            const res: ApiResponse<any> = event.body;
            if (res.success === 'KO'){
              return throwError('Api call failed');
                         */
          }
            return event;

        },
          (err: any) => {
          if (err instanceof HttpErrorResponse) {
            if (err.status === 401) {
              this.userService.logout();
              this.router.navigateByUrl('login');
            }
          }
        })
      )

      ;  }
}
