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

import {
  ERROR_CANT_USE_PASSWORDLESS_AUTH,
  ERROR_OTP_ALREADY_USED,
  ERROR_OTP_HAS_EXPIRED,
  ERROR_TOO_MANY_ATTEMPTS,
  ERROR_TWO_FA_IS_REQUIRED,
  ERROR_USER_NOT_VALID,
} from '@/modules/@common/constants/errors';
import { TYPE_ERROR } from '@/modules/@common/notify/constants';
import { USER_AUTH_ERROR_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 { verifyPasswordLessAuthAction } 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 { showNotificationAction } from '@/modules/layout/redux/slices';

export default (action$) =>
  action$.pipe(
    ofType(verifyPasswordLessAuthAction.type),
    switchMap(({ payload }) => {
      const { email, code } = payload;

      const stream$ = ajax({
        method: 'POST',
        url: `${process.env.APP_PCN_API_BASE_URL_FE}/public/auth/verify-passwordless-auth-code`,
        headers: {
          Accept: 'application/json',
          'Content-Type': 'application/json',
        },
        crossDomain: true,
        withCredentials: true,
        body: JSON.stringify({
          email,
          code,
        }),
      }).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 }) => {
          const actions = [];

          if (
            [
              ERROR_USER_NOT_VALID,
              ERROR_OTP_HAS_EXPIRED,
              ERROR_OTP_ALREADY_USED,
              ERROR_TOO_MANY_ATTEMPTS,
              ERROR_TWO_FA_IS_REQUIRED,
              ERROR_CANT_USE_PASSWORDLESS_AUTH,
            ].includes(response.errorCode)
          ) {
            actions.push(
              of({ type: '@#' }).pipe(
                tap(() =>
                  Router.push({
                    pathname: USER_AUTH_ERROR_PAGE.path,
                    query: {
                      error: response.errorCode,
                    },
                  }),
                ),
              ),
            );
          } else {
            actions.push(
              of(
                showNotificationAction({
                  type: TYPE_ERROR,
                  message: response?.message ?? 'Connection error',
                }),
              ),
            );
          }

          return concat(...actions, of(setFormLoadingAction(false)));
        }),
      );

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