import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';
import { Observable } from 'rxjs';
import { AuthenticationService } from 'src/app/core/services/authentication.service';

@Injectable({
  providedIn: 'root'
})
export class AuthGuard implements CanActivate {
  constructor(
    private router: Router, 
    private authService: AuthenticationService
  ) {}

  canActivate(): boolean {
    console.log('🔒 AuthGuard vérifie l\'accès...');
    console.log('🔒 isAuthenticated:', this.authService.isAuthenticated);
    
    const token = localStorage.getItem('__token');
    const user = localStorage.getItem('__user');
    
    console.log('🔒 Token localStorage:', !!token);
    console.log('🔒 User localStorage:', !!user);
    
    // Vérifier l'AuthenticationService OU la présence directe du token
    const hasValidAuth = this.authService.isAuthenticated || (token && user);
    
    if (hasValidAuth) {
      console.log('✅ AuthGuard: Accès autorisé');
      return true;
    } else {
      console.log('❌ AuthGuard: Accès refusé, redirection vers /login');
      this.router.navigate(['/login']);
      return false;
    }
  }
}
