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

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

const queryGQL = `
  mutation AiWorkbenchGenerateSlidesByAiQuery(
    $videoId: String!,
    $notifyByEmail: Boolean!
  ) {
    aiWorkbenchGenerateSlidesByAi(
      videoId: $videoId,
      notifyByEmail: $notifyByEmail,
    )
  }
`;

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

      const stream$ = gqlRequest({
        query: queryGQL,
        variables: {
          videoId: video.uid,
          notifyByEmail: action.payload,
        },
      }).pipe(
        switchMap(({ errors }) => {
          const actions = [of(setAction({ isLoading: false }))];

          if (!errors?.length) {
            actions.push(of(monitoringStartAction()));
            actions.push(of(setAction({ processing: true })));
          }

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

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