import { API_URL } from '@/core/config/env';

type Json = Record<string, unknown> | unknown[] | null;

// Wrap fetch with sane defaults and optional base URL handling
export async function apiFetch(input: string, init: RequestInit = {}): Promise<Response> {
  const isAbsolute = /^https?:\/\//i.test(input);
  const url = isAbsolute ? input : `${API_URL}${input.startsWith('/') ? '' : '/'}${input}`;

  const resp = await fetch(url, {
    cache: 'no-store',
    keepalive: true,
    ...init,
  });
  return resp;
}

export async function fetchJson<T = Json>(input: string, init: RequestInit = {}): Promise<T> {
  const resp = await apiFetch(input, init);
  if (!resp.ok) {
    throw new Error(`HTTP error! status: ${resp.status}`);
  }
  return (await resp.json()) as T;
}

// Fetch JSON from the public folder at /public/json/<name>.json
// Note: This uses a relative path; server-side usage may require an absolute SITE_URL.
export async function fetchPublicJson<T = Json>(name: string): Promise<T> {
  const path = `/json/${name}.json`;
  const resp = await fetch(path, { cache: 'no-store', keepalive: true });
  if (!resp.ok) {
    throw new Error(`HTTP error! status: ${resp.status}`);
  }
  return (await resp.json()) as T;
}

