const TOKEN_KEY = "mc_auth_token";

export function getToken() {
  return localStorage.getItem(TOKEN_KEY) || "";
}

export function setToken(t) {
  localStorage.setItem(TOKEN_KEY, t);
}

export function clearToken() {
  localStorage.removeItem(TOKEN_KEY);
}

export function getApiBase() {
  const envBase = import.meta.env.VITE_API_BASE;
  if (envBase) {
    return String(envBase).replace(/\/+$/, "");
  }
  if (typeof window === "undefined") return "http://localhost:8080/api";
  return `${window.location.origin}/api`;
}

export async function apiRequest(path, options = {}) {
  const base = getApiBase();
  const token = getToken();
  const res = await fetch(`${base}${path}`, {
    headers: {
      "Content-Type": "application/json",
      ...(token ? { Authorization: `Bearer ${token}` } : {}),
      ...(options.headers || {}),
    },
    ...options,
  });
  let body = null;
  try {
    body = await res.json();
  } catch {
    body = null;
  }
  if (!res.ok) {
    const message =
      (body && body.error) || `请求失败 (${res.status} ${res.statusText})`;
    throw new Error(message);
  }
  return body;
}
