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

import { getViewabilityConfigAction, setViewabilityConfigAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';

const queryGQL = `
  query videoGetPublishViewabilityConfig {
    videoGetPublishViewabilityConfig {
      mediaPlatform
      viewabilities {
        name
        onlyForExisting
      }
      transitions {
        name
        transitions
      }
    }
  }
`;

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

          if (!errors.length) {
            actions.push(of(setViewabilityConfigAction(data.videoGetPublishViewabilityConfig)));
          }

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

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