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

import { RUN_CONTEXT } from '@/modules/@common/ccFiles/constants';

import { runContextSelector } from '../selectors';
import {
  replaceUploadProcessingAction,
  replaceUploadStartAction,
  uploadProcessingAction,
  uploadStartAction,
} from '../slices';
import { gqlRequest } from '@/modules/@common/request';
import { selectedVideoSelector } from '@/modules/editorial/editorialVideoDetails/redux/selectors';
import { ownerSelector } from '@/modules/uploaderNew/redux/selectors';

const queryGQL = `
  query Query($name: String, $filename: String!, $thumbnail: String, $contentOwnerId: Float!) {
    S3UploadLink(name: $name, filename: $filename, thumbnail: $thumbnail, contentOwnerId: $contentOwnerId) {
      uploadUrl
      downloadUrl
    }
  }
`;

export default (action$, state$) =>
  action$.pipe(
    ofType(uploadStartAction.type, replaceUploadStartAction.type),
    switchMap((action) => {
      const runContext = runContextSelector(state$.value);

      const { file } = action.payload;
      const filename = file.name;
      let contentOwnerId = null;

      if (runContext === RUN_CONTEXT.IN_TAB) {
        const selectedVideo = selectedVideoSelector(state$.value);
        contentOwnerId = selectedVideo.contentOwner;
      }

      if (runContext === RUN_CONTEXT.IN_VIDEO_UPLOAD) {
        const owner = ownerSelector(state$.value);
        contentOwnerId = owner?.value;
      }

      const requestParams = {
        contentOwnerId,
        filename,
      };

      const stream$ = gqlRequest({ query: queryGQL, variables: requestParams }).pipe(
        switchMap(({ data, errors }) => {
          const actions = [];

          if (!errors.length && data.S3UploadLink) {
            const params = { ...data.S3UploadLink, file };
            const processingAction =
              action.type === uploadStartAction.type ? uploadProcessingAction : replaceUploadProcessingAction;

            if (action.type === replaceUploadStartAction.type) {
              params.ccFileForReplace = action.payload.ccFileForReplace;
            }

            actions.push(of(processingAction(params)));
          }

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

      return concat(stream$);
    }),
  );
