export const API_BASE = "/api";

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

let token: string | null = localStorage.getItem("stamp_token");

export function setToken(t: string) {
  token = t;
  localStorage.setItem("stamp_token", t);
}

export function clearToken() {
  token = null;
  localStorage.removeItem("stamp_token");
}

export function getToken() {
  return token;
}

export async function apiFetch<T>(path: string, options: RequestInit = {}): Promise<T> {
  const headers = new Headers(options.headers);
  if (!headers.has("Content-Type") && !(options.body instanceof FormData)) {
    headers.set("Content-Type", "application/json");
  }
  if (token) {
    headers.set("Authorization", `Bearer ${token}`);
  }

  const res = await fetch(`${API_BASE}${path}`, { ...options, headers });
  const json: ApiResponse<T> = await res.json();

  if (!json.success) {
    throw new Error(json.error?.message || "请求失败");
  }
  return json.data as T;
}
