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

import * as selectors from '../selectors';
import { getBrandsOptionsAction, getKeywordsOptionsAction, getPeopleOptionsAction, setFieldAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';
import { getUserContentOwnerIdsSelector } from '@/modules/@common/user/redux/selectors';

const categoryEnum = {
  [getKeywordsOptionsAction.type]: 'KEYWORDS',
  [getBrandsOptionsAction.type]: 'BRANDS',
  [getPeopleOptionsAction.type]: 'PEOPLE',
};

const query = `
  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
      }
    }
  }
`;

const getResponse = ({ data: { taxonomyAutocomplete } }) =>
  taxonomyAutocomplete.map((taxonomy) => ({
    value: taxonomy.uid,
    label: taxonomy.values?.length ? taxonomy.values[0].value : '',
  }));

export default (action$, state$) =>
  action$.pipe(
    ofType(getKeywordsOptionsAction.type, getBrandsOptionsAction.type, getPeopleOptionsAction.type),
    debounce((action) => timer(action.payload?.length ? 1000 : 0)),
    switchMap((action) => {
      const autocomplete = selectors.autocompleteSelector(state$.value);

      const stream$ = gqlRequest({
        query,
        variables: {
          contentOwner: getUserContentOwnerIdsSelector(state$.value),
          category: categoryEnum[action.type],
          prefix: action.payload ?? '',
          lang: 'EN',
        },
      }).pipe(
        switchMap((response) => {
          const actions = [];

          if (!response.errors.length) {
            actions.push(
              of(
                setFieldAction({
                  autocomplete: {
                    ...autocomplete,
                    textOptions: getResponse(response),
                  },
                }),
              ),
            );
          }

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

      return concat(
        of(
          setFieldAction({
            autocomplete: {
              ...autocomplete,
              textOptions: null,
            },
          }),
        ),
        stream$,
      );
    }),
  );
