import { ofType } from 'redux-observable';
import { concat, EMPTY, of } from 'rxjs';
import { ajax } from 'rxjs/ajax';
import { switchMap } from 'rxjs/operators';

import { setFormLoadingAction } from '@/modules/auth/common/redux/slices';
import { getCustomLoginPageByAccountIdAction, setIsSsoAuthProcessAction } from '@/modules/auth/Login/redux/slices';

export default (action$) =>
  action$.pipe(
    ofType(getCustomLoginPageByAccountIdAction.type),
    switchMap((action) => {
      const { accountId, redirectUrl } = action.payload;

      const stream$ = ajax({
        method: 'GET',
        url: `${process.env.APP_PCN_API_BASE_URL_FE}/public/props/getCustomLoginPage/${accountId}`,
        crossDomain: true,
        withCredentials: true,
      }).pipe(
        switchMap(({ response }) => {
          if (response?.customLoginPageUrl) {
            window.location.replace(`${response.customLoginPageUrl}?olp=${encodeURIComponent(redirectUrl)}`);
            return EMPTY;
          }

          return concat(of(setFormLoadingAction(false)), of(setIsSsoAuthProcessAction(false)));
        }),
      );

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