import axios, {type AxiosInstance, type InternalAxiosRequestConfig, type AxiosResponse, type AxiosError} from "axios";
import LocalStorageUtil from "@/utils/local";
import {LOGIN_EXPIRED_CODE} from "@/constants";

const axiosInstance: AxiosInstance = axios.create({
    baseURL: process.env.REACT_APP_API_URL,
    timeout: 30000
});

const requestInterceptor = (config: InternalAxiosRequestConfig): InternalAxiosRequestConfig => {
    config.headers.token = LocalStorageUtil.getItem("__TOKEN__");
    return config;
};

const responseInterceptor = (response: AxiosResponse): AxiosResponse => {
    if (response.data.code === LOGIN_EXPIRED_CODE) {
        // Toast.show({
        //     content: `登录失效: ${response.data.code} ${LocalStorageUtil.getItem("__TOKEN__")}`,
        // });
        setTimeout(() => {
            LocalStorageUtil.clear();
            // window.location.replace("/");
        }, 2000);
    }
    return response;
};

const onError = (error: AxiosError) => Promise.reject(error);

axiosInstance.interceptors.request.use(requestInterceptor, onError);
axiosInstance.interceptors.response.use(responseInterceptor, onError);

export default axiosInstance;
