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

import { DELETE_CONFIGURATION } from '@/graphql/services/onlineHelp/constants';
import { TYPE_SUCCESS } from '@/modules/@common/notify/constants';

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

import { deleteItemAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';
import { showNotificationAction } from '@/modules/layout/redux/slices';

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

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

          return EMPTY;
        }),
      );

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