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

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

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

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

export default (action$) =>
  action$.pipe(
    ofType(getLiveEventDefaultImagesAction.type),
    switchMap((action) => {
      const { eventType } = action.payload;
      const fieldId = eventType === PRE_EVENT ? 'preEventId' : 'postEventId';
      const fieldImages = eventType === PRE_EVENT ? 'preEventImages' : 'postEventImages';

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

          if (!errors.length) {
            const { uid, files } = data.getLiveEventDefaultImages;

            actions.push(
              of(
                updateLiveEventFormAction({
                  [fieldId]: uid,
                  [fieldImages]: files,
                }),
              ),
            );
          }

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

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