import { Injectable } from '@angular/core';
import {
  // ActivatedRouteSnapshot,
  CanActivate,
  CanLoad,
  // Route,
  Router,
  // RouterStateSnapshot,
  // UrlSegment,
  UrlTree
} from '@angular/router';
import { User } from '@prisma/client';
import { Observable, of } from 'rxjs';
import { map } from 'rxjs/operators';

import { UserService } from '../user/user.service';

@Injectable()
export class AdminGuard implements CanLoad, CanActivate {
  constructor(
    private readonly $router: Router,
    private readonly $userService: UserService
  ) {}

  public canLoad(/*
    route: Route,
    segments: UrlSegment[]
  */): Observable<boolean | UrlTree> {
    return !this.$userService.user()
      ? of(false)
      : this.$userService.user()!.pipe(
          map((user: User | undefined) => {
            return user?.role === 'Admin' ? true : false;
          })
        );
  }

  public canActivate(/*
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  */):
    | Observable<boolean | UrlTree>
    | Promise<boolean | UrlTree>
    | boolean
    | UrlTree {
    return !this.$userService.user()
      ? of(false)
      : this.$userService.user()!.pipe(
          map((user: User | undefined) => {
            return user?.role === 'Admin' ? true : false;
          })
        );
  }
}
