import { apiClient, ApiResponse } from './client'

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>> => {
    return apiClient.get<Transaction>(`/api/v1/transactions/${chainId}/${hash}`)
  },
  /** 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 }> => {
    return apiClient.getSafe<Transaction>(`/api/v1/transactions/${chainId}/${hash}`)
  },
  list: async (chainId: number, page: number, pageSize: number): Promise<ApiResponse<Transaction[]>> => {
    const params = new URLSearchParams({
      chain_id: chainId.toString(),
      page: page.toString(),
      page_size: pageSize.toString(),
    })
    const raw = (await apiClient.get(`/api/v1/transactions?${params.toString()}`)) as unknown as { data?: Transaction[]; items?: Transaction[] }
    const data = Array.isArray(raw?.data) ? raw.data : Array.isArray(raw?.items) ? raw.items : []
    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 params = new URLSearchParams({
        chain_id: chainId.toString(),
        page: page.toString(),
        page_size: pageSize.toString(),
      })
      const raw = await apiClient.getSafe<Transaction[]>(`/api/v1/transactions?${params.toString()}`)
      if (!raw.ok) return { ok: false, data: [] }
      const data = Array.isArray(raw.data) ? raw.data : []
      return { ok: true, data }
    } catch {
      return { ok: false, data: [] }
    }
  },
}
