export interface PublicFetchMetadata {
  source: string
  lastModified: string | null
}

export function getPublicExplorerBase(): string {
  const configured = (process.env.NEXT_PUBLIC_API_URL || '').trim()
  return configured || 'https://blockscout.defi-oracle.io'
}

export async function fetchPublicJson<T>(path: string): Promise<T> {
  const response = await fetch(`${getPublicExplorerBase()}${path}`)
  if (!response.ok) {
    throw new Error(`HTTP ${response.status}`)
  }
  return (await response.json()) as T
}

export async function fetchPublicJsonWithMeta<T>(path: string): Promise<{ data: T; meta: PublicFetchMetadata }> {
  const response = await fetch(`${getPublicExplorerBase()}${path}`)
  if (!response.ok) {
    throw new Error(`HTTP ${response.status}`)
  }

  return {
    data: (await response.json()) as T,
    meta: {
      source: response.headers.get('X-Config-Source') || 'explorer-api',
      lastModified: response.headers.get('Last-Modified'),
    },
  }
}
