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

import { TYPE_SUCCESS } from '@/modules/@common/notify/constants';

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

const queryGQL = `
  query AiWorkbenchGetSlidesQuery(
    $videoId: String!,
  ) {
    aiWorkbenchGetSlides(
      videoId: $videoId,
    ) {
      published
      draft
      download
      slides {
        id
        time
        img
        title
      }
      pdfFile
      isGeneratingAvailable
      causes
    }
  }
`;

export default (action$, state$) =>
  action$.pipe(
    ofType(getSlidesAction.type),
    switchMap((action) => {
      const video = selectedVideoSelector(state$.value);
      const { shouldShowGenerationsCompletedNotification = false, isPdfMonitoringUpdate = false } =
        action.payload || {};

      const stream$ = gqlRequest({
        query: queryGQL,
        variables: {
          videoId: video.uid,
        },
      }).pipe(
        switchMap(({ data, errors }) => {
          const actions = [];
          const response = data.aiWorkbenchGetSlides;
          const slides = response?.slides ?? [];
          const payload = { pdfFile: response.pdfFile || '' };

          if (!errors?.length) {
            if (!isPdfMonitoringUpdate) {
              payload.slides = slides;
              payload.published = response.published;
              payload.download = response.download;
              payload.draft = response.draft;
              payload.isLoading = false;
              payload.isGeneratingAvailable = response.isGeneratingAvailable;
              payload.causes = response.causes;
            }

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

            if (shouldShowGenerationsCompletedNotification) {
              const message = slides.length
                ? `Slides generation completed. ${slides.length} slides were identified`
                : 'Slides generation completed. No slides were identified';

              actions.push(of(showNotificationAction({ type: TYPE_SUCCESS, message })));
            }
          }

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

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