import Router from 'next/router';
import { ofType } from 'redux-observable';
import { concat, 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 { PASSWORD_LESS_LOGIN_CODE_PAGE, USER_AUTH_ERROR_PAGE } from '@/modules/@common/router/constants';

import { getPasswordLessAuthAction } from '../slices';
import { setFormLoadingAction } from '@/modules/auth/common/redux/slices';
import { showNotificationAction } from '@/modules/layout/redux/slices';

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

      const stream$ = ajax({
        method: 'POST',
        url: `${process.env.APP_PCN_API_BASE_URL_FE}/public/auth/request-passwordless-auth-code`,
        headers: {
          Accept: 'application/json',
          'Content-Type': 'application/json',
        },
        crossDomain: true,
        withCredentials: true,
        body: JSON.stringify({
          email,
        }),
      }).pipe(
        switchMap(() =>
          concat(
            of({ type: '@#' }).pipe(
              tap(() =>
                Router.push({
                  pathname: PASSWORD_LESS_LOGIN_CODE_PAGE.path,
                  query: {
                    email,
                  },
                }),
              ),
            ),
            of(setFormLoadingAction(false)),
          ),
        ),
        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$);
    }),
  );
