const DEFAULT_CLIENT_KEY = "9ca7f706-a8b0-4520-b467-5e8321df36fb";

function clientKey() {
  return process.env.NEXT_PUBLIC_X_CLIENT_KEY ?? DEFAULT_CLIENT_KEY;
}

function apiBase() {
  const base = process.env.NEXT_PUBLIC_API_URL?.replace(/\/$/, "");
  return base ?? "";
}

/** Server-side fetch for public landing data (requires `X-Client-Key`). */
export async function publicFetch<T>(path: string): Promise<T | null> {
  const base = apiBase();
  if (!base) return null;
  const url = `${base}${path.startsWith("/") ? path : `/${path}`}`;
  try {
    const res = await fetch(url, {
      headers: {
        "Content-Type": "application/json",
        "X-Client-Key": clientKey(),
      },
      next: { revalidate: 60 },
    });
    if (!res.ok) return null;
    const json = (await res.json()) as { data?: T };
    return json.data ?? null;
  } catch {
    // e.g. ECONNREFUSED during `next build` in Docker when API is not running
    return null;
  }
}
