type ApiResponse<T> = {
  success: boolean;
  data?: T;
  error?: { code: string; message: string };
};

export async function adminFetch<T>(path: string, options: RequestInit = {}): Promise<T> {
  const key = sessionStorage.getItem("admin_key");
  if (!key) throw new Error("未登录");

  const headers = new Headers(options.headers);
  headers.set("X-Admin-Key", key);
  if (!headers.has("Content-Type") && !(options.body instanceof FormData)) {
    headers.set("Content-Type", "application/json");
  }

  const res = await fetch(`/api/admin${path}`, { ...options, headers });
  const json: ApiResponse<T> = await res.json();
  if (!json.success) throw new Error(json.error?.message || "请求失败");
  return json.data as T;
}
