import { Injectable } from '@angular/core';
import { SearchStateSearchResult, SearchStateSearchService } from '@store/search-component-store';
import { CustomerInfoDTO, CustomerService, ListResponseArgsOfCustomerInfoDTO } from '@swagger/crm';
import { UiFilter } from '@ui/filter';
import { UiErrorModalComponent, UiModalService } from '@ui/modal';
import { of } from 'rxjs';
import { catchError, map } from 'rxjs/operators';

@Injectable()
export class CustomerSearchStateSearchService implements SearchStateSearchService<CustomerInfoDTO> {
  constructor(private _customerService: CustomerService, private _modal: UiModalService) {}

  search(filter: UiFilter, options: { skip: number }) {
    return this._customerService
      .CustomerListCustomers({
        ...filter.getQueryToken(),
        skip: options.skip,
        take: 25,
      })
      .pipe(
        map((res) => this.mapResponseToSearchStateSearchResult(res)),
        catchError((error) => {
          this._modal.open({
            content: UiErrorModalComponent,
            title: 'Fehler beim Laden der Kunden Suchergebnisse',
            data: error,
          });
          return of({});
        })
      );
  }

  mapResponseToSearchStateSearchResult(response: ListResponseArgsOfCustomerInfoDTO): SearchStateSearchResult {
    return {
      items: response.result ?? [],
      message: response.message,
      hits: response.hits ?? 0,
      error: response.error ?? false,
    };
  }
}
