import { getTokenAggregationApiBase } from '@/services/api/tokenAggregation'

export interface PolygonMeshTokenRow {
  hubSymbol: string
  wrappedSymbol: string
  decimals?: number
  hub138Address?: string | null
  mainnetRootAddress?: string
  polygonAddress?: string
  polygonExplorerUrl?: string | null
  hub138ExplorerUrl?: string | null
  mainnetExplorerUrl?: string | null
}

export interface PolygonMapperResponse {
  chainId: number
  hubChainId: number
  meshTokens: PolygonMeshTokenRow[]
  vipBridge?: {
    bridgeAddress?: string
    austdPolygon?: string
    ausdtAll?: string
  }
  officialPolygonTokenList?: {
    mappedApi?: string
    upstreamRepo?: string
    submissionDoc?: string
  }
  match?: PolygonMeshTokenRow
  query?: string
}

export async function fetchPolygonMapper(query?: string): Promise<PolygonMapperResponse | null> {
  const params = query?.trim() ? `?q=${encodeURIComponent(query.trim())}` : ''
  try {
    const response = await fetch(`${getTokenAggregationApiBase()}/report/polygon-mapper${params}`, {
      cache: 'no-store',
    })
    if (!response.ok) return null
    return (await response.json()) as PolygonMapperResponse
  } catch {
    return null
  }
}

export function polygonMapperRowForChain(
  mapper: PolygonMapperResponse | null,
  chainId: number,
  address: string,
): PolygonMeshTokenRow | undefined {
  if (!mapper || chainId !== 137) return undefined
  const lower = address.toLowerCase()
  return mapper.meshTokens?.find(
    (row) =>
      row.polygonAddress?.toLowerCase() === lower ||
      row.hub138Address?.toLowerCase() === lower ||
      row.mainnetRootAddress?.toLowerCase() === lower,
  )
}
