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

import {
  appendUploadedFileAction,
  replaceAppendUploadedFileAction,
  replaceUploadProcessingAction,
  uploadProcessingAction,
} from '../slices';
import { uploadS3 } from '@/modules/@common/request';

export default (action$) =>
  action$.pipe(
    ofType(uploadProcessingAction.type, replaceUploadProcessingAction.type),
    switchMap((action) => {
      const { uploadUrl, downloadUrl, file } = action.payload;

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

          if (!errors.length) {
            if (action.type === uploadProcessingAction.type) {
              actions.push(
                of(
                  appendUploadedFileAction({
                    name: file.name,
                    file: downloadUrl,
                  }),
                ),
              );
            }

            if (action.type === replaceUploadProcessingAction.type) {
              actions.push(
                of(
                  replaceAppendUploadedFileAction({
                    name: file.name,
                    file: downloadUrl,
                    ccFileForReplace: action.payload.ccFileForReplace,
                  }),
                ),
              );
            }
          }

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

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