import axios, { type AxiosRequestConfig } from "axios";
import { useUserStore } from "@/stores/UserStore";
import { ElMessage } from "element-plus";

const instance = axios.create({
  baseURL: import.meta.env.VITE_SERVER,
});

instance.interceptors.request.use((config) => {
  const store = useUserStore();
  if (!store.token) {
    return config;
  }

  // 确保 token 被正确添加到请求头
  config.headers.token = store.token;
  return config;
});

// 响应拦截器
instance.interceptors.response.use(
  (response) => {
    return response;
  },
  (error) => {
    // 处理错误响应
    if (error.response?.status === 401) {
      // token过期或无效
      const store = useUserStore();
      store.clearUserInfo();
      ElMessage.error("登录已过期，请重新登录");
    } else {
      ElMessage.error(error.message || "请求失败");
    }
    return Promise.reject(error);
  },
);

const http = async <T>(config: AxiosRequestConfig): Promise<Result<T>> => {
  const response = await instance.request<Result<T>>(config);
  return response.data;
};

export default http;
