import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, Router, RouterStateSnapshot } from '@angular/router';
import { Observable, of } from 'rxjs';
import { IListQueryParams } from '@fleio-api/base-model/list-query-params';
import { catchError, map } from 'rxjs/operators';
import { ICartItemsModel } from '@fleio-api/billing/cart/model/cart-item.model';
import { CartApiService } from '@fleio-api/billing/cart/cart-api.service';
import { FleioObjectsList } from '@fleio-api/fleio-objects-list';
import { ConfigService } from '@shared/config/config.service';

@Injectable({
  providedIn: 'root'
})
export class OrderServicesRedirectResolver  {
  constructor(
    private cartApiService: CartApiService,
    private router: Router,
    private config: ConfigService,
  ) {
  }

  resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot):
    Observable<FleioObjectsList<ICartItemsModel>> | Promise<FleioObjectsList<ICartItemsModel>> |
    FleioObjectsList<ICartItemsModel> {
    return this.cartApiService.list(
      route.queryParams as IListQueryParams
    ).pipe(map((result: any) => {
      if (result?.client) {
        this.router.navigateByUrl(this.config.getPanelUrl(`orders/select-product?filtering=cycles__currency__code:${result.currency}`));
      }
      return result;
    }), catchError(() => of(null)));
  }
}
