// lib/apiClient.ts
import { IBaseResponse } from "@/types/api";

export async function fetchApi<T>(path: string): Promise<IBaseResponse<T>> {
  const base = process.env.NEXT_PUBLIC_API_URL;
  if (!base) {
    throw new Error(
      "NEXT_PUBLIC_API_URL is not defined. Please set it in your env (e.g., .env.local)."
    );
  }

  let url: string;
  try {
    // Robustly join base + path regardless of leading/trailing slashes
    url = new URL(path, base).toString();
  } catch (e) {
    throw new Error(`Invalid API URL. base='${base}' path='${path}'`);
  }

  let res: Response;
  try {
    res = await fetch(url);
  } catch (err: any) {
    // Network/DNS/connection-level errors land here
    const reason = err?.message || String(err);
    throw new Error(`Failed to fetch '${url}': ${reason}`);
  }

  if (!res.ok) {
    const body = await res.text().catch(() => "");
    throw new Error(
      `Failed to fetch '${url}': ${res.status} ${res.statusText}${
        body ? ` - ${body}` : ""
      }`
    );
  }

  return res.json();
}
