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

import { FILE_VERSION_MANUAL, JOB_TYPE_SPEECH_RECOGNITION } from '../../constants';
import { TYPE_ERROR } from '@/modules/@common/notify/constants';

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

const queryGQL = `
  mutation AiWorkbenchTranscriptGenerateByAiQuery(
    $videoId: String!,
    $feedId: Int!,
  ) {
    aiWorkbenchTranscriptGenerateByAi(
      videoId: $videoId,
      feedId: $feedId,
    ) {
      complete
    }
  }
`;

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

      const shouldShowErrorIfLangIsManual = translations.some(
        (file) => file.lang === video.lang[0] && file.version === FILE_VERSION_MANUAL,
      );

      if (shouldShowErrorIfLangIsManual) {
        return concat(
          of(
            showNotificationAction({
              type: TYPE_ERROR,
              message: 'Manual transcript should be removed before the transcript generation',
            }),
          ),
        );
      }

      const stream$ = gqlRequest({
        query: queryGQL,
        variables: {
          videoId: video.uid,
          feedId: video.feedSourceId,
        },
      }).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_SPEECH_RECOGNITION })));
          }

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

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