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

import { TAG_SYSTEM_CATEGORY_TEXT } from '../../constants';

import { getSystemTagsOptionsAction, setStateAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';

const queryGQLTaxonomyAutocomplete = `
  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 queryGQLAutocompleteKeyword = `
  query autocompleteKeyword(
    $category: String!,
    $prefix: String,
    $size: Int,
    $sort: String,
    $videoId: String,
    $contentOwner: [Float]
  ) {
    autocompleteKeyword(
      category: $category,
      prefix: $prefix,
      size: $size,
      sort: $sort,
      videoId: $videoId,
      contentOwner: $contentOwner
    ) {
      value
    }
  }
`;

export default (action$) =>
  action$.pipe(
    ofType(getSystemTagsOptionsAction.type),
    switchMap((action) => {
      const { searchText, category } = action.payload;
      const queryGQL =
        category === TAG_SYSTEM_CATEGORY_TEXT ? queryGQLAutocompleteKeyword : queryGQLTaxonomyAutocomplete;

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

          if (!errors.length) {
            let tagsOptions = [];

            if (data.taxonomyAutocomplete) {
              tagsOptions = data.taxonomyAutocomplete.map((tag) => ({
                id: tag.uid,
                label: tag.values[0].value,
                value: tag.values[0].value,
              }));
            } else if (data.autocompleteKeyword) {
              tagsOptions = data.autocompleteKeyword.map((tag) => ({
                id: tag.value,
                label: tag.value,
                value: tag.value,
              }));
            }

            actions.push(
              of(
                setStateAction({
                  tagsOptions,
                }),
              ),
            );
          }

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

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