import { markApiErrorHandled } from './apiHandledError';
import CookieStorage from '../CookieStorage';
import { messageAction, loggedAction } from '../sessionTypes';
import { getCommonDispatch } from '../commonDispatch';
import { getErrorMessageValue } from '../useMessageUtils';
import i18n from 'i18next';
function isStorybook() {
    return (typeof window !== 'undefined' &&
        (window.location.port === '6006' ||
            Boolean(window.__STORYBOOK__)));
}
function defaultRedirectUrls() {
    const publicUrl = import.meta.env.VITE_APP_PUBLIC_URL;
    return {
        on401: import.meta.env.VITE_APP_AUTH_URL,
        on403: import.meta.env.VITE_APP_UNAUTHORIZED_URL ??
            (publicUrl ? `${publicUrl}/unauthorized` : undefined),
    };
}
function clearAuthStorage() {
    CookieStorage.removeJwtToken();
    sessionStorage.clear();
    localStorage.clear();
}
function handleToastAuthError(status) {
    if (status === 401) {
        clearAuthStorage();
        getCommonDispatch()?.(loggedAction(undefined));
    }
    const value = getErrorMessageValue({
        err: { response: { status } },
        t: i18n.t.bind(i18n),
    });
    getCommonDispatch()?.(messageAction({ value, type: 'error' }));
}
function handleRedirectAuthError(status, redirect, onBeforeRedirect, skipAuthHandlingInStorybook = true) {
    if (skipAuthHandlingInStorybook && isStorybook())
        return;
    onBeforeRedirect?.(status);
    if (status === 401) {
        clearAuthStorage();
        if (redirect.on401)
            window.location.replace(redirect.on401);
        return;
    }
    if (redirect.on403)
        window.location.href = redirect.on403;
}
export function applyAuthErrorHandling(api, options) {
    const { authErrorHandling = 'none', authStatuses = [401, 403], redirect: redirectOverrides, onBeforeRedirect, skipAuthHandlingInStorybook = true, } = options;
    if (authErrorHandling === 'none')
        return api;
    const redirect = { ...defaultRedirectUrls(), ...redirectOverrides };
    api.interceptors.response.use((response) => response, async (error) => {
        const status = error.response?.status;
        if (status === 401 || status === 403) {
            if (!authStatuses.includes(status))
                return Promise.reject(error);
            if (authErrorHandling === 'toast') {
                handleToastAuthError(status);
            }
            else if (authErrorHandling === 'redirect') {
                handleRedirectAuthError(status, redirect, onBeforeRedirect, skipAuthHandlingInStorybook);
            }
            markApiErrorHandled(error);
        }
        return Promise.reject(error);
    });
    return api;
}
