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 { LOGIN_PAGE } from '@/modules/@common/router/constants';

import { setFieldAction, verifyTokenAction } from '../slices';
import { setFormLoadingAction } from '@/modules/auth/common/redux/slices';
import { showNotificationAction } from '@/modules/layout/redux/slices';

export default (action$) =>
  action$.pipe(
    ofType(verifyTokenAction.type),
    switchMap(({ payload }) => {
      const { token } = payload;

      const stream$ = ajax({
        method: 'POST',
        url: `${process.env.APP_PCN_API_BASE_URL_FE}/public/invitations/getPreloadInvitationData`,
        headers: {
          Accept: 'application/json',
          'Content-Type': 'application/json',
        },
        crossDomain: true,
        withCredentials: true,
        body: JSON.stringify({
          token,
        }),
      }).pipe(
        switchMap(({ response }) => {
          if (response.url) {
            window.location.replace(response.url);
            return EMPTY;
          }

          if (!response.email) {
            window.location.replace(LOGIN_PAGE.path);
            return concat(
              of(
                showNotificationAction({
                  type: TYPE_ERROR,
                  message: 'Email doesn`t exist',
                }),
              ),
            );
          }

          return concat(
            of(
              setFieldAction({
                email: response.email,
                token,
              }),
            ),
            of(setFormLoadingAction(false)),
          );
        }),
        catchError(({ response }) => {
          window.location.replace(LOGIN_PAGE.path);
          return concat(
            of(
              showNotificationAction({
                type: TYPE_ERROR,
                message: response?.message ?? 'Connection error',
              }),
            ),
            of(setFormLoadingAction(false)),
          );
        }),
      );

      return concat(of(setFormLoadingAction(true)), stream$);
    }),
  );
