import { resolveExplorerApiBase } from '@/libs/frontend-api-client/api-base'

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

/** Production SSR fallback when NEXT_PUBLIC_API_URL is unset (same host as public explorer). */
const DEFAULT_PUBLIC_EXPLORER_BASE = 'https://explorer.d-bis.org'

export function getPublicExplorerBase(): string {
  return resolveExplorerApiBase({
    envValue: process.env.NEXT_PUBLIC_API_URL,
    serverFallback: DEFAULT_PUBLIC_EXPLORER_BASE,
  })
}

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'),
    },
  }
}
