import { inject, Injectable } from '@angular/core';
import { Router, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';

import { AuthenticationService } from './user/authentication.service';

@Injectable({ providedIn: 'root' })
export class AuthGuard
{
  private readonly router = inject(Router);
  private readonly authService = inject(AuthenticationService);

  public canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot)
  {
    const currentUser = this.authService.currentUserValue;
    if (currentUser)
    {
      let permissionkey = route.data.permissionKey;
      if (permissionkey === undefined)
      {
        return true;
      }
      else
      {
        let found: boolean = false;
        let keys: string[] = permissionkey.split(',');
        for (const key of keys)
        {
          found = currentUser.moduleIds.includes(key);
          if (found)
            break;
        }

        if (found === false)
          this.router.navigate(['/accessdenied']);

        return true;
      }
    }
    else
    {
      //Not logged in so redirect to login page with the return url
      this.router.navigate(['/login'], { queryParams: { returnUrl: state.url } });
      return false;
    }
  }
}
