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

import { getLabelsForWaterfallAction, setModalInfoAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';

const query = `
  query MPLabelsAutocompleteQuery(
    $prefix: String,
    $size: Int
  ) {
    mpLabelsAutocomplete(
      prefix: $prefix,
      size: $size
    ) {
      value
      count
    }
  }
`;

export default (action$) =>
  action$.pipe(
    ofType(getLabelsForWaterfallAction.type),
    debounce((action) => timer(action.payload?.prefix?.length ? 1000 : 0)),
    switchMap(({ payload }) => {
      const stream$ = gqlRequest({
        query,
        variables: {
          prefix: payload?.prefix ?? '',
          size: 30,
        },
      }).pipe(
        switchMap(({ data, errors }) => {
          let actions = [];

          if (!errors.length) {
            actions = [
              of(
                setModalInfoAction({
                  labelsOptions: data.mpLabelsAutocomplete.filter((item) => !!item.value?.length),
                }),
              ),
            ];
          }

          return concat(...actions);
        }),
      );

      return concat(stream$);
    }),
  );
