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

import { DEMAND_TAG_PAGE, SUPPLY_TAG_PAGE } from '../../constants';
import { TYPE_SUCCESS } from '@/modules/@common/notify/constants';

import * as selectors from '../selectors';
import { bulkCreateWaterfallAction, getDataAction, setModalInfoAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';
import { showNotificationAction } from '@/modules/layout/redux/slices';

const query = `
  mutation BulkCreateWaterfall(
    $waterfall: [MarketplaceWaterfallInputType]!
  ) {
    bulkCreateWaterfall(
      waterfall: $waterfall
    ) {
      data {
        id
        created
        updated
        supplyId
        demandId
        tier
        priority
      }
    }
  }
`;

export default (action$, state$) =>
  action$.pipe(
    ofType(bulkCreateWaterfallAction.type),
    filter((action) => action.payload?.selected?.length),
    switchMap(({ payload: { selected } }) => {
      const state = state$.value;

      const pageConfig = selectors.pageConfigSelector(state);

      let waterfall = [];

      if (pageConfig.type === SUPPLY_TAG_PAGE) {
        waterfall = selected.map((id) => ({ supplyId: pageConfig.id, demandId: id }));
      }

      if (pageConfig.type === DEMAND_TAG_PAGE) {
        waterfall = selected.map((id) => ({ supplyId: id, demandId: pageConfig.id }));
      }

      const stream$ = gqlRequest({
        query,
        variables: {
          waterfall,
        },
      }).pipe(
        switchMap(({ errors }) => {
          let actions = [];

          if (!errors.length) {
            actions = [
              of(
                showNotificationAction({
                  type: TYPE_SUCCESS,
                  message: 'Tags were added',
                }),
              ),
              of(getDataAction()),
            ];
          }

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

      return concat(
        of(setModalInfoAction({ isFetchingData: true })),
        stream$,
        of(setModalInfoAction({ isFetchingData: false })),
      );
    }),
  );
