import { getExplorerApiBase } from './blockscout'

export interface NetworksConfigChain {
  chainIdDecimal?: number
  chainName?: string
  shortName?: string
}

export interface NetworksConfigResponse {
  defaultChainId?: number
  chains?: NetworksConfigChain[]
}

export interface TokenListToken {
  chainId?: number
  symbol?: string
  address?: string
  name?: string
  decimals?: number
  logoURI?: string
  tags?: string[]
}

export interface TokenListResponse {
  tokens?: TokenListToken[]
}

export interface CapabilitiesResponse {
  chainId?: number
  chainName?: string
  walletSupport?: {
    walletAddEthereumChain?: boolean
    walletWatchAsset?: boolean
  }
  http?: {
    supportedMethods?: string[]
    unsupportedMethods?: string[]
  }
  tracing?: {
    supportedMethods?: string[]
    unsupportedMethods?: string[]
  }
}

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

export const configApi = {
  getNetworks: async (): Promise<NetworksConfigResponse> =>
    fetchJson<NetworksConfigResponse>('/api/config/networks'),

  getTokenList: async (): Promise<TokenListResponse> =>
    fetchJson<TokenListResponse>('/api/config/token-list'),

  getCapabilities: async (): Promise<CapabilitiesResponse> =>
    fetchJson<CapabilitiesResponse>('/api/config/capabilities'),
}
