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

export interface AddressInfo {
  address: string
  chain_id: number
  transaction_count: number
  token_count: number
  is_contract: boolean
  label?: string
  tags: string[]
}

export interface AddressTransactionsParams {
  chain_id: number
  from_address: string
  page?: number
  page_size?: number
}

export interface TransactionSummary {
  hash: string
  block_number: number
  from_address: string
  to_address?: string
  value: string
  status?: number
}

export const addressesApi = {
  get: async (chainId: number, address: string): Promise<ApiResponse<AddressInfo>> => {
    return apiClient.get<AddressInfo>(`/api/v1/addresses/${chainId}/${address}`)
  },
  /** Use when you need to check response.ok before setting state (avoids treating 4xx/5xx body as data). */
  getSafe: async (chainId: number, address: string): Promise<{ ok: boolean; data: AddressInfo | null }> => {
    return apiClient.getSafe<AddressInfo>(`/api/v1/addresses/${chainId}/${address}`)
  },
  getTransactionsSafe: async (
    chainId: number,
    address: string,
    page = 1,
    pageSize = 20
  ): Promise<{ ok: boolean; data: TransactionSummary[] }> => {
    try {
      const params = new URLSearchParams({
        chain_id: chainId.toString(),
        from_address: address,
        page: page.toString(),
        page_size: pageSize.toString(),
      })
      const raw = (await apiClient.get(`/api/v1/transactions?${params.toString()}`)) as unknown as {
        data?: TransactionSummary[]
        items?: TransactionSummary[]
      }
      const data = Array.isArray(raw?.data) ? raw.data : Array.isArray(raw?.items) ? raw.items : []
      return { ok: true, data }
    } catch {
      return { ok: false, data: [] }
    }
  },

  getTransactions: async (
    chainId: number,
    address: string,
    page = 1,
    pageSize = 20
  ): Promise<ApiResponse<TransactionSummary[]>> => {
    const params = new URLSearchParams({
      chain_id: chainId.toString(),
      from_address: address,
      page: page.toString(),
      page_size: pageSize.toString(),
    })
    const raw = (await apiClient.get(`/api/v1/transactions?${params.toString()}`)) as unknown as {
      data?: TransactionSummary[]
      items?: TransactionSummary[]
    }
    const data = Array.isArray(raw?.data) ? raw.data : Array.isArray(raw?.items) ? raw.items : []
    return { data }
  },
}
