import { vi } from 'vitest'
import { switchOrAddChain, watchTokenInWallet } from '@/utils/walletWatchToken'
import type { WalletChain } from '@/components/wallet/AddToMetaMask'

const chain138: WalletChain = {
  chainId: '0x8a',
  chainIdDecimal: 138,
  chainName: 'DeFi Oracle Meta Mainnet',
  nativeCurrency: { name: 'Ether', symbol: 'ETH', decimals: 18 },
  rpcUrls: ['https://rpc-http-pub.d-bis.org'],
  blockExplorerUrls: ['https://explorer.d-bis.org'],
}

describe('walletWatchToken', () => {
  it('switches when chain already exists', async () => {
    const request = vi.fn().mockResolvedValue(null)
    const ok = await switchOrAddChain({ request }, chain138)
    expect(ok).toBe(true)
    expect(request).toHaveBeenCalledWith({
      method: 'wallet_switchEthereumChain',
      params: [{ chainId: '0x8a' }],
    })
  })

  it('adds chain when wallet reports 4902', async () => {
    const request = vi
      .fn()
      .mockRejectedValueOnce({ code: 4902 })
      .mockResolvedValueOnce(null)
    const ok = await switchOrAddChain({ request }, chain138)
    expect(ok).toBe(true)
    expect(request).toHaveBeenNthCalledWith(2, {
      method: 'wallet_addEthereumChain',
      params: [
        expect.objectContaining({
          chainId: '0x8a',
          chainName: 'DeFi Oracle Meta Mainnet',
        }),
      ],
    })
  })

  it('watchTokenInWallet passes hex chainId for Chain 138 tokens', async () => {
    const request = vi
      .fn()
      .mockResolvedValueOnce(null)
      .mockResolvedValueOnce(true)
    const result = await watchTokenInWallet(
      { request },
      {
        chainId: 138,
        address: '0xf22258f57794CC8E06237084b353Ab30fFfa640b',
        symbol: 'cUSDC',
        decimals: 6,
      },
      chain138,
    )
    expect(result).toEqual({ ok: true, added: true })
    expect(request).toHaveBeenNthCalledWith(2, {
      method: 'wallet_watchAsset',
      params: {
        type: 'ERC20',
        options: expect.objectContaining({
          chainId: '0x8a',
          symbol: 'cUSDC',
        }),
      },
    })
  })
})
