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

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

const queryGQL = `
  query autocompleteLabelGrouped(
    $accountId: Int,
    $prefix: String!,
    $excludeOrigin: String
  ) {
    autocompleteLabelGrouped(
      accountId: $accountId,
      prefix: $prefix,
      excludeOrigin: $excludeOrigin
    ) {
      labelGrouped {
        name
        values {
          value
        }
        color
        contentOwnerId
        labelId
        accountId
      }
    }
  }
`;

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

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

          if (!errors.length) {
            const tagsOptions = data.autocompleteLabelGrouped.labelGrouped
              .reduce((acc, curr) => {
                const labels = curr.values
                  ? curr.values.map((label) => ({
                      label: label.value,
                      value: label.value,
                      categoryName: curr.name,
                      categoryLabelId: curr.labelId,
                      categoryColor: curr.color,
                    }))
                  : [];

                return [...acc, ...labels];
              }, [])
              .sort((tag, nextTag) => tag.label.localeCompare(nextTag.label));

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

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

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