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

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

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

const queryGQL = `
  mutation AiWorkbenchSetSubtitleQuery($payload: AiWorkbenchSetSubtitleInputType) {
    aiWorkbenchSetSubtitle(payload: $payload)
  }
`;

export default (action$, state$) =>
  action$.pipe(
    ofType(setSubtitleAction.type),
    switchMap(() => {
      const video = selectedVideoSelector(state$.value);
      const lang = selectedTranslateFileSelector(state$.value);
      const editData = editDataSelector(state$.value);

      const payload = {
        videoId: video.uid,
        lang,
        lemmas: Object.entries(editData).map(([uid, lemma]) => ({
          uid,
          startTime: lemma.startTime,
          endTime: lemma.endTime,
          tokens: Object.values(lemma.tokens),
        })),
      };

      const stream$ = gqlRequest({
        query: queryGQL,
        variables: {
          payload,
        },
      }).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_PUBLISH_TRANSCRIPT })));
          }

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

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