import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, Router, RouterStateSnapshot } from '@angular/router';
import { Observable } from 'rxjs';
import { EnduserBillingSummaryModel } from '@fleio-api/billing/model/enduser-billing-summary.model';
import { AuthService } from '@shared/auth/auth.service';
import { ConfigService } from '@shared/config/config.service';

@Injectable({
  providedIn: 'root'
})
export class RequireClientDataResolver  {
  constructor(
    private authService: AuthService,
    private router: Router,
    private config: ConfigService
  ) {
  }

  resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot):
    Observable<EnduserBillingSummaryModel> | Promise<EnduserBillingSummaryModel> | EnduserBillingSummaryModel {
    if (this.authService && this.authService.feature('billing')) {
      if (this.authService.userData && this.authService.userData.user &&
        Array.isArray(this.authService.userData.user.clients) && this.authService.userData.user.clients.length) {
        // client already associated, nothing to do
        return null;
      } else {
        // has no clients while requiring one, redirect
        this.router.navigateByUrl(this.config.getPanelUrl('clients/create')).then(() => {});
        return null;
      }
    } else {
      return null;
    }
  }
}
