import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, Router, RouterStateSnapshot } from '@angular/router';
import { FleioObjectsList } from '../../fleio-objects-list';
import { IInvoiceModel } from '../model/invoice.model';
import { Observable } from 'rxjs';
import { InvoicesApiService } from './invoices-api.service';
import { IListQueryParams } from '../../base-model/list-query-params';
import { map } from 'rxjs/operators';
import { ConfigService } from '@shared/config/config.service';
import { NotificationService } from '@shared/ui-api/notification.service';

@Injectable({
  providedIn: 'root'
})
export class InvoiceListPayResolver  {
  constructor(
    private invoicesApi: InvoicesApiService,
    private router: Router,
    private config: ConfigService,
    private notificationService: NotificationService,
  ) {
  }

  resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot):
    Observable<FleioObjectsList<IInvoiceModel>> | Promise<FleioObjectsList<IInvoiceModel>> |
    FleioObjectsList<IInvoiceModel> {
    const activeClient = this.config.authService.activeClient();
    const queryParams = {
      filtering: 'status:unpaid',
      detailed_list: true,
      page_size: 1000,
    } as IListQueryParams;
    if (activeClient && activeClient.currency) {
      queryParams.filtering = queryParams.filtering += `+currency:${activeClient.currency}`;
    }
    return this.invoicesApi.list(queryParams).pipe(map((data) => {
      if (data.count < 2) {
        this.notificationService.showMessage($localize`No multiple unpaid invoices.`);
        this.router.navigateByUrl(this.config.getPanelUrl('billing/invoices'));
      }
      return data;
    }));
  }
}
