import { useUserInfoStore } from "@/stores/useUserInfoStore";
import { useWalletStore } from "@/stores/useWalletStore";
import actions from "@/utils/client/actions";
import Request from "./axios";

const BASE_URL = process.env.NEXT_PUBLIC_BASE_URL;

const server = new Request({
    timeout: 10 * 1000,
    baseURL: BASE_URL,
    transform: {
        // instance  interceptor
        requestInterceptor: (config) => {
            return config;
        },
        requestInterceptorCatch: (err) => {
            return err;
        },
        responseInterceptor: (config) => {
            return config;
        },
        responseInterceptorCatch: async (err) => {
            const { response } = err;
            if (!response) return err;
            // @ts-ignore
            const { code } = response.data;
            switch (code) {
                case 401:
                    localStorage.removeItem("globalStore");
                    useWalletStore.getState().reset();
                    useUserInfoStore.getState().reset();
                    await actions();
                    break;
                default:
                    return err;
            }
        },
    },
});

export { server };
