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

import { BULK_USER_ACTIONS } from '@/graphql/services/users/constants';
import { TYPE_SUCCESS } from '@/modules/@common/notify/constants';

import { PAYLOAD_NAME } from '@/graphql/services/users/types/payload/bulkActions';

import * as selectors from '../selectors';
import { bulkUpdateAction, getDataAction, setTableAction } from '../slices';
import { notifyAction } from '@/modules/@common/notify/redux/slices';
import { gqlRequest } from '@/modules/@common/request';

const query = `
  mutation ${BULK_USER_ACTIONS} ($payload: ${PAYLOAD_NAME}) {
    ${BULK_USER_ACTIONS}(payload: $payload){
      ids
    }
  }
`;

export default (action$, state$) =>
  action$.pipe(
    ofType(bulkUpdateAction.type),
    filter(() => {
      const selected = selectors.selectedSelector(state$.value);

      return selected.length > 0;
    }),
    switchMap((action) => {
      const selected = selectors.selectedSelector(state$.value);

      const stream$ = gqlRequest({
        query,
        variables: {
          payload: {
            ids: selected,
            field: action.payload.field,
            value: action.payload.value,
          },
        },
      }).pipe(
        switchMap((response) => {
          if (!response.errors.length) {
            return concat(
              of(
                notifyAction({
                  type: TYPE_SUCCESS,
                  message: 'Action completed successfully',
                }),
              ),
              of(
                setTableAction({
                  selected: [],
                }),
              ),
              of(getDataAction()),
            );
          }

          return EMPTY;
        }),
      );

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