import axios from "axios";
import {store} from "@/main.ts";
import {addNewMessage, color} from "@/services/popupDisplayer.ts";

const axiosInstance = axios.create({
    baseURL: import.meta.env.VITE_BACKEND_URL,
    headers: {
        'Content-Type': 'application/json',
    },
});

axiosInstance.interceptors.response.use(
    response => response, // Directly return successful responses.
    async error => {
        const originalRequest = error.config;
        if (error.response.status === 401 && !originalRequest._retry && store.authenticated) {
            originalRequest._retry = true; // Mark the request as retried to avoid infinite loops.
            try {
                await store.refreshUserToken();
                // Update the authorization header with the new access token.
                axiosInstance.defaults.headers.common['Authorization'] = `Bearer ${store.user.token}`;
                return axiosInstance(originalRequest); // Retry the original request with the new access token.
            } catch (refreshError) {
                // Handle refresh token errors by clearing stored tokens and redirecting to the login page.
                console.error('Token refresh failed:', refreshError);
                localStorage.removeItem('accessToken');
                localStorage.removeItem('refreshToken');
                window.location.href = '/login';
                return Promise.reject(refreshError);
            }
        }
        return Promise.reject(error); // For all other errors, return the error as is.
    }
);

// TODO: spawn a error modal
function defaultApiErrorHandler(err: string){
    addNewMessage(err, color.Red);
}

function defaultApiSuccessHandler(response: any){
    addNewMessage(response.data, color.green)
}
function callApi(endpoint: string, onSuccessHandler?: any, onErrorHandler?: any): void {
    axiosInstance.get(endpoint).then(
        onSuccessHandler == null ? defaultApiSuccessHandler : onSuccessHandler
    ).catch(
        (err) => {
            onErrorHandler == null ? defaultApiErrorHandler(err): onErrorHandler(err);
            throw err;
        }
    )
}


export {callApi}