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

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

const queryGQL = `
  query getPublisherInfoById($id: Int!) {
    getPublisherInfoById(id: $id) {
      id
      name,
      slug,
    }
  }
`;

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

          if (!errors.length) {
            actions.push(
              of(
                updateLiveEventFormAction({
                  publisherInfo: data.getPublisherInfoById,
                }),
              ),
            );
          }

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

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