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

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

import { followToHelpLinkAction, showNotificationAction } from '../slices';

export default (action$) =>
  action$.pipe(
    ofType(followToHelpLinkAction.type),
    switchMap(() => {
      const suffix = window.location.pathname;

      return ajax({
        method: 'GET',
        url: `${process.env.APP_PCN_API_BASE_URL_FE}/public/online-help?suffix=${suffix}`,
        crossDomain: true,
        withCredentials: true,
      }).pipe(
        switchMap(({ response: redirectUrl }) => {
          window.open(redirectUrl, '_blank');

          return EMPTY;
        }),
        catchError(({ response }) =>
          concat(
            of(
              showNotificationAction({
                type: TYPE_ERROR,
                message: response?.message ?? 'Connection error',
              }),
            ),
          ),
        ),
      );
    }),
  );
