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

export interface CuratedPoolRegistryEntry {
  chainId: number
  chainName: string
  poolAddress: string
  lpTokenAddress: string
  lpTokenType: 'dodo_dvm' | 'univ2_pair'
  venue: 'dodo_pmm' | 'uniswap_v2'
  baseSymbol: string
  quoteSymbol: string
  baseAddress: string
  quoteAddress: string
  status?: string
  role?: string
  publicRoutingEnabled?: boolean
  feeBps?: number
  totalLiquidityUsd?: number
  reserve0?: string
  reserve1?: string
  reserve0Usd?: number
  reserve1Usd?: number
  liquiditySource?: string
  liquidityAsOf?: string
  integrationStack?: string
}

export interface PoolRegistryResponse {
  generatedAt: string
  source: string
  complete: boolean
  count: number
  pools: CuratedPoolRegistryEntry[]
}

export interface LpPositionRow {
  chainId: number
  poolAddress: string
  lpTokenAddress: string
  lpTokenType: 'dodo_dvm' | 'univ2_pair'
  venue: string
  pairLabel: string
  shareBalanceRaw: string
  shareBalanceUnits: string
  shareOfPool: number
  estimatedUsd: number | null
  baseSymbol: string
  quoteSymbol: string
  status: 'active' | 'zero'
}

export interface LpPositionsResponse {
  generatedAt: string
  chainId: number
  address: string
  rpcUsed: boolean
  poolsScanned: number
  activePositions: number
  totalEstimatedUsd: number | null
  positions: LpPositionRow[]
  notes: string[]
}

const base = () => getTokenAggregationApiBase()

export async function fetchPoolRegistry(chainId?: number): Promise<PoolRegistryResponse | null> {
  const query = chainId ? `?chainId=${chainId}` : ''
  const response = await fetch(`${base()}/report/pool-registry${query}`, { cache: 'no-store' })
  if (!response.ok) return null
  return (await response.json()) as PoolRegistryResponse
}

export async function fetchLpPositions(params: {
  chainId: number
  address: string
  hintAddresses?: string[]
}): Promise<LpPositionsResponse | null> {
  const search = new URLSearchParams({
    chainId: String(params.chainId),
    address: params.address,
  })
  if (params.hintAddresses?.length) {
    search.set('hintAddresses', params.hintAddresses.join(','))
  }
  const response = await fetch(`${base()}/report/lp-positions?${search.toString()}`, { cache: 'no-store' })
  if (!response.ok) return null
  return (await response.json()) as LpPositionsResponse
}
