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 { selectedTranslateFileSelector, translationFilesSelector } from '../selectors';
import { getTranslationFilesAction, removeTranslationFileAction, 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 AiWorkbenchTranslationRemoveFileQuery(
      $videoId: String!
      $file: String
      $lang: String
      $langName: String
      $sizeInBytes: Int
      $source: String
      $version: String
      $state: String
      $operationId: String
  ) {
    aiWorkbenchTranslationRemoveFile(
      videoId: $videoId
      file: $file
      lang: $lang
      langName: $langName
      sizeInBytes: $sizeInBytes
      source: $source
      version: $version
      state: $state
      operationId: $operationId
    ) {
      complete
    }
  }
`;

export default (action$, state$) =>
  action$.pipe(
    ofType(removeTranslationFileAction.type),
    switchMap(() => {
      const video = selectedVideoSelector(state$.value);
      const translationFiles = translationFilesSelector(state$.value);
      const selectedTranslationFile = selectedTranslateFileSelector(state$.value);
      const translationFileObjectToRemove = translationFiles.find((file) => file.lang === selectedTranslationFile);

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

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

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

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