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

export interface Transaction {
  chain_id: number
  hash: string
  block_number: number
  block_hash: string
  transaction_index: number
  from_address: string
  to_address?: string
  value: string
  gas_price?: number
  max_fee_per_gas?: number
  max_priority_fee_per_gas?: number
  gas_limit: number
  gas_used?: number
  status?: number
  input_data?: string
  contract_address?: string
  created_at: string
}

export const transactionsApi = {
  get: async (chainId: number, hash: string): Promise<ApiResponse<Transaction>> => {
    const raw = await fetchBlockscoutJson<unknown>(`/api/v2/transactions/${hash}`)
    return { data: normalizeTransaction(raw as never, chainId) }
  },
  /** Use when you need to check response.ok before setting state (avoids treating 4xx/5xx body as data). */
  getSafe: async (chainId: number, hash: string): Promise<{ ok: boolean; data: Transaction | null }> => {
    try {
      const { data } = await transactionsApi.get(chainId, hash)
      return { ok: true, data }
    } catch {
      return { ok: false, data: null }
    }
  },
  list: async (chainId: number, page: number, pageSize: number): Promise<ApiResponse<Transaction[]>> => {
    const params = new URLSearchParams({
      page: page.toString(),
      page_size: pageSize.toString(),
    })
    const raw = await fetchBlockscoutJson<{ items?: unknown[] }>(`/api/v2/transactions?${params.toString()}`)
    const data = Array.isArray(raw?.items) ? raw.items.map((item) => normalizeTransaction(item as never, chainId)) : []
    return { data }
  },
  /** Use when you need to check ok before setting state (avoids treating error body as list). */
  listSafe: async (chainId: number, page: number, pageSize: number): Promise<{ ok: boolean; data: Transaction[] }> => {
    try {
      const { data } = await transactionsApi.list(chainId, page, pageSize)
      return { ok: true, data }
    } catch {
      return { ok: false, data: [] }
    }
  },
}
