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

import { getTaxonomyKeywordsAction, isLoadingKeywordsAction, keywordsAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';
import { getToken } from '@/modules/@common/token/helpers';

const queryGQL = `
  query taxonomyAutocomplete($category: String!, $prefix: String, $lang: String, $size: Int) {
    taxonomyAutocomplete(category: $category, prefix: $prefix, lang: $lang, size: $size){
      uid,
      category,
      values {
        lang
        value
        suggestions
      }
    }
  }
`;

export default (action$) =>
  action$.pipe(
    ofType(getTaxonomyKeywordsAction.type),
    debounceTime(+process.env.APP_CLEAR_TIMEOUT),
    filter(() => !!getToken()),
    switchMap((action) => {
      const {
        payload: { prefix, category },
      } = action;

      const stream$ = gqlRequest({
        query: queryGQL,
        variables: {
          category,
          prefix,
          lang: 'EN',
        },
      }).pipe(
        switchMap(({ data, errors }) => {
          const actions = [];

          if (!errors.length) {
            actions.push(of(keywordsAction(data.taxonomyAutocomplete)));
          }

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

      return concat(of(isLoadingKeywordsAction(true)), stream$, of(isLoadingKeywordsAction(false)));
    }),
  );
