import { Injectable } from "@angular/core";
import {
  HttpEvent,
  HttpHandler,
  HttpInterceptor,
  HttpRequest,
  HttpResponse,
  HttpErrorResponse,
} from "@angular/common/http";
import { Observable, throwError } from "rxjs";
import { catchError, tap } from "rxjs/operators";
import { Router } from "@angular/router";
import { AuthenticationService } from "../core/services/authentication.service";
import { ToastService } from "../services/toast.service";

@Injectable()
export class HttpLoggerInterceptor implements HttpInterceptor {
  private callCount: { [key: string]: number } = {}; // Stocke les appels par URL
  private isRedirecting = false;

  constructor(
    private router: Router,
    private authService: AuthenticationService,
    private toast: ToastService
  ) {}

  intercept(
    request: HttpRequest<any>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {
    return next.handle(request).pipe(
      tap((event: HttpEvent<any>) => {
        if (event instanceof HttpResponse) {
          // Logger les réponses si nécessaire
          // console.log('Response:', event);
        }
      }),
      catchError((error: HttpErrorResponse) => {
        console.error('HTTP Logger - Error:', error);

        if (error.status === 401 && !this.isRedirecting) {
          console.error('❌ 401 Unauthorized - Redirection vers login');
          this.isRedirecting = true;

          this.toast.showError('Session expirée. Veuillez vous reconnecter.');

          // Nettoyer la session
          this.authService.logout().subscribe({
            next: () => {
              console.log('🚪 Logout réussi, navigation vers /login');
              this.router.navigate(['/login']).then(success => {
                if (success) {
                  console.log('✅ Navigation vers /login réussie');
                  this.isRedirecting = false;
                } else {
                  console.error('❌ Navigation vers /login échouée, fallback');
                  window.location.href = '/login';
                }
              });
            },
            error: (err) => {
              console.error('❌ Erreur lors du logout:', err);
              window.location.href = '/login';
            }
          });
        }

        return throwError(() => error);
      })
    );
  }
}
