import { Injectable } from "@angular/core";
import {
  HttpRequest,
  HttpHandler,
  HttpEvent,
  HttpErrorResponse,
} from "@angular/common/http";
import { Observable, catchError, retry, throwError } from "rxjs";
import { AuthService } from "../services/auth.service";
import { Router } from "@angular/router";
import { HelpersService } from "../services/helpers.service";

@Injectable()
export class ErrorInterceptor {
  constructor(
    private auth: AuthService,
    private router: Router,
    private helpers: HelpersService
  ) {}

  intercept(
    request: HttpRequest<unknown>,
    next: HttpHandler
  ): Observable<HttpEvent<unknown>> {
    return next.handle(request).pipe(
      retry(1),
      catchError((error: HttpErrorResponse) => {
        if (error.status === 401) {
          this.auth.removeToken();
          this.router.navigate(["/auth"], {
            queryParams: { url: this.router.url },
          });
          this.helpers.toast("error", "Sesi Anda telah berakhir");
        }
        let message = "";
        if (error.error instanceof ErrorEvent) {
          // handle client-side error
          message = `Error: ${error.error.message}`;
        } else {
          // handle server-side error
          message = `Error Status: ${error.status}\nMessage: ${error.message}`;
        }
        return throwError(() => error);
      })
    );
  }
}
