import type { Address } from 'abitype'

import type { Client } from '../../clients/createClient.js'
import type { Transport } from '../../clients/transports/createTransport.js'
import { multicall3Abi } from '../../constants/abis.js'
import type { ErrorType } from '../../errors/utils.js'
import type { BlockTag } from '../../types/block.js'
import type { Chain } from '../../types/chain.js'
import type { Hash } from '../../types/misc.js'
import { decodeFunctionResult } from '../../utils/abi/decodeFunctionResult.js'
import { encodeFunctionData } from '../../utils/abi/encodeFunctionData.js'
import {
  type FormatBlockParameterErrorType,
  formatBlockParameter,
} from '../../utils/block/formatBlockParameter.js'
import type { RequestErrorType } from '../../utils/buildRequest.js'
import { getAction } from '../../utils/getAction.js'
import { type CallParameters, call } from './call.js'

export type GetBalanceParameters = {
  /** The address of the account. */
  address: Address
} & (
  | {
      /** The balance of the account at a block number. */
      blockNumber?: bigint | undefined
      blockTag?: undefined
      blockHash?: undefined
      requireCanonical?: undefined
    }
  | {
      blockNumber?: undefined
      /** The balance of the account at a block tag. */
      blockTag?: BlockTag | undefined
      blockHash?: undefined
      requireCanonical?: undefined
    }
  | {
      blockNumber?: undefined
      blockTag?: undefined
      /** The balance of the account at a block specified by block hash. */
      blockHash: Hash
      /** Whether or not to throw an error if the block is not in the canonical chain. Only allowed in conjunction with `blockHash`. */
      requireCanonical?: boolean | undefined
    }
)

export type GetBalanceReturnType = bigint

export type GetBalanceErrorType =
  | FormatBlockParameterErrorType
  | RequestErrorType
  | ErrorType

/**
 * Returns the balance of an address in wei.
 *
 * - Docs: https://viem.sh/docs/actions/public/getBalance
 * - JSON-RPC Methods: [`eth_getBalance`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getbalance)
 *
 * You can convert the balance to ether units with [`formatEther`](https://viem.sh/docs/utilities/formatEther).
 *
 * ```ts
 * const balance = await getBalance(client, {
 *   address: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',
 *   blockTag: 'safe'
 * })
 * const balanceAsEther = formatEther(balance)
 * // "6.942"
 * ```
 *
 * @param client - Client to use
 * @param parameters - {@link GetBalanceParameters}
 * @returns The balance of the address in wei. {@link GetBalanceReturnType}
 *
 * @example
 * import { createPublicClient, http } from 'viem'
 * import { mainnet } from 'viem/chains'
 * import { getBalance } from 'viem/public'
 *
 * const client = createPublicClient({
 *   chain: mainnet,
 *   transport: http(),
 * })
 * const balance = await getBalance(client, {
 *   address: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e',
 * })
 * // 10000000000000000000000n (wei)
 */
export async function getBalance<chain extends Chain | undefined>(
  client: Client<Transport, chain>,
  {
    address,
    blockHash,
    blockNumber,
    blockTag = client.experimental_blockTag ?? 'latest',
    requireCanonical,
  }: GetBalanceParameters,
): Promise<GetBalanceReturnType> {
  const block = formatBlockParameter({
    blockHash,
    blockNumber,
    blockTag,
    requireCanonical,
  })

  if (client.batch?.multicall && client.chain?.contracts?.multicall3) {
    const multicall3Address = client.chain.contracts.multicall3.address

    const calldata = encodeFunctionData({
      abi: multicall3Abi,
      functionName: 'getEthBalance',
      args: [address],
    })

    const { data } = await getAction(
      client,
      call,
      'call',
    )({
      to: multicall3Address,
      data: calldata,
      blockHash,
      blockNumber,
      blockTag,
      requireCanonical,
    } as unknown as CallParameters<chain>)

    return decodeFunctionResult({
      abi: multicall3Abi,
      functionName: 'getEthBalance',
      args: [address],
      data: data || '0x',
    })
  }

  const balance = await client.request({
    method: 'eth_getBalance',
    params: [address, block],
  })
  return BigInt(balance)
}
