import { ofType } from 'redux-observable';
import { concat, EMPTY } from 'rxjs';
import { map, mergeMap } from 'rxjs/operators';

import { getLiveEventEmbedCodeAction, setLiveEventEmbedCodeAction } from '../../../liveEvent/redux/slices';
import { getEmbedCodeAction, setEmbedCodeAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';

const queryGQL = `
  query getEventEmbedCode($eventId: Int!) {
    getEventEmbedCode(eventId: $eventId) {
      embedCode
    }
  }
`;

export default (action$) =>
  action$.pipe(
    ofType(getEmbedCodeAction.type, getLiveEventEmbedCodeAction.type),
    mergeMap((action) => {
      const stream$ = gqlRequest({
        query: queryGQL,
        variables: {
          eventId: action.payload,
        },
      }).pipe(
        map(({ data, errors }) => {
          if (!errors.length) {
            const { embedCode } = data.getEventEmbedCode;

            return action.type === getLiveEventEmbedCodeAction.type
              ? setLiveEventEmbedCodeAction(embedCode)
              : setEmbedCodeAction(embedCode);
          }

          return EMPTY;
        }),
      );

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