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

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

const queryGQL = `
  query getLiveEventFeedContentOwner($publisherId: Int!) {
    getLiveEventFeedContentOwner(publisherId: $publisherId) {
      contentOwner {
        id
        name
      },
      feed {
        id
        name
      }
    }
  }
`;

export default (action$) =>
  action$.pipe(
    ofType(getLiveEventContentOwnerAction.type),
    switchMap((action) => {
      const { publisherId } = action.payload;
      const stream$ = gqlRequest({
        query: queryGQL,
        variables: {
          publisherId,
        },
      }).pipe(
        concatMap(({ data, errors }) => {
          const actions = [];

          if (!errors.length) {
            const { contentOwner, feed } = data.getLiveEventFeedContentOwner;

            actions.push(
              of(
                updateLiveEventFormAction({
                  contentOwnerId: contentOwner.id,
                  feedId: feed.id,
                }),
              ),
            );
          }

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

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