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

import { STATE_DOWNLOAD, STATE_PUBLISH } from '../../constants';
import { TYPE_SUCCESS } from '@/modules/@common/notify/constants';

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

const queryGQL = `
  mutation AiWorkbenchSetStateSlidesQuery(
    $videoId: String!,
    $publish: Boolean,
    $download: Boolean,
  ) {
    aiWorkbenchSetStateSlides(
      videoId: $videoId,
      publish: $publish,
      download: $download,
    ) {
      published
      draft
      processing
      download
    }
  }
`;

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

      const variables = {
        videoId: video.uid,
      };

      if (whoChange === STATE_PUBLISH) {
        variables.publish = state.publish;
      }

      if (whoChange === STATE_DOWNLOAD) {
        variables.download = state.download;
      }

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

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

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

            if (whoChange === STATE_PUBLISH) {
              actions.push(
                of(
                  showNotificationAction({
                    type: TYPE_SUCCESS,
                    message: action.payload.state.publish
                      ? 'Slides successfully published!'
                      : 'Slides successfully unpublished!',
                  }),
                ),
                of(runPdfMonitoringAction()),
              );

              if (state.publish) {
                actions.push(
                  of(
                    setAction({
                      published: state.publish,
                      draft: false,
                    }),
                  ),
                );
              }
            }
          }

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

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