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

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

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

export default (action$, state$) =>
  action$.pipe(
    ofType(getListOfCreatedVideoAction.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.aiWorkbenchGetChaptersGetCreatedVideos;
            payload.videos = videos;
          }

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

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

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