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

import { JOB_TYPE_CC_TRANSLATION_PROCESSING } from '../../constants';

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 AiWorkbenchTranslationGenerateByAiQuery(
    $videoId: String!,
    $targetLanguages: [String],
  ) {
    aiWorkbenchTranslationGenerateByAi(
      videoId: $videoId,
      targetLanguages: $targetLanguages,
    ) {
      complete
    }
  }
`;

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

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

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

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

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