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

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

const query = `
  mutation BulkUpdateDemandTag(
    $tags: [MarketplaceDemandTagInputType]
  ) {
    bulkUpdateDemandTag(
      tags: $tags
    ) {
      data {
        id
        name
        status
      }
    }
  }
`;

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

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

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

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