import {
  type Url,
  createMeeClient,
  testnetMcUSDC,
  toMultichainNexusAccount
} from "@biconomy/abstractjs"
import { http, type Address, zeroAddress } from "viem"
import { privateKeyToAccount } from "viem/accounts"
import { baseSepolia } from "viem/chains"
import type { Ecosystem } from "../src/toEcosystem"

export const validateMeeNode = async ({
  infras,
  clients,
  meeNode
}: Ecosystem) => {
  const eoaAccount = privateKeyToAccount(infras[0].network.privateKey)
  const chains = infras.map(({ network }) => network.chain)

  const paymentChain = infras[0]
  const paymentChainId = paymentChain.network.chain.id
  const paymentChainTestClient = clients[0].testClient

  const mcNexus = await toMultichainNexusAccount({
    signer: eoaAccount,
    chains,
    transports: infras.map(({ network }) => http(network.rpcUrl))
  })

  const meeClient = await createMeeClient({
    url: `${meeNode?.url}/v3` as Url,
    account: mcNexus
  })

  const mcNexusAddress = mcNexus.addressOn(paymentChainId) as Address
  const feeTokenAddress = testnetMcUSDC.addressOn(baseSepolia.id)

  // @ts-ignore
  await paymentChainTestClient.deal({
    erc20: feeTokenAddress,
    account: mcNexusAddress,
    amount: 1000000000n
  })

  await paymentChainTestClient.setBalance({
    address: mcNexusAddress,
    value: 1000000000n
  })

  const quote = await meeClient.getQuote({
    instructions: [
      {
        calls: [{ to: zeroAddress, value: 1n, gasLimit: 100000n }],
        chainId: paymentChainId
      }
    ],
    feeToken: {
      address: feeTokenAddress,
      chainId: paymentChainId
    }
  })

  const { hash } = await meeClient.executeQuote({ quote })
  const receipt = await meeClient.waitForSupertransactionReceipt({ hash })
  if (receipt.transactionStatus !== "MINED_SUCCESS") {
    throw new Error(`transaction failed: ${receipt.transactionStatus}`)
  }
  console.log("mee validation passed ✅")
}
