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

import { TYPE_ERROR } from '@/modules/@common/notify/constants';

import { setIsLoadingAction, uploadLiveEventImageFlowAction, uploadLiveEventImageToS3Action } from '../slices';
import { gqlRequest } from '@/modules/@common/request';
import { showNotificationAction } from '@/modules/layout/redux/slices';
import { contentOwnerIdSelector } from '@/modules/liveEvents/liveEvent/redux/selectors';

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

export default (action$, state$) =>
  action$.pipe(
    ofType(uploadLiveEventImageFlowAction.type),
    switchMap((action) => {
      const contentOwnerId = contentOwnerIdSelector(state$.value);

      const { image, type } = action.payload;

      if (image && image.size > 5000000) {
        const message = {
          type: TYPE_ERROR,
          message: 'Maximum thumbnail file size is 5MB',
        };
        return concat(of(showNotificationAction(message)));
      }

      const requestParams = {
        contentOwnerId,
        filename: image?.name,
        fromLiveEvent: true,
      };

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

          if (!errors.length && data.S3UploadLink) {
            const s3uploadParams = { ...data.S3UploadLink };
            actions.push(
              of(
                uploadLiveEventImageToS3Action({
                  contentOwner: contentOwnerId,
                  image,
                  type,
                  ...s3uploadParams,
                }),
              ),
            );
          }

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

      return concat(of(setIsLoadingAction(true)), stream$);
    }),
  );
