
import {HttpRequest, HttpHandlerFn, HttpEvent, HttpErrorResponse} from '@angular/common/http';
import {catchError, Observable, throwError} from 'rxjs';
import {Router} from '@angular/router';
import {inject} from '@angular/core';
import {USER_TOKEN} from '../data/login/localStorage.namespace';
import {LocalStorageService} from './localStorage.service';

export function InterceptorService(req: HttpRequest<unknown>, next: HttpHandlerFn): Observable<HttpEvent<unknown>> {
  const router = inject(Router);
  const storage = inject(LocalStorageService);
  const headers = req.headers.set('Authorization', String(storage.getItem(USER_TOKEN)));
  const newReq = req.clone({headers});

  return next(newReq).pipe(
    catchError((error: HttpErrorResponse) => {
      // 响应错误处理
      if (error.status === 401) {
        router.navigate(['/error/401']);
      }
      if (error.status == 403) {
        router.navigate(['/error/403']);
      }
      if (error.status == 404) {
        router.navigate(['/error/404']);
      }
      if (error.status == 500) {
        router.navigate(['/error/500']);
      }
      return throwError(() => error);
    })
  );


}
