const API_URL = process.env.NEXT_PUBLIC_API_URL || "http://127.0.0.1:8000";

export async function apiFetch(endpoint: string, options: RequestInit & { token?: string } = {}) {
  const { token, ...fetchOptions } = options;
  const headers: Record<string, string> = {
    "Accept": "application/json",
    "Content-Type": "application/json",
    ...(options.headers as Record<string, string> || {}),
  };
  if (token) headers["Authorization"] = `Bearer ${token}`;

  const res = await fetch(`${API_URL}/api${endpoint}`, { ...fetchOptions, headers });
  const data = await res.json();

  if (!res.ok) throw new Error(data.message || "API request failed");
  return data;
}
