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

import { getCurrentUploadStateFromQueue } from '../../selectors';
import { uploadCcFilesAction, uploadThumbnailAction } from '../../slices';
import { uploadS3 } from '@/modules/@common/request';

export default (action$, state$) =>
  action$.pipe(
    ofType(uploadThumbnailAction.type),
    switchMap(() => {
      const {
        thumbnail,
        uploadVideo: { thumbnailUploadUrl },
      } = getCurrentUploadStateFromQueue(state$.value);

      const stream$ = uploadS3(thumbnailUploadUrl, thumbnail).pipe(
        switchMap(({ errors }) => {
          const actions = [];

          if (!errors.length) {
            actions.push(of(uploadCcFilesAction()));
          }

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

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