import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent, HttpErrorResponse } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';
import { NavController } from '@ionic/angular';
import { Preferences } from '@capacitor/preferences';
import { getApps } from 'firebase/app';
import { getAuth, signOut as firebaseSignOut } from 'firebase/auth';

@Injectable({ providedIn: 'root' })
export class AuthInterceptorService implements HttpInterceptor {

  constructor(private navCtrl: NavController) {}

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(req).pipe(
      catchError((error: HttpErrorResponse) => {
        if (error.status === 401) {
          this.clearAndRedirect();
        }
        return throwError(() => error);
      })
    );
  }

  private clearAndRedirect() {
    Preferences.remove({ key: 'token' });
    if (getApps().length > 0) {
      firebaseSignOut(getAuth()).catch(() => {});
    }
    this.navCtrl.navigateRoot('/login');
  }
}
