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

import { CREATE_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 * as selectors from '../selectors';
import { createItemAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';
import { showNotificationAction } from '@/modules/layout/redux/slices';

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

export default (action$, state$) =>
  action$.pipe(
    ofType(createItemAction.type),
    switchMap(() => {
      const name = selectors.nameSelector(state$.value);
      const suffix = selectors.suffixSelector(state$.value);
      const helpPageUrl = selectors.helpPageUrlSelector(state$.value);

      const stream$ = gqlRequest({
        query,
        variables: {
          payload: {
            name,
            suffix,
            helpPageUrl,
          },
        },
      }).pipe(
        switchMap((response) => {
          if (!response.errors.length) {
            Router.push('/online-help');

            return of(
              showNotificationAction({
                type: TYPE_SUCCESS,
                message: 'Configuration created successfully',
              }),
            );
          }

          return EMPTY;
        }),
      );

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