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

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

const queryGQL = `
  query WatchEmbedCode($id: Int!) {
    watchEmbedCode(id: $id){
      data
    }
  }
`;

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

          if (!errors.length) {
            actions.push(of(setEmbedCodeAction(data.watchEmbedCode.data)));
          }

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

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