import {
  createBicoBundlerClient,
  toNexusAccount
} from "@biconomy/abstractjs-canary"
import { http, parseEther, zeroAddress } from "viem"
import { privateKeyToAccount } from "viem/accounts"
import type { Infra } from "../src/toEcosystem"
import { toClients } from "../src/utils"

export const validateCore = async ({
  bundler,
  network: { rpcUrl, chain, privateKey }
}: Infra) => {
  const eoaAccount = privateKeyToAccount(privateKey)
  const nexusAccount = await toNexusAccount({
    signer: eoaAccount,
    chain,
    transport: http(rpcUrl)
  })

  const accountAddress = await nexusAccount.getAddress()

  const bundlerClient = createBicoBundlerClient({
    account: nexusAccount,
    chain,
    transport: http(bundler.url),
    mock: true // Using mock mode for testing purposes
  })

  const { testClient } = await toClients({
    rpcUrl,
    chain,
    privateKey
  })

  await testClient.setBalance({
    address: accountAddress,
    value: parseEther("1")
  })

  const hash = await bundlerClient.sendUserOperation({
    calls: [
      {
        to: zeroAddress,
        value: 0n
      }
    ]
  })
  const { success } = await bundlerClient.waitForUserOperationReceipt({
    hash
  })
  if (!success) {
    throw new Error("core validation failed")
  }
  console.log("core validation passed ✅")
}
