import { getApiOrigin } from '@/lib/site';

interface ApiEnvelope<T> {
  success: boolean;
  data: T;
  error?: string;
}

export async function serverFetch<T>(path: string, revalidate = 120): Promise<T> {
  const res = await fetch(`${getApiOrigin()}/api${path}`, {
    next: { revalidate },
  });

  if (!res.ok) {
    throw new Error(`API ${res.status}: ${path}`);
  }

  const json = (await res.json()) as ApiEnvelope<T>;
  if (!json.success) {
    throw new Error(json.error || 'Request failed');
  }

  return json.data;
}
