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

import { videoSelector } from '../selectors';
import { videoStatusAction, videoStatusUpdateProgressAction, videoUpdatedAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';

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

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

      const stream$ = gqlRequest({
        query: queryVideoUpdateGQL,
        variables: {
          id: uid,
          video: {
            status: approved ? 'ACTIVE' : 'DISABLED',
          },
        },
      }).pipe(
        switchMap(({ data, errors }) => {
          const actions = [];

          if (!errors.length) {
            actions.push(of(videoUpdatedAction(data.videoUpdate.video)));
          }

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

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