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

import { PASS_CRYPTO_SALT } from '@/modules/@common/envs/constants';
import { TYPE_ERROR } from '@/modules/@common/notify/constants';
import { LOGIN_PAGE } from '@/modules/@common/router/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 { getUserDataEventAction, setCodeStepAction, setIsSsoAuthProcessAction } from '../slices';
import { clearStorage, 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 { emailSelector, passwordSelector } from '@/modules/auth/Login/redux/selectors';
import { showNotificationAction } from '@/modules/layout/redux/slices';

export default (action$, state$) =>
  action$.pipe(
    ofType(getUserDataEventAction.type),
    switchMap((action) => {
      const sso = action.payload;
      const email = emailSelector(state$.value);
      const password = passwordSelector(state$.value);

      const { encryptString } = new StringCrypto();

      const passwordHash = encryptString(password, PASS_CRYPTO_SALT);

      const body = {};

      if (sso?.ssoCode) {
        body.ssoConfirmationCode = sso.ssoCode;
      } else {
        body.email = email;
        body.password = passwordHash;
      }

      const stream$ = ajax({
        method: 'POST',
        url: `${process.env.APP_PCN_API_BASE_URL_FE}/public/auth/login`,
        headers: {
          Accept: 'application/json',
          'Content-Type': 'application/json',
        },
        crossDomain: true,
        withCredentials: true,
        body: JSON.stringify(body),
      }).pipe(
        switchMap(({ response }) => {
          const actions = [];

          if (response.is2FaVerification) {
            actions.push(of(setFormLoadingAction(false)), of(setCodeStepAction(true)));
          } else {
            clearStorage();

            setUser(response?.token);

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

            const redirectUrl =
              sso?.redirectUrl || getSessionStorageItem(REDIRECT_URL_STORAGE_NAME) || window.location.origin;

            const authStream = 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;
              }),
            );

            actions.push(authStream);
          }

          return concat(...actions);
        }),
        catchError(({ response }) => {
          Router.replace(LOGIN_PAGE.path);

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

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