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

import { selectedVideoSelector } from '../../../AiWorkbench/redux/selectors';
import { descriptionSelector } from '../selectors';
import { updateDescriptionInVideoListOrDetailAction } from '../slices';
import { videosSelector } from '@/modules/editorial/editorialSearchResults/redux/selectors';
import { videosAction } from '@/modules/editorial/editorialSearchResults/redux/slices';
import { selectedVideoSelector as detailSelectedVideoSelector } from '@/modules/editorial/editorialVideoDetails/redux/selectors';
import { reloadSelectedVideoAction } from '@/modules/editorial/editorialVideoDetails/redux/slices';

export default (action$, state$) =>
  action$.pipe(
    ofType(updateDescriptionInVideoListOrDetailAction.type),
    switchMap(({ payload }) => {
      const { uid } = selectedVideoSelector(state$.value);
      const description = descriptionSelector(state$.value);
      const videos = videosSelector(state$.value);
      const isVideoDetailOpened = detailSelectedVideoSelector(state$.value);

      const updatedVideos = videos.map((originalVideo) =>
        originalVideo.uid === uid ? { ...originalVideo, plot: payload ? description : '' } : originalVideo,
      );

      const actions = [];
      actions.push(of(videosAction(updatedVideos)));
      if (isVideoDetailOpened) {
        actions.push(of(reloadSelectedVideoAction()));
      }

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