import { ApiResponse } from './client'
import { fetchBlockscoutJson, normalizeBlock } from './blockscout'

export interface Block {
  chain_id: number
  number: number
  hash: string
  timestamp: string
  miner: string
  transaction_count: number
  gas_used: number
  gas_limit: number
}

export interface BlockListParams {
  chain_id: number
  page?: number
  page_size?: number
  min_block?: number
  max_block?: number
  miner?: string
  sort?: string
  order?: 'asc' | 'desc'
}

export const blocksApi = {
  list: async (params: BlockListParams): Promise<ApiResponse<Block[]>> => {
    const queryParams = new URLSearchParams()
    queryParams.append('chain_id', params.chain_id.toString())
    if (params.page) queryParams.append('page', params.page.toString())
    if (params.page_size) queryParams.append('page_size', params.page_size.toString())
    if (params.min_block) queryParams.append('min_block', params.min_block.toString())
    if (params.max_block) queryParams.append('max_block', params.max_block.toString())
    if (params.miner) queryParams.append('miner', params.miner)
    if (params.sort) queryParams.append('sort', params.sort)
    if (params.order) queryParams.append('order', params.order)

    const raw = await fetchBlockscoutJson<{ items?: unknown[] }>(`/api/v2/blocks?${queryParams.toString()}`)
    const data = Array.isArray(raw?.items) ? raw.items.map((item) => normalizeBlock(item as never, params.chain_id)) : []
    return { data }
  },

  getByNumber: async (chainId: number, number: number): Promise<ApiResponse<Block>> => {
    const raw = await fetchBlockscoutJson<unknown>(`/api/v2/blocks/${number}`)
    return { data: normalizeBlock(raw as never, chainId) }
  },

  getByHash: async (chainId: number, hash: string): Promise<ApiResponse<Block>> => {
    const raw = await fetchBlockscoutJson<unknown>(`/api/v2/blocks/${hash}`)
    return { data: normalizeBlock(raw as never, chainId) }
  },
}
