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

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

const query = `
  mutation DeleteWaterfall(
    $supplyIds: [String]!,
    $demandIds: [String]!
  ) {
    deleteWaterfall(
      supplyIds: $supplyIds,
      demandIds: $demandIds
    ) {
      data {
        id
      }
    }
  }
`;

export default (action$) =>
  action$.pipe(
    ofType(deleteWaterfallAction.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$);
    }),
  );
