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

import { UPDATE_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 { updateItemAction } from '../slices';
import { gqlRequest } from '@/modules/@common/request';
import { showNotificationAction } from '@/modules/layout/redux/slices';

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

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

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

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

          return EMPTY;
        }),
      );

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