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

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

const queryGQL = `
  query autocompleteLabel(
    $accountId: Int,
    $prefix: String,
    $excludeOrigin: String
  ) {
    autocompleteLabel(
      accountId: $accountId,
      prefix: $prefix,
      excludeOrigin: $excludeOrigin
    ) {
      uid
      name
      color
    }
  }
`;

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

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

          if (!errors.length) {
            const customCategoriesOptions = data.autocompleteLabel
              .filter((category) => category.name && category.color && category.uid)
              .map((category) => ({
                id: category.uid,
                label: category.name || '',
                value: category.name || '',
                color: category.color,
              }))
              .sort((category, nextCategory) => category.label.localeCompare(nextCategory.label));

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

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

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