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

import { bulkUpdateViewabilityThresholdAction, getDataAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';

const query = `
  mutation BulkUpdateViewabilityThreshold(
    $viewabilityThreshold: Float,
    $ids: [String]
  ) {
    bulkUpdateViewabilityThreshold(
      viewabilityThreshold: $viewabilityThreshold,
      ids: $ids
    ) {
      data {
        id
      }
    }
  }
`;

export default (action$) =>
  action$.pipe(
    ofType(bulkUpdateViewabilityThresholdAction.type),
    switchMap(({ payload: { ids, viewabilityThreshold } }) => {
      const stream$ = gqlRequest({
        query,
        variables: {
          viewabilityThreshold,
          ids,
        },
      }).pipe(
        switchMap(({ errors }) => {
          let actions = [];

          if (!errors.length) {
            actions = [of(getDataAction())];
          }

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

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