import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';
import { UserService } from '@msfa-services/api/user.service';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';

@Injectable({
  providedIn: 'root',
})
export class OrganizationGuard implements CanActivate {
  constructor(private router: Router, private userService: UserService) {}

  canActivate(): Observable<boolean> {
    return this.userService.selectedOrganization$.pipe(
      map(organization => {
        if (!organization) {
          void this.router.navigateByUrl(`/organization-picker`);
        }
        return true;
      })
    );
  }
}
