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

import { gqlRequest } from '@/modules/@common/request';
import { videosSelector } from '@/modules/editorial/editorialSearchResults/redux/selectors';
import {
  selectedVideoAction,
  startSearchEventAction,
  videosAction,
} from '@/modules/editorial/editorialSearchResults/redux/slices';
import { selectedVideoSelector } from '@/modules/editorial/editorialVideoDetails/redux/selectors';
import { clearAction, deleteVideoAction } from '@/modules/editorial/editorialVideoDetails/redux/slices';

const queryGQL = `
  mutation videoDeleteMutation($id: String!) {
    videoDelete(id: $id) {
      result
    }
  }
`;

export default (action$, state$) =>
  action$.pipe(
    ofType(deleteVideoAction.type),
    switchMap(() => {
      const { uid } = selectedVideoSelector(state$.value);
      const videos = videosSelector(state$.value);

      const stream$ = gqlRequest({
        query: queryGQL,
        variables: {
          id: uid,
        },
      }).pipe(
        switchMap(({ data, errors }) => {
          const actions = [];

          if (!errors.length) {
            const { videoDelete } = data;

            if (videoDelete.result) {
              const updatedVideoList = videos.filter((originalVideo) => originalVideo.uid !== uid);

              actions.push(
                of(
                  selectedVideoAction({
                    uid: null,
                  }),
                ),
                of(clearAction()),
                of(videosAction(updatedVideoList)),
                of(startSearchEventAction({ onlyCounters: true })),
              );
            }
          }

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

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