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

import { createLiveEventEndpointAction, setIsLoadingAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';

const queryGQL = `
  query createLiveEventEndpoint($id: String!) {
    createLiveEventEndpoint(id: $id) {
     data
    }
  }
`;

export default (action$) =>
  action$.pipe(
    ofType(createLiveEventEndpointAction.type),
    switchMap((action) => {
      const stream$ = gqlRequest({
        query: queryGQL,
        variables: {
          id: action.payload,
        },
      }).pipe(
        concatMap(({ errors }) => {
          const actions = [];

          if (!errors.length) {
            actions.push(of(setIsLoadingAction(false)));
          }

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

      return concat(of(setIsLoadingAction(true)), stream$);
    }),
  );
