/**
 * Unit tests for addNetwork functionality
 */

import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import { addNetwork, isNetworkAdded, addOrSwitchNetwork, getEthereumProvider } from './addNetwork';

// Mock window.ethereum
const mockEthereum = {
  isMetaMask: true,
  request: vi.fn(),
  on: vi.fn(),
  removeListener: vi.fn(),
};

describe('addNetwork', () => {
  beforeEach(() => {
    vi.clearAllMocks();
    if (typeof window !== 'undefined') {
      (window as any).ethereum = mockEthereum;
    }
  });

  afterEach(() => {
    if (typeof window !== 'undefined') {
      delete (window as any).ethereum;
    }
  });

  it('should get Ethereum provider', () => {
    const provider = getEthereumProvider();
    expect(provider).toBe(mockEthereum);
  });

  it('should throw error if MetaMask not installed', () => {
    if (typeof window !== 'undefined') {
      delete (window as any).ethereum;
    }
    expect(() => getEthereumProvider()).toThrow('MetaMask is not installed');
  });

  it('should add network successfully', async () => {
    mockEthereum.request.mockResolvedValue(null);
    
    await addNetwork();
    
    expect(mockEthereum.request).toHaveBeenCalledWith({
      method: 'wallet_addEthereumChain',
      params: [expect.objectContaining({
        chainId: '0x8a',
        chainName: 'DeFi Oracle Meta Mainnet',
      })],
    });
  });

  it('should check if network is added', async () => {
    mockEthereum.request.mockResolvedValue('0x8a');
    
    const isAdded = await isNetworkAdded();
    expect(isAdded).toBe(true);
  });

  it('should add or switch network', async () => {
    mockEthereum.request.mockResolvedValueOnce('0x1'); // Current chain
    mockEthereum.request.mockResolvedValueOnce(null); // Switch network
    
    await addOrSwitchNetwork();
    
    expect(mockEthereum.request).toHaveBeenCalledWith({
      method: 'wallet_switchEthereumChain',
      params: [{ chainId: '0x8a' }],
    });
  });
});

