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

import { TYPE_SUCCESS } from '@/modules/@common/notify/constants';

import { selectedVideoSelector } from '../../../AiWorkbench/redux/selectors';
import { addTranslationFileAction, getTranslationFilesAction, setAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';
import { reloadSelectedVideoAction } from '@/modules/editorial/editorialVideoDetails/redux/slices';
import { showNotificationAction } from '@/modules/layout/redux/slices';

const queryGQL = `
  mutation AiWorkbenchTranslationAddFileQuery(
      $videoId: String!
      $file: String!
      $lang: String!
  ) {
    aiWorkbenchTranslationAddFile(
      videoId: $videoId
      file: $file
      lang: $lang
    ) {
      file
      lang
      langName
      sizeInBytes
      source
      version
      state
      operationId
    }
  }
`;

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

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

          if (!errors?.length) {
            actions.push(
              of(
                setAction({
                  isLoading: false,
                }),
              ),
              of(getTranslationFilesAction()),
              of(
                showNotificationAction({
                  type: TYPE_SUCCESS,
                  message: 'Translation was uploaded successfully.',
                }),
              ),
              of(reloadSelectedVideoAction()),
            );
          }

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

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