import { getToken } from "./authState";
import { resolveApiUrl } from "../config/runtime";

function authHeaders(): Record<string, string> {
  const token = getToken();
  return token ? { Authorization: `Bearer ${token}` } : {};
}

export async function api<T>(url: string, options: RequestInit = {}): Promise<T> {
  const hasBody = options.body !== undefined && options.body !== null;
  const response = await fetch(resolveApiUrl(url), {
    ...options,
    headers: {
      ...(hasBody && !(options.body instanceof FormData) ? { "Content-Type": "application/json" } : {}),
      ...authHeaders(),
      ...((options.headers as Record<string, string> | undefined) ?? {})
    } as HeadersInit
  });
  const data = await response.json().catch(() => ({}));
  if (!response.ok) {
    throw new Error(data.message ?? "请求失败");
  }
  return data as T;
}
