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

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

import { registerUserAction } from '../slices';
import { setSessionStorageItem } from '@/modules/@common/storage/helpers';
import { setFormLoadingAction } from '@/modules/auth/common/redux/slices';
import { getPasswordLessAuthAction } from '@/modules/auth/Login/redux/slices';
import { showNotificationAction } from '@/modules/layout/redux/slices';

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

      const stream$ = ajax({
        method: 'POST',
        url: `${process.env.APP_PCN_API_BASE_URL_FE}/public/invitations/signIn`,
        headers: {
          Accept: 'application/json',
          'Content-Type': 'application/json',
        },
        crossDomain: true,
        withCredentials: true,
        body: JSON.stringify({
          email,
          token,
          firstName,
          lastName,
        }),
      }).pipe(
        switchMap(({ response }) => {
          setSessionStorageItem(REDIRECT_URL_STORAGE_NAME, response);

          const actions = [of(getPasswordLessAuthAction({ email })), of(setFormLoadingAction(false))];

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

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