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

import { bulkUpdateAvailableKeysAction, searchAvailableKeysAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';

const query = `
  mutation bulkUpdateAvailableKeys(
    $ids: [String],
    $status: String
  ) {
    bulkUpdateAvailableKeys(
      ids: $ids,
      status: $status
    )
  }
`;

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

          if (!errors.length) {
            actions.push(of(searchAvailableKeysAction()));
          }
          return concat(...actions);
        }),
      );

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