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

import { PRE_EVENT } from '../../constants';

import { getImageData } from '../../helpers/request';
import {
  createLiveEventImageAction,
  getLiveEventImageAction,
  setIsLoadingAction,
  updateLiveEventFormAction,
} from '../slices';
import { gqlRequest } from '@/modules/@common/request';

const queryGQL = `
  mutation createLiveEventImage(
    $name: String!,
    $contentOwner: Int!,
    $url: String!
  ) {
    createLiveEventImage(
      name: $name,
      contentOwner: $contentOwner,
      url: $url
    ) {
      uid,
      name,
      files {
        file
      }
    }
  }
`;

export default (action$) =>
  action$.pipe(
    ofType(createLiveEventImageAction.type),
    switchMap((action) => {
      const body = getImageData(action.payload);
      const { type } = action.payload;
      const id = type === PRE_EVENT ? 'preEventId' : 'postEventId';

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

          if (!errors.length) {
            const { uid } = data.createLiveEventImage;

            actions.push(
              of(
                updateLiveEventFormAction({
                  [id]: uid,
                  isLoading: false,
                }),
              ),
              of(
                getLiveEventImageAction({
                  type,
                  id: uid,
                }),
              ),
            );
          }

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

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