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

import { getPublishersAction, setPublishersAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';
import { getToken } from '@/modules/@common/token/helpers';

import allPublishersGQL from '@/modules/@common/gql/queries/allPublishers';

export default (action$) =>
  action$.pipe(
    ofType(getPublishersAction.type),
    debounceTime(500),
    filter(() => !!getToken()),
    switchMap(() => {
      const stream$ = gqlRequest({
        query: allPublishersGQL,
        variables: {
          watchEnabledOnly: false,
          removeDisabled: true,
          removeLimit: true,
        },
      }).pipe(
        switchMap(({ data, errors }) => {
          const actions = [];

          if (!errors.length) {
            actions.push(of(setPublishersAction(data.allPublishers)));
          }

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

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