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

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

const queryGQL = `
  mutation AiWorkbenchSetSlidesQuery(
    $videoId: String!,
    $slides: [AiWorkbenchSlideInputType],
  ) {
    aiWorkbenchSetSlides(
      videoId: $videoId,
      slides: $slides,
    ) {
      published
      draft
      processing
      download
      slides {
        id
        time
        title
        img
      }
    }
  }
`;

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

      const stream$ = gqlRequest({
        query: queryGQL,
        variables: {
          videoId: video.uid,
          slides: action.payload.sort((a, b) => a.time - b.time),
        },
      }).pipe(
        switchMap(({ data, errors }) => {
          const response = data.aiWorkbenchSetSlides;
          const payload = { isLoading: false };

          if (!errors?.length) {
            payload.slides = response?.slides ?? [];
            payload.published = response.published;
            payload.draft = response.draft;
            payload.processing = response.processing;
            payload.formId = null;
            payload.isDirty = true;
          }

          return concat(of(setAction(payload)));
        }),
      );

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