import { Injectable } from '@angular/core';
import { ApplicationService } from '@core/application';
import { DomainCustomerOrderService } from '@domain/oms';
import { BranchDTO } from '@generated/swagger/checkout-api';
import { AutocompleteTokenDTO } from '@generated/swagger/oms-api';
import { UiFilterAutocomplete, UiFilterAutocompleteProvider, UiInput } from '@ui/filter';
import { cloneDeep } from 'lodash';
import { Observable, of } from 'rxjs';
import { catchError, map, switchMap } from 'rxjs/operators';

@Injectable()
export class CustomerOrderSearchMainAutocompleteProvider extends UiFilterAutocompleteProvider {
  for = 'goods-out';

  constructor(
    private omsService: DomainCustomerOrderService,
    private applicationService: ApplicationService,
  ) {
    super();
  }

  complete(input: UiInput): Observable<UiFilterAutocomplete[]> {
    if (input.value.length >= 3) {
      return this.applicationService.getSelectedBranch$().pipe(
        switchMap((branch) =>
          this.omsService
            .complete(this.createAutocompleteToken(input, branch))
            .pipe(catchError(() => of({ result: [] }))),
        ),
        map((res) => res.result),
      );
    } else {
      return of([]);
    }
  }

  createAutocompleteToken(input: UiInput, branch: BranchDTO | undefined): AutocompleteTokenDTO {
    const autocomnpleteToken: AutocompleteTokenDTO = {};

    const token = input?.parent?.parent?.getQueryToken();
    const filter = token?.filter ?? {};
    const type = Object.keys(token?.input).join(';');

    if (branch?.id) {
      autocomnpleteToken.filter = { ...filter, branch_id: String(branch.id) };
    } else {
      autocomnpleteToken.filter = filter;
    }

    autocomnpleteToken.input = input?.value ?? '';

    autocomnpleteToken.type = type;

    autocomnpleteToken.take = 5;

    return autocomnpleteToken;
  }
}
