import { getExplorerApiBase } from './blockscout'

export interface BridgeRouteCatalog {
  weth9: Record<string, string>
  weth10: Record<string, string>
  trustless?: Record<string, string>
}

export interface BridgeRoutesResponse {
  source?: string
  lastModified?: string
  updated?: string
  description?: string
  routes: BridgeRouteCatalog
  chain138Bridges?: Record<string, string>
}

const bridgeRoutesBase = `${getExplorerApiBase()}/token-aggregation/api/v1/bridge`

export function normalizeBridgeRouteEntries(
  routes: BridgeRouteCatalog | null | undefined,
): Array<{ bridge: 'WETH9' | 'WETH10'; destination: string; address: string }> {
  if (!routes) return []

  const entries: Array<{ bridge: 'WETH9' | 'WETH10'; destination: string; address: string }> = []

  for (const [destination, address] of Object.entries(routes.weth9 || {})) {
    if (address) entries.push({ bridge: 'WETH9', destination, address })
  }
  for (const [destination, address] of Object.entries(routes.weth10 || {})) {
    if (address) entries.push({ bridge: 'WETH10', destination, address })
  }

  return entries.sort((left, right) =>
    left.destination.localeCompare(right.destination) || left.bridge.localeCompare(right.bridge),
  )
}

export const bridgeRoutesApi = {
  getRoutesSafe: async (): Promise<{ ok: boolean; data: BridgeRoutesResponse | null }> => {
    try {
      const response = await fetch(`${bridgeRoutesBase}/routes`)
      if (!response.ok) {
        return { ok: false, data: null }
      }
      const payload = (await response.json()) as BridgeRoutesResponse
      if (!payload?.routes?.weth9 || !payload?.routes?.weth10) {
        return { ok: false, data: null }
      }
      return { ok: true, data: payload }
    } catch {
      return { ok: false, data: null }
    }
  },
}
