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

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

const queryGQL = `
  query autocompleteLabelValue(
    $accountId: Int,
    $prefix: String,
    $label: String,
    $excludeOrigin: String
  ) {
    autocompleteLabelValue(
      accountId: $accountId,
      prefix: $prefix,
      label: $label,
      excludeOrigin: $excludeOrigin
    ) {
      value
    }
  }
`;

export default (action$) =>
  action$.pipe(
    ofType(getCustomTagsOptionsAction.type),
    switchMap((action) => {
      const { searchText, category, accountId } = action.payload;

      const stream$ = gqlRequest({
        query: queryGQL,
        variables: {
          prefix: searchText,
          label: category,
          accountId,
          excludeOrigin: 'RSS',
        },
      }).pipe(
        switchMap(({ data, errors }) => {
          const actions = [];

          if (!errors.length) {
            const tagsOptions = data.autocompleteLabelValue
              .filter((tag) => tag.value)
              .map((tag) => ({
                label: tag.value,
                value: tag.value,
              }))
              .sort((tag, nextTag) => tag.label.localeCompare(nextTag.label));

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

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

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