import { ofType } from 'redux-observable';
import { concat, EMPTY, Observable, of } from 'rxjs';
import { ajax } from 'rxjs/ajax';
import { catchError, switchMap } from 'rxjs/operators';
import type { Action } from '@reduxjs/toolkit';

import { TYPE_ERROR } from '@/modules/@common/notify/constants';
import { USERS_PAGE } from '@/modules/@common/router/constants';
import { TOKEN_COOKIE_NAME, TOKEN_COOKIE_VALUE } from '@/modules/@common/token/constants';
import { AUTH_URL } from '@/modules/auth/common/constants/auth';

import { cancelImpersonationAction, logOutEventAction } from '../slices';
import { clearStorage } from '@/modules/@common/storage/helpers';
import { getToken, setTokenCookieName, setTokenCookieValue } from '@/modules/@common/token/helpers';
import { showNotificationAction } from '@/modules/layout/redux/slices';

type ResponseType = {
  cookieName: string;
  cookieValue: string;
};

export default (action$: Observable<Action>) =>
  action$.pipe(
    ofType(cancelImpersonationAction.type),
    switchMap(() => {
      const adminToken = getToken();

      const stream$: Observable<Action> = ajax<ResponseType>({
        method: 'POST',
        url: `${process.env.APP_PCN_API_BASE_URL_FE}/private/users/cancelImpersonation`,
        headers: {
          Accept: 'application/json',
          'Content-Type': 'application/json',
          authorization: getToken(),
        },
        crossDomain: true,
        withCredentials: true,
        body: JSON.stringify({
          adminToken,
        }),
      }).pipe(
        switchMap(({ response }) => {
          clearStorage();

          if (response?.cookieName) {
            setTokenCookieName(response.cookieName);
            setTokenCookieValue(response.cookieValue);
          }

          return ajax({
            method: 'POST',
            url: `${AUTH_URL}`,
            crossDomain: true,
            withCredentials: true,
            body: {
              [TOKEN_COOKIE_NAME]: response?.cookieName,
              [TOKEN_COOKIE_VALUE]: response?.cookieValue,
            },
          }).pipe(
            switchMap(() => {
              window.location.replace(`${window.location.origin}${USERS_PAGE.path}`);

              return EMPTY;
            }),
          );
        }),
        catchError(({ response }) =>
          concat(
            of(
              showNotificationAction({
                type: TYPE_ERROR,
                message: response?.message ?? 'Connection error',
              }),
            ),
            of(logOutEventAction()),
          ),
        ),
      );

      return concat(stream$);
    }),
  );
