import { timeOut } from "@/lib/utils";

const BASE_URL = process.env.NEXT_PUBLIC_API_BASE_URL!;

export async function apiFetch<T>(endpoint: string, options?: RequestInit): Promise<T> {
  await timeOut(500);

  const res = await fetch(`${BASE_URL}${endpoint}`, {
    cache: "no-store",
    ...options,
  });

  if (!res.ok) {
    const text = await res.text().catch(() => "");
    let parsed: any = null;
    try {
      parsed = JSON.parse(text);
    } catch {}

    const backendMessage = parsed?.message;

    throw new Error(backendMessage || text || "Hubo un error al cargar la información.");
  }

  return res.json() as Promise<T>;
}
