import axios from "axios";
import { Toast } from "@douyinfe/semi-ui";

// 自动推断 API 地址：优先级依次为 window.CONFIG > VITE_API_BASE_URL > 当前页面的 hostname:8000
const getBaseUrl = () => {
  const winConfig =
    typeof window !== "undefined"
      ? (window as unknown as { CONFIG?: { API_BASE_URL?: string } }).CONFIG?.API_BASE_URL
      : undefined;
  if (typeof winConfig === "string" && winConfig) return winConfig;
  if (typeof import.meta !== "undefined" && import.meta.env && import.meta.env.VITE_API_BASE_URL) {
    return import.meta.env.VITE_API_BASE_URL;
  }
  // 自动使用当前页面的 hostname，API 端口固定为 8000
  if (typeof window !== "undefined") {
    return `${window.location.protocol}//${window.location.hostname}:8000`;
  }
  return "http://localhost:8000";
};

export const client = axios.create({
  baseURL: getBaseUrl(),
});

client.interceptors.response.use(
  (response) => response,
  (error) => {
    // Check if error has a response (server responded with status code outside 2xx)
    if (error.response) {
      const { status, data } = error.response;
      const message = data?.detail || data?.message || "请求失败";

      // Handle specific status codes
      if (status >= 500) {
        Toast.error(`服务器错误 (${status}): ${message}`);
      } else if (status >= 400) {
        Toast.error(`请求错误 (${status}): ${message}`);
      }
    } else if (error.request) {
      // The request was made but no response was received
      Toast.error("网络错误: 无法连接到服务器");
    } else {
      // Something happened in setting up the request that triggered an Error
      Toast.error(`请求配置错误: ${error.message}`);
    }

    return Promise.reject(error);
  },
);

export async function request<T>(
  path: string,
  init?: { method?: string; data?: unknown; params?: Record<string, unknown> },
): Promise<T> {
  const method = init?.method || "GET";
  const response = await client.request<T>({
    url: path,
    method,
    params: init?.params,
    data: init?.data,
  });
  return response.data;
}
