import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot } from '@angular/router';
import { ApplicationService } from '@core/application';
import { CrmCustomerService } from '@domain/crm';
import { map, take } from 'rxjs/operators';

@Injectable({ providedIn: 'root' })
export class CustomerCardGuard implements CanActivate {
  constructor(
    private router: Router,
    private customerService: CrmCustomerService,
    private readonly _applicationService: ApplicationService
  ) {}

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    const id = Number(route.params?.customerId);

    return this.customerService.getCustomer(id, 2).pipe(
      take(1),
      map((customer) => {
        if (!customer.result.features.find((feature) => feature.description === 'Kundenkarte')) {
          this.router.navigate(['/kunde', this._applicationService.activatedProcessId, 'customer', id]);
        }
        return true;
      })
    );
  }
}
