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

import { bulkUpdateKeyListsAction, searchKeyListsAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';

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

export default (action$) =>
  action$.pipe(
    ofType(bulkUpdateKeyListsAction.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(searchKeyListsAction()));
          }
          return concat(...actions);
        }),
      );

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