import { getExplorerApiBase } from './blockscout'

export interface PlannerProviderPair {
  tokenInSymbol?: string
  tokenOutSymbol?: string
  status?: string
}

export interface PlannerProviderCapability {
  chainId?: number
  provider?: string
  executionMode?: string
  live?: boolean
  quoteLive?: boolean
  executionLive?: boolean
  supportedLegTypes?: string[]
  pairs?: PlannerProviderPair[]
  notes?: string[]
}

export interface PlannerCapabilitiesResponse {
  providers?: PlannerProviderCapability[]
}

export interface InternalExecutionPlanResponse {
  plannerResponse?: {
    decision?: string
    steps?: unknown[]
  }
  execution?: {
    contractAddress?: string
  }
}

const plannerBase = `${getExplorerApiBase()}/token-aggregation/api/v2`

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

export const plannerApi = {
  getCapabilities: async (chainId = 138): Promise<PlannerCapabilitiesResponse> =>
    fetchJson<PlannerCapabilitiesResponse>(`${plannerBase}/providers/capabilities?chainId=${chainId}`),

  getInternalExecutionPlan: async (): Promise<InternalExecutionPlanResponse> =>
    fetchJson<InternalExecutionPlanResponse>(`${plannerBase}/routes/internal-execution-plan`, {
      method: 'POST',
      headers: {
        'content-type': 'application/json',
      },
      body: JSON.stringify({
        sourceChainId: 138,
        tokenIn: '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2',
        tokenOut: '0x004b63A7B5b0E06f6bB6adb4a5F9f590BF3182D1',
        amountIn: '100000000000000000',
      }),
    }),
}
