import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router';
import { AuthenticationService } from '../services/api/authentication.service'; // Adjust the path as necessary
import { MatDialog, MatDialogRef } from '@angular/material/dialog';
import { LoginComponent } from '../components/login/login.component';

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

  async canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Promise<boolean> {
    try {
      const isAuthenticated = await this.authService.isAuthenticated();
      
      if (!isAuthenticated) {
        this.router.navigate(['/']);
      }
  
      return isAuthenticated;
    } catch (error) {
      return false;
    }
  }
  

  openLogin():  MatDialogRef<LoginComponent, any> {
    const dialogRef = this.dialog.open(LoginComponent, {
      width: "35vw",
      data: {
        afterLogin: () => {
          dialogRef.close();
        }
      }
    });
    return dialogRef;
  }
}