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

import { lastUpdateAction } from '../slices';
import { initResponseSelector } from '@/modules/@common/gql/redux/selectors';
import { initResponseAction, initResponseEventAction } from '@/modules/@common/gql/redux/slices';
import { setVideoLangs } from '@/modules/@common/helpers/videoLangs';
import { setIAB } from '@/modules/@common/iab/helpers';

export default (action$, state$) =>
  action$.pipe(
    ofType(initResponseEventAction.type),
    switchMap(() => {
      const initResponse = initResponseSelector(state$.value);

      const {
        iab: { data: iab },
        videoLangs,
      } = initResponse;

      setIAB(iab);
      setVideoLangs(videoLangs);

      return concat(of(lastUpdateAction(new Date())), of(initResponseAction()));
    }),
  );
