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 { REDIRECT_URL_STORAGE_NAME } from '@/modules/@common/storage/constants';
import { TOKEN_COOKIE_NAME, TOKEN_COOKIE_VALUE } from '@/modules/@common/token/constants';
import { AUTH_URL } from '@/modules/auth/common/constants/auth';

import { verifyCodeEventAction } from '../slices';
import { getSessionStorageItem } from '@/modules/@common/storage/helpers';
import { setTokenCookieName, setTokenCookieValue } from '@/modules/@common/token/helpers';
import { setUser } from '@/modules/@common/user/helpers';
import { setFormLoadingAction } from '@/modules/auth/common/redux/slices';
import { codeSelector, emailSelector } from '@/modules/auth/Login/redux/selectors';
import { showNotificationAction } from '@/modules/layout/redux/slices';

export default (action$, state$) =>
  action$.pipe(
    ofType(verifyCodeEventAction.type),
    switchMap(() => {
      const email = emailSelector(state$.value);
      const code = codeSelector(state$.value);

      const stream$ = ajax({
        method: 'POST',
        url: `${process.env.APP_PCN_API_BASE_URL_FE}/public/auth/verify2facode`,
        headers: {
          Accept: 'application/json',
          'Content-Type': 'application/json',
        },
        crossDomain: true,
        withCredentials: true,
        body: JSON.stringify({
          email,
          twoFaCode: code,
        }),
      }).pipe(
        switchMap(({ response }) => {
          const redirectUrl = getSessionStorageItem(REDIRECT_URL_STORAGE_NAME) || window.location.origin;

          setUser(response?.token);

          if (response?.cookieName) {
            setTokenCookieName(response.cookieName);
            setTokenCookieValue(response.cookieValue);
          }

          return ajax({
            method: 'POST',
            url: AUTH_URL,
            crossDomain: true,
            withCredentials: true,
            body: {
              token: response.token,
              [TOKEN_COOKIE_NAME]: response?.cookieName,
              [TOKEN_COOKIE_VALUE]: response?.cookieValue,
            },
          }).pipe(
            switchMap(() => {
              window.location.replace(redirectUrl);

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

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