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_UI_LINK_WAS_EXPIRED } from '@/modules/@common/constants/errors';
import { TYPE_ERROR } from '@/modules/@common/notify/constants';
import { USER_AUTH_ERROR_PAGE } from '@/modules/@common/router/constants';

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

export default (action$) =>
  action$.pipe(
    ofType(verifyCodeAction.type),
    switchMap(({ payload }) => {
      const stream$ = ajax({
        method: 'POST',
        url: `${process.env.APP_PCN_API_BASE_URL_FE}/public/auth/get-reset-password-preload-data`,
        headers: {
          Accept: 'application/json',
          'Content-Type': 'application/json',
        },
        crossDomain: true,
        withCredentials: true,
        body: JSON.stringify({
          token: payload.token,
        }),
      }).pipe(
        switchMap(({ response }) =>
          concat(
            of(
              setFieldAction({
                email: response.email,
                code: response.resetCode,
              }),
            ),
            of(setFormLoadingAction(false)),
          ),
        ),
        catchError(({ response }) =>
          concat(
            of({ type: '@#' }).pipe(
              tap(() =>
                Router.push({
                  pathname: USER_AUTH_ERROR_PAGE.path,
                  query: {
                    error: ERROR_UI_LINK_WAS_EXPIRED,
                  },
                }),
              ),
            ),
            of(setFormLoadingAction(false)),
            of(
              showNotificationAction({
                type: TYPE_ERROR,
                message: response?.message ?? 'Connection error',
              }),
            ),
          ),
        ),
      );

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