import { ofType } from 'redux-observable';
import { concat, of, timer } from 'rxjs';
import { debounce, switchMap } from 'rxjs/operators';

import { getPlayerBoostListOptionsAction, setAction, setPlayerIsLoadingAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';

const query = `
  query getPlayerBoostList(
    $type: String
    $searchText: String
  ) {
    getPlayerBoostList(
      type: $type
      searchText: $searchText
    ) {
    records{
      value
      label
      uid
      }
    }
  }
`;

export default (action$) =>
  action$.pipe(
    ofType(getPlayerBoostListOptionsAction.type),
    debounce((action) => {
      const search = action.payload;
      return timer(search?.length > 1 ? 1000 : 0);
    }),
    switchMap((action) => {
      const actions = [];
      const stream$ = gqlRequest({
        query,
        variables: {
          searchText: action.payload.searchText ?? '',
          type: action.payload.type,
        },
      }).pipe(
        switchMap((response) => {
          if (!response.errors.length) {
            actions.push(
              of(
                setAction({
                  boostsListOptions: response.data.getPlayerBoostList?.records ?? [],
                }),
              ),
            );
          }
          return concat(...actions);
        }),
      );
      return concat(of(setPlayerIsLoadingAction(true)), stream$, of(setPlayerIsLoadingAction(false)));
    }),
  );
