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

import { SET_AIW_THUMBNAIL_FROM_VIDEO_FRAME } from '@/graphql/services/aiWorkbench/constants/thumbnail';

import { SET_AIW_THUMBNAIL_FROM_VIDEO_FRAME_PAYLOAD } from '@/graphql/services/aiWorkbench/types/thumbnail/payload/setThumbnailFromVideoFrame';

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

const queryGQL = `
  mutation ${SET_AIW_THUMBNAIL_FROM_VIDEO_FRAME}($payload: ${SET_AIW_THUMBNAIL_FROM_VIDEO_FRAME_PAYLOAD}) {
    ${SET_AIW_THUMBNAIL_FROM_VIDEO_FRAME}(payload: $payload) {
      published
      draft
      processing
    }
  }
`;

export default (action$, state$) =>
  action$.pipe(
    ofType(setThumbnailFromVideoFrameAction.type),
    switchMap((action) => {
      const video = selectedVideoSelector(state$.value);

      const stream$ = gqlRequest({
        query: queryGQL,
        variables: {
          payload: {
            videoId: video.uid,
            timestamp: action.payload,
          },
        },
      }).pipe(
        switchMap(({ data, errors }) => {
          const response = data[SET_AIW_THUMBNAIL_FROM_VIDEO_FRAME];
          const payload = { isLoading: false };
          const actions = [];

          if (!errors?.length) {
            payload.published = response.published;
            payload.draft = response.draft;
            payload.processing = response.processing;
            payload.isDirty = true;

            actions.push(of(setAction(payload)), of(monitoringStartAction()));
          }

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

      return concat(of(setAction({ isLoading: true })), stream$);
    }),
  );
