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

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

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

const queryGQL = `
  query getLiveEventImage($id: String!) {
    getLiveEventImage(id: $id) {
      uid,
      name,
      files {
        file
        width
        height
      }
    }
  }
`;

export default (action$) =>
  action$.pipe(
    ofType(getLiveEventImageAction.type),
    concatMap((action) => {
      const { id, type } = action.payload;

      const fieldId = type === PRE_EVENT ? 'preEventId' : 'postEventId';
      const fieldImages = type === PRE_EVENT ? 'preEventImages' : 'postEventImages';

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

          if (!errors.length) {
            actions.push(
              of(
                updateLiveEventFormAction({
                  [fieldId]: data.getLiveEventImage?.uid,
                  [fieldImages]: data.getLiveEventImage?.files,
                }),
              ),
            );
          }

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

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