import { ToastrService } from 'ngx-toastr';
import { Injectable } from '@angular/core';
// import { catchError } from 'rxjs/operators';

import {
  HttpRequest,
  HttpHandler,
  HttpEvent,
  HttpInterceptor,
  HttpErrorResponse,
} from '@angular/common/http';
import { catchError, Observable, throwError } from 'rxjs';

@Injectable()
export class ErrorInterceptor implements HttpInterceptor {
  constructor(private readonly toastr: ToastrService) {}

  intercept(
    request: HttpRequest<any>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {
    return next.handle(request).pipe(
      catchError((error: HttpErrorResponse) => {
        let errorMsg = '';
        if (error?.error instanceof ErrorEvent) {
          errorMsg = `Error: ${error.error.message}`;
        } else {
          this.handleServerSideError(error);
          errorMsg = `Error Code: ${error?.status},  Message: ${error?.message}`;
        }
        return throwError(errorMsg);
      })
    );
  }

  handleServerSideError(error: HttpErrorResponse): void {
    console.log('error => ', error);
    switch (error?.status) {
      case 401:
        this.toastr.error('You are not authorized , Please login again !');

        break;

      case 403:
        this.toastr.error(error?.error?.errorMsg);
        break;

      case 402:
        this.toastr.error(error?.error?.errorMsg);
        break;

      case 422:
        this.toastr.error(error?.error?.errorMsg);
        break;

      case 400:
        this.toastr.error(error?.error?.errorMsg);
        break;

      case 412:
        this.toastr.error(error?.error?.errorMsg);
        break;

      case 500:
        this.toastr.error('SERVER ERROR, TRY AGAIN  !');
        break;

      case 425:
        this.toastr.error(error?.error?.errorMsg);
        break;

      case 415:
        this.toastr.error(error?.error?.errorMsg);
        break;

      case 404:
        this.toastr.error(error?.error?.errorMsg);
        break;
    }
  }
}
