import type { Client } from '../../clients/createClient.js'
import type { Transport } from '../../clients/transports/createTransport.js'
import {
  TransactionReceiptNotFoundError,
  type TransactionReceiptNotFoundErrorType,
} from '../../errors/transaction.js'
import type { ErrorType } from '../../errors/utils.js'
import type { Chain } from '../../types/chain.js'
import type { Hash } from '../../types/misc.js'
import type { RequestErrorType } from '../../utils/buildRequest.js'
import {
  type FormattedTransactionReceipt,
  formatTransactionReceipt,
} from '../../utils/formatters/transactionReceipt.js'

export type GetTransactionReceiptParameters = {
  /** The hash of the transaction. */
  hash: Hash
}

export type GetTransactionReceiptReturnType<
  chain extends Chain | undefined = undefined,
> = FormattedTransactionReceipt<chain>

export type GetTransactionReceiptErrorType =
  | RequestErrorType
  | TransactionReceiptNotFoundErrorType
  | ErrorType

/**
 * Returns the [Transaction Receipt](https://viem.sh/docs/glossary/terms#transaction-receipt) given a [Transaction](https://viem.sh/docs/glossary/terms#transaction) hash.
 *
 * - Docs: https://viem.sh/docs/actions/public/getTransactionReceipt
 * - Example: https://stackblitz.com/github/wevm/viem/tree/main/examples/transactions_fetching-transactions
 * - JSON-RPC Methods: [`eth_getTransactionReceipt`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_gettransactionreceipt)
 *
 * @param client - Client to use
 * @param parameters - {@link GetTransactionReceiptParameters}
 * @returns The transaction receipt. {@link GetTransactionReceiptReturnType}
 *
 * @example
 * import { createPublicClient, http } from 'viem'
 * import { mainnet } from 'viem/chains'
 * import { getTransactionReceipt } from 'viem/public'
 *
 * const client = createPublicClient({
 *   chain: mainnet,
 *   transport: http(),
 * })
 * const transactionReceipt = await getTransactionReceipt(client, {
 *   hash: '0x4ca7ee652d57678f26e887c149ab0735f41de37bcad58c9f6d3ed5824f15b74d',
 * })
 */
export async function getTransactionReceipt<chain extends Chain | undefined>(
  client: Client<Transport, chain>,
  { hash }: GetTransactionReceiptParameters,
) {
  const receipt = await client.request(
    {
      method: 'eth_getTransactionReceipt',
      params: [hash],
    },
    { dedupe: true },
  )

  if (!receipt) throw new TransactionReceiptNotFoundError({ hash })

  const format =
    client.chain?.formatters?.transactionReceipt?.format ||
    formatTransactionReceipt
  return format(
    receipt,
    'getTransactionReceipt',
  ) as GetTransactionReceiptReturnType<chain>
}
