import { HttpErrorResponse } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { DomainGoodsService } from '@domain/oms';
import { ComponentStore, tapResponse } from '@ngrx/component-store';
import { ListResponseArgsOfOrderItemListItemDTO, OrderItemListItemDTO } from '@swagger/oms';
import { isResponseArgs } from '@utils/object';
import { Subject } from 'rxjs';
import { switchMap, tap, withLatestFrom } from 'rxjs/operators';

export interface GoodsInCleanupListState {
  message?: string;
  fetching: boolean;
  hits: number;
  results: OrderItemListItemDTO[];
  selectedOrderItemSubsetIds: number[];
}

@Injectable()
export class GoodsInCleanupListStore extends ComponentStore<GoodsInCleanupListState> {
  get results() {
    return this.get((s) => s.results);
  }
  readonly results$ = this.select((s) => s.results);

  get hits() {
    return this.get((s) => s.hits);
  }
  readonly hits$ = this.select((s) => s.hits);

  get fetching() {
    return this.get((s) => s.fetching);
  }
  readonly fetching$ = this.select((s) => s.fetching);

  get selectedOrderItemSubsetIds() {
    return this.get((s) => s.selectedOrderItemSubsetIds);
  }
  selectedOrderItemSubsetIds$ = this.select((s) => s.selectedOrderItemSubsetIds);

  private _searchResultSubject = new Subject<ListResponseArgsOfOrderItemListItemDTO>();

  readonly searchResult$ = this._searchResultSubject.asObservable();

  constructor(private _domainGoodsInService: DomainGoodsService) {
    super({
      fetching: false,
      hits: 0,
      results: [],
      selectedOrderItemSubsetIds: [],
    });
  }

  searchRequest() {
    return this._domainGoodsInService.goodsInCleanupList();
  }

  search = this.effect(($) =>
    $.pipe(
      tap((_) => this.patchState({ fetching: true })),
      withLatestFrom(this.results$),
      switchMap(([_, _results]) =>
        this.searchRequest().pipe(
          tapResponse(
            (res) => {
              this.patchState({
                hits: res.hits,
                results: res.result ?? [],
                fetching: false,
              });

              this._searchResultSubject.next(res);
            },
            (err: Error) => {
              if (err instanceof HttpErrorResponse && isResponseArgs(err.error)) {
                this._searchResultSubject.next(err.error);
              } else {
                this._searchResultSubject.next({
                  error: true,
                  message: err.message,
                });
              }
              this.patchState({ fetching: false });
              console.error('GoodsInCleanupListStore.search()', err);
            }
          )
        )
      )
    )
  );
}
