import { notFound } from "next/navigation";

export class ApiDown extends Error {
  constructor() {
    super("API_DOWN");
  }
}

const base = () => process.env.NEXT_PUBLIC_API_URL ?? "http://127.0.0.1:8000";

export async function api<T>(path: string): Promise<T> {
  let response: Response;

  try {
    response = await fetch(`${base()}/api/v1${path}`, { cache: "no-store" });
  } catch {
    throw new ApiDown();
  }

  if (response.status === 404) {
    notFound();
  }

  if (!response.ok) {
    throw new ApiDown();
  }

  return response.json() as Promise<T>;
}

export function siteUrl() {
  return process.env.NEXT_PUBLIC_SITE_URL ?? "http://localhost:3000";
}
