import axios from "axios";

const http = axios.create({
  baseURL: "/api"
});

http.interceptors.request.use((config) => {
  const token = localStorage.getItem("token");
  if (token) {
    config.headers["satoken"] = token;
  }
  return config;
});

http.interceptors.response.use(
  (response) => {
    const data = response.data;
    if (data && data.code !== 0) {
      if (data.message && (data.message.includes("未登录") || data.message.includes("token"))) {
        localStorage.removeItem("token");
        localStorage.removeItem("role");
        window.location.href = "/login";
      }
      return Promise.reject(new Error(data.message || "请求失败"));
    }
    return response;
  },
  (error) => {
    if (error && error.response && error.response.status === 401) {
      localStorage.removeItem("token");
      localStorage.removeItem("role");
      window.location.href = "/login";
    }
    return Promise.reject(error);
  }
);

export default http;

