import { AuthService } from '../service/auth.service';
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';

@Injectable()
export class ErrorInterceptor implements HttpInterceptor {
	constructor(
		private authenticationService: AuthService,
		private router: Router
	) {}

	intercept(
		request: HttpRequest<any>,
		next: HttpHandler
	): Observable<HttpEvent<any>> {
		return next.handle(request).pipe(
			catchError((err) => {
				if (err.status === 401) {
					const returnUrl = this.router.url;
					this.authenticationService.logout();
					void this.router.navigate(['/authentication/signin'], {
						queryParams: returnUrl && returnUrl !== '/'
							? { r: returnUrl }
							: undefined,
					});
				}

				let error = err.error || err.message || err.statusText;

				if (!error) {
					console.log('not parsed error', err);
				}
				return throwError(() => error);
			})
		);
	}
}
