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

import { TYPE_SUCCESS } from '@/modules/@common/notify/constants';

import { ITEM_INPUT_TYPE_NAME } from '@/graphql/services/hubs/types/input/itemCreate';

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

const query = `
mutation UpdateHub($entity: ${ITEM_INPUT_TYPE_NAME}) {
  updateHub(entity: $entity) {
    id
    name
  }
}
`;

export default (action$, state$) =>
  action$.pipe(
    ofType(updateItemAction.type),
    switchMap(() => {
      const stream$ = gqlRequest({
        query,
        variables: {
          entity: createRequestBody(state$.value, true),
        },
      }).pipe(
        switchMap((response) => {
          if (!response.errors.length) {
            Router.push('/hubs');

            return concat(
              of(
                showNotificationAction({
                  type: TYPE_SUCCESS,
                  message: 'Hub updated',
                }),
              ),
            );
          }

          return EMPTY;
        }),
      );

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