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

import { videoSelector } from '../selectors';
import { videoUpdatedAction, videoVerificationAction, videoVerificationUpdateProgressAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';
import { videosSelector } from '@/modules/editorial/editorialSearchResults/redux/selectors';
import { videosAction } from '@/modules/editorial/editorialSearchResults/redux/slices';

import queryVideoUpdateGQL from '@/modules/@common/gql/queries/videoUpdate';

export default (action$, state$) =>
  action$.pipe(
    ofType(videoVerificationAction.type),
    switchMap((action) => {
      const verified = action.payload;
      const state = state$.value;
      const { uid } = videoSelector(state);

      const stream$ = gqlRequest({
        query: queryVideoUpdateGQL,
        variables: {
          id: uid,
          video: {
            approval: {
              status: verified ? 'APPROVED' : 'NOT_APPROVED',
            },
          },
        },
      }).pipe(
        filter((data) => data.data.videoUpdate.video),
        switchMap(({ data, errors }) => {
          let actions = [];
          if (!errors.length) {
            const { videos } = videosSelector(state);

            const newVideos = videos.map((oneVideo$) =>
              oneVideo$.uid !== data.videoUpdate.video.uid ? oneVideo$ : { ...oneVideo$, ...data.videoUpdate.video },
            );

            actions = [of(videoUpdatedAction(data.videoUpdate.video)), of(videosAction(newVideos))];
          }

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

      return concat(
        of(videoVerificationUpdateProgressAction(true)),
        stream$,
        of(videoVerificationUpdateProgressAction(false)),
      );
    }),
  );
