import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot } from '@angular/router';
import { ApplicationService } from '@core/application';
import { first } from 'rxjs/operators';

@Injectable({ providedIn: 'root' })
export class CanActivateCartGuard implements CanActivate {
  constructor(private readonly _applicationService: ApplicationService, private readonly _router: Router) {}

  async canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    const processes = await this._applicationService.getProcesses$('customer').pipe(first()).toPromise();
    let lastActivatedProcessId = (
      await this._applicationService.getLastActivatedProcessWithSectionAndType$('customer', 'cart').pipe(first()).toPromise()
    )?.id;
    if (!lastActivatedProcessId) {
      lastActivatedProcessId = Date.now();
      await this._applicationService.createProcess({
        id: lastActivatedProcessId,
        type: 'cart',
        section: 'customer',
        name: `Vorgang ${processes.length + 1}`,
      });
    }
    await this._router.navigate(['/kunde', lastActivatedProcessId, 'cart']);
    return false;
  }
}
