import axios from 'axios';
import CookieStorage from '../CookieStorage';
import { dispatchServerApiError } from './dispatchApiError';
import { isServerError, markApiErrorHandled } from './apiHandledError';
const DEFAULT_HEADERS = {
    'Cache-Control': 'no-cache, no-store, must-revalidate',
    Pragma: 'no-cache',
    'Content-Type': 'application/json',
    Accept: 'application/json',
};
function toHandledServerErrorResponse(error) {
    return {
        data: null,
        status: error.response?.status ?? 500,
        statusText: error.response?.statusText ?? 'Internal Server Error',
        headers: error.response?.headers ?? {},
        config: error.config,
    };
}
export function createApiClient(options) {
    const { baseURL, attachJwt = true, serverErrorHandling = 'toast', augmentRequest, } = options;
    const api = axios.create({
        headers: DEFAULT_HEADERS,
        baseURL,
    });
    api.interceptors.response.use((response) => response, async (error) => {
        const status = error.response?.status;
        if (isServerError(status) && serverErrorHandling === 'toast') {
            dispatchServerApiError({ err: error });
            markApiErrorHandled(error);
            return toHandledServerErrorResponse(error);
        }
        if (error.status === null) {
            console.log(JSON.stringify(error));
        }
        return Promise.reject(error);
    });
    api.interceptors.request.use((config) => {
        if (!config?.headers) {
            throw new Error('no header available');
        }
        if (attachJwt) {
            const token = CookieStorage.getJwtToken();
            if (token) {
                config.headers.Authorization = `Bearer ${token}`;
            }
        }
        return augmentRequest ? augmentRequest(config) : config;
    });
    return api;
}
