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

import { REVOKE_INVITATION } from '@/graphql/services/invitations/constants';
import { TYPE_SUCCESS } from '@/modules/@common/notify/constants';

import { PAYLOAD_NAME } from '@/graphql/services/invitations/types/payload/item';

import { revokeAction, revokeActionSuccess } from '../slices';
import { notifyAction } from '@/modules/@common/notify/redux/slices';
import { gqlRequest } from '@/modules/@common/request';

const query = `
  mutation ${PAYLOAD_NAME}($payload: ${PAYLOAD_NAME}) {
    ${REVOKE_INVITATION}(payload: $payload) {
      id
    }
  }
`;

export default (action$) =>
  action$.pipe(
    ofType(revokeAction.type),
    switchMap((action) => {
      const stream$ = gqlRequest({
        query,
        variables: {
          payload: {
            id: action.payload,
          },
        },
      }).pipe(
        switchMap((response) => {
          if (!response.errors.length) {
            return of(
              notifyAction({
                type: TYPE_SUCCESS,
                message: 'Invitation revoked successfully',
              }),
              revokeActionSuccess(action.payload),
            );
          }

          return EMPTY;
        }),
      );

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