import { ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot } from "@angular/router";
import { catchError, map, Observable, of } from "rxjs";
import { AuthService } from "./auth.service";
import { Injectable } from "@angular/core";

// auth.guard.ts
@Injectable({
  providedIn: 'root',
})

export class AuthGuard implements CanActivate {
  

   constructor(private authService: AuthService, private router: Router) {}

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
    // Check if route is public first
    if (route.data['public']) {
      return of(true);
    }

    return this.authService.getUserDetails().pipe(
      map((response) => {
        if (response.status === 'success' && response.user?.id) {
          return true;
        }
        
        // Store the attempted URL for redirect after login
        this.authService.redirectUrl = state.url;
        this.router.navigate(['/login']);
        return false;
      }),
      catchError(() => {
        this.authService.redirectUrl = state.url;
        this.router.navigate(['/login']);
        return of(false);
      })
    );
  }
}