import { Injectable } from '@angular/core';
import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor, HttpResponse } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError, tap } from 'rxjs/operators';

import { AccountService, AlertService } from '@app/_services';

@Injectable()
export class ErrorInterceptor implements HttpInterceptor {
    constructor(
        private accountService: AccountService,
        private alertService: AlertService,
    ) {}

    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        return next.handle(request).pipe(
            tap(evt => {
                if (evt instanceof HttpResponse) {
                    if ((request.method === 'POST' || request.method === 'PATCH') && evt.status === 200) {
                        // Erfolgsmeldung für POST und PATCH
                        this.alertService.success('Saved', {autoClose: true});
                    }
                }
            }),
            catchError(err => {
                if ([401, 403].includes(err.status) && this.accountService.userValue) {
                    // auto logout if 401 or 403 response returned from api
                    this.accountService.logout();
                }
                console.log(err);
                this.alertService.error(err.message + ' - ' + err.error);

                const error = err.error?.message || err.statusText;
                return throwError(() => error);
            })
        );
    }
}