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

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

const queryGQL = `
  query getLiveEventPublishers {
    getLiveEventPublishers{
      id
      name
    }
  }
`;

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

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

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

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