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

import { getSelectedVideoAction, setAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';
import { monitoringStartAction } from '@/modules/editorial/editorialSearch/redux/slices';

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

export default (action$) =>
  action$.pipe(
    ofType(getSelectedVideoAction.type),
    switchMap((action) => {
      const stream$ = gqlRequest({
        query: queryGQL,
        variables: {
          uid: action.payload,
        },
      }).pipe(
        switchMap(({ data, errors }) => {
          const actions = [];

          if (!errors?.length) {
            actions.push(
              of(
                setAction({
                  selectedVideo: data.video,
                }),
              ),
              of(monitoringStartAction()),
            );
          }

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

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