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

import { TYPE_ERROR } from '@/modules/@common/notify/constants';

import { endAction } from '@/modules/@common/monitoring/redux/slices';
import { gqlRequest } from '@/modules/@common/request';
import { selectedVideoSelector, videosSelector } from '@/modules/editorial/editorialSearchResults/redux/selectors';
import { selectedVideoAction, videosAction } from '@/modules/editorial/editorialSearchResults/redux/slices';
import { showNotificationAction } from '@/modules/layout/redux/slices';

import videoById from '@/modules/@common/gql/queries/videoById';

export default (action$, state$) =>
  action$.pipe(
    ofType(endAction.type),
    switchMap((monitoringData) => {
      const state = state$.value;

      const videoId = monitoringData.payload;

      const stream$ = gqlRequest({
        query: videoById,
        variables: {
          uid: videoId,
        },
      }).pipe(
        switchMap(({ data, errors }) => {
          const actions = [];
          const videos = videosSelector(state);
          const selectedVideo = selectedVideoSelector(state);

          if (!errors.length) {
            const isVideoActive = data.video.status === 'ACTIVE';

            if (data.video.status !== 'PROCESSING') {
              actions.push(
                of(
                  showNotificationAction({
                    type: isVideoActive ? 'success' : 'error',
                    message: isVideoActive ? 'Video processing completed successfully' : 'Video processing failed',
                  }),
                ),
              );
            }

            const allowToShow = ['ACTIVE', 'PROCESSING', 'FAILED'].some((status) => data.video.status === status);

            if (allowToShow) {
              let updatedVideo = null;

              const updatedVideos = videos.map((video) => {
                if (video.uid === data.video.uid) {
                  updatedVideo = { ...video, ...data.video };

                  return { ...video, ...data.video };
                }

                return video;
              });

              if (updatedVideo) {
                if (updatedVideo.uid === selectedVideo?.uid) {
                  actions.push(of(selectedVideoAction(updatedVideo)));
                }

                actions.push(of(videosAction(updatedVideos)));
              }
            } else {
              const updatedVideos = videos.filter((video) => video.uid !== data.video.uid);

              actions.push(of(videosAction(updatedVideos)), of(selectedVideoAction()));
            }
          } else {
            actions.push(
              of(
                showNotificationAction({
                  type: TYPE_ERROR,
                  message: 'Video processing failed',
                }),
              ),
            );

            if (videoId === selectedVideo?.uid) {
              actions.push(of(selectedVideoAction()));
            }
          }

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

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