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

import { setIsLoadingAction, setLiveStreamDataAction, testLiveEventEndPointAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';
import { streamIdSelector } from '@/modules/liveEvents/liveEvent/redux/selectors';

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

export default (action$, state$) =>
  action$.pipe(
    ofType(testLiveEventEndPointAction.type),
    switchMap(() => {
      const streamId = streamIdSelector(state$.value);
      const stream$ = gqlRequest({
        query: queryGQL,
        variables: {
          id: streamId,
        },
      }).pipe(
        concatMap(({ errors }) => {
          const actions = [of(setIsLoadingAction(false))];

          if (!errors.length) {
            actions.push(
              of(
                setLiveStreamDataAction({
                  repeatRequest: true,
                }),
              ),
            );
          }

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

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