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

import { setAction as chaptersSetAction } from '../../../Chapters/redux/slices';
import { setAction as descriptionSetAction } from '../../../Description/redux/slices';
import { setAction as highlightsSetAction } from '../../../Highlights/redux/slices';
import { setAction as slidesSetAction } from '../../../Slides/redux/slices';
import { setAction as thumbnailSetAction } from '../../../Thumbnail/redux/slices';
import { setAction as translationsSetAction } from '../../../Translations/redux/slices';
import { selectedVideoSelector } from '../selectors';
import { getModulesAttributeAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';

const queryGQL = `
  query AiWorkbenchGetModulesAttribute(
    $videoId: String!,
  ) {
    aiWorkbenchGetModulesAttribute(
      videoId: $videoId,
    ) {
      chapters {
        published
        processing
        draft
        updatedAt
        updatedBy
      }
      highlights {
        published
        processing
        draft
        updatedAt
        updatedBy
      }
      slides {
        published
        processing
        draft
        download
        updatedAt
        updatedBy
      }
      translations {
        published
        processing
      }
       description {
        published
        processing
        draft
        updatedAt
        updatedBy
      }
      thumbnail {
        published
        processing
        draft
        updatedAt
        updatedBy
      }
    }
  }
`;

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

      const stream$ = gqlRequest({
        query: queryGQL,
        variables: {
          videoId: video.uid,
        },
      }).pipe(
        switchMap(({ data, errors }) => {
          const actions = [];
          const { chapters, highlights, slides, translations, description, thumbnail } =
            data.aiWorkbenchGetModulesAttribute;

          if (!errors?.length) {
            actions.push(
              of(chaptersSetAction(chapters)),
              of(highlightsSetAction(highlights)),
              of(slidesSetAction(slides)),
              of(translationsSetAction(translations)),
              of(descriptionSetAction(description)),
              of(thumbnailSetAction(thumbnail)),
            );
          }

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

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