import { HttpInterceptorFn } from '@angular/common/http';
import { ToastrService } from 'ngx-toastr';
import { inject } from '@angular/core';
import { catchError, throwError } from 'rxjs';
import { HttpErrorResponse } from '@angular/common/http';

export const httpErrorInterceptor: HttpInterceptorFn = (req, next) => {
  const toast = inject(ToastrService);

  return next(req).pipe(
    catchError((error: HttpErrorResponse) => {
      let errorMessage = '';

      if (error.error instanceof ErrorEvent) {
        errorMessage = `Client error: ${error.error.message}`;
      } else {
        switch (error.status) {
          case 0:
            errorMessage = 'Network error: Please check your internet connection.';
            break;
          case 401:
            errorMessage = 'Unauthorized: Please log in again.';
            break;
          case 403:
            errorMessage = 'Forbidden: You do not have permission to access this resource.';
            break;
          case 404:
            errorMessage = 'Resource not found: The requested resource does not exist.';
            break;
          case 500:
            errorMessage = 'Server error: Please try again later.';
            break;
          default:
            errorMessage = `Unexpected error: ${error.message}`;
        }
      }

      toast.error(errorMessage, 'Error', { timeOut: 3000 });

      return throwError(() => new Error(errorMessage));
    })
  );
};
