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 { 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 { submitPasswordAction } from '../slices';
import { getSessionStorageItem } from '@/modules/@common/storage/helpers';
import { setTokenCookieName, setTokenCookieValue } from '@/modules/@common/token/helpers';
import { setFormLoadingAction } from '@/modules/auth/common/redux/slices';
import {
  codeSelector,
  emailSelector,
  password2Selector,
  passwordSelector,
} from '@/modules/auth/CreateResetPassword/redux/selectors';
import { showNotificationAction } from '@/modules/layout/redux/slices';

export default (action$, state$) =>
  action$.pipe(
    ofType(submitPasswordAction.type),
    switchMap(() => {
      const email = emailSelector(state$.value);
      const code = codeSelector(state$.value);
      const password = passwordSelector(state$.value);
      const password2 = password2Selector(state$.value);

      const { encryptString } = new StringCrypto();

      const passwordHash = encryptString(password, PASS_CRYPTO_SALT);
      const passwordHash2 = encryptString(password2, PASS_CRYPTO_SALT);

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

          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$);
    }),
  );
