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

import { EDITORIAL_PAGE } from '@/modules/@common/router/constants';

import { hasUnfinishedJobs } from '../../helpers/monitoring';
import { endAction, repeatAction, runAction } from '../slices';

export default (action$) =>
  action$.pipe(
    ofType(repeatAction.type),
    delay(+process.env.APP_REQUEST_TIMEOUT),
    filter(() => window.location.pathname === EDITORIAL_PAGE),
    mergeMap(({ payload }) => {
      const { videoId, jobs } = payload.repeat;

      return concat(of(hasUnfinishedJobs(jobs) ? runAction(videoId) : endAction(videoId)));
    }),
  );
