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

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

const queryGQL = `
  query AiWorkbenchGetHighlightsGetCreatedVideosQuery($videoId: String!) {
    aiWorkbenchGetHighlightsGetCreatedVideos(videoId: $videoId) {
      totalCount
      data {
        uid
        name
        videoCreationDate
      }
    }
  }
`;

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

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

          if (!errors.length) {
            const { data: videos } = data.aiWorkbenchGetHighlightsGetCreatedVideos;
            payload.videos = videos;
          }

          actions.push(of(setAction(payload)));

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

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