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

import { createLiveEventImageAction, uploadLiveEventImageToS3Action } from '../slices';
import { uploadS3 } from '@/modules/@common/request';

export default (action$) =>
  action$.pipe(
    ofType(uploadLiveEventImageToS3Action.type),
    switchMap((action) => {
      const { uploadUrl, downloadUrl, image, type, contentOwner } = action.payload;

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

          if (!errors.length) {
            actions.push(
              of(
                createLiveEventImageAction({
                  url: downloadUrl,
                  name: image.name,
                  contentOwner,
                  type,
                }),
              ),
            );
          }

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

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