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

import {
  initErrorAction,
  initErrorEventAction,
  initRequestEventAction,
  initResponseAction,
  initResponseEventAction,
} from '../slices';
import { gqlRequest } from '@/modules/@common/request';

import { init as initQuery } from '../../queries';

export default (action$) =>
  action$.pipe(
    ofType(initRequestEventAction.type),
    switchMap(() => {
      const stream$ = gqlRequest({ query: initQuery }).pipe(
        switchMap(({ data, errors }) => {
          const actions = [];

          if (!errors.length) {
            actions.push(of(initResponseAction(data)), of(initResponseEventAction()));
          } else {
            actions.push(of(initErrorAction(errors[0])), of(initErrorEventAction()));
          }

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

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