import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, CanActivateChild, Router, RouterStateSnapshot } from '@angular/router';
import { ApplicationService } from '@core/application';
import { DomainCheckoutService } from '@domain/checkout';
import { map } from 'rxjs/operators';

@Injectable({ providedIn: 'root' })
export class CustomerCreateGuard implements CanActivateChild {
  readonly typeMappings = {
    guest: 'guest',
    online: 'webshop',
    b2b: 'b2b',
    branch: 'store',
  };

  constructor(private router: Router, private checkoutService: DomainCheckoutService, private application: ApplicationService) {}

  canActivateChild(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    const currentRoute = route.url[0].path;

    return this.checkoutService.getSetableCustomerTypes(this.application.activatedProcessId).pipe(
      map((selectables) => {
        if (selectables[currentRoute]) {
          return true;
        }

        // If Upgrade for p4mUser is necessary - select the correct route
        // cardFeature is either 'webshop' or 'store' for p4mUsers
        if (!!route?.queryParams?.card && !!route?.queryParams?.cardFeature) {
          this.router.navigate(
            [
              '/customer/create',
              selectables[route?.queryParams?.cardFeature] === true
                ? route?.queryParams?.cardFeature
                : route?.queryParams?.cardFeature === 'webshop'
                ? 'store'
                : 'webshop',
            ],
            { queryParams: route.queryParams }
          );
          return false;
        }

        for (const key in selectables) {
          if (Object.prototype.hasOwnProperty.call(selectables, key)) {
            if (selectables[key]) {
              this.router.navigate(['/kunde', this.application.activatedProcessId, 'customer', 'create', key], {
                queryParams: route.queryParams,
              });
              return false;
            }
          }
        }
        return false;
      })
    );
  }
}
