const BASE_URL: string = import.meta.env.VITE_API_BASE_URL ?? ''

/**
 * Fetch wrapper centralizado para la API pública de canasta básica.
 * — Sin credenciales ni CSRF (API pública).
 * — Siempre envía Accept: application/json.
 */
export async function apiFetch<T>(path: string, params?: Record<string, string>): Promise<T> {
  const url = new URL(`${BASE_URL}${path}`)

  if (params) {
    Object.entries(params).forEach(([key, value]) => {
      if (value !== '') {
        url.searchParams.set(key, value)
      }
    })
  }

  const response = await fetch(url.toString(), {
    method: 'GET',
    headers: {
      Accept: 'application/json',
    },
  })

  if (!response.ok) {
    const body = await response.json().catch(() => ({}))
    const message: string =
      typeof body === 'object' && body !== null && 'message' in body
        ? String((body as Record<string, unknown>).message)
        : `Error ${response.status}`
    throw new Error(message)
  }

  return response.json() as Promise<T>
}


