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

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

const query = `
  mutation UpdateTiers(
    $supplyId: String,
    $demands: [MarketplaceDemandTierInputType]
  ) {
    updateTiers(
      supplyId: $supplyId,
      demands: $demands
    ) {
      data {
        id
        created
        updated
        supplyId
        demandId
        tier
        priority
      }
    }
  }
`;

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

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

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

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