using System.Numerics;
using Managing.Application.Abstractions.Services;
using Managing.Common;
using Managing.Domain.Evm;
using Managing.Infrastructure.Evm;
using Managing.Infrastructure.Evm.Abstractions;
using Managing.Infrastructure.Evm.Services;
using Microsoft.Extensions.Options;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using Nethereum.Contracts;
using Nethereum.Contracts.Standards.ERC721.ContractDefinition;
using Nethereum.Web3;
using Xunit;
using static Managing.Common.Enums;
using Assert = Xunit.Assert;

namespace Managing.Infrastructure.Tests;

public class EvmManagerTests
{
    public readonly EvmManager _manager;
    private readonly List<Chain> _chains;

    public List<ISubgraphPrices> Subgraphs;
    public readonly IWeb3ProxyService _web3Proxy;
    public readonly string PublicAddress = "0x932167388dd9aad41149b3ca23ebd489e2e2dd78";


    public EvmManagerTests()
    {
        // Use the helper method to create Web3ProxyService
        _web3Proxy = CreateWebProxyService();

        var cache = new Mock<ICacheService>();
        _manager = new EvmManager(Subgraphs, _web3Proxy, cache.Object);
        _chains = ChainService.GetChains();
    }

    [Ignore]
    [Theory]
    [InlineData("")]
    public async Task Should_get_address_balance(string address)
    {
        var balance = await _manager.GetAddressBalance(address);
        Assert.IsType<decimal>(balance);
        Assert.True(balance > -1);
    }

    // Connect to nft contract
    [Ignore]
    [Theory]
    [InlineData("0x17f4BAa9D35Ee54fFbCb2608e20786473c7aa49f")]
    public async Task Should_return_holder_list_for_nft_collection(string contract)
    {
        var holders = await _manager.GetContractHolders(contract, DateTime.UtcNow.AddDays(-30));
        Assert.IsType<List<Holder>>(holders);
        Assert.True(holders.Any());
    }

    [Ignore]
    [Theory]
    [InlineData("0xa435530d50d7D17Fd9fc6E1c897Dbf7C08E12d35", "0x17f4BAa9D35Ee54fFbCb2608e20786473c7aa49f")]
    public async Task Should_return_event_transfer_nft(string owner, string contract)
    {
        var holders = await _manager.GetNftEvent(owner, contract);
        Assert.IsType<List<EventLog<TransferEventDTO>>>(holders);
        Assert.True(holders.Any());
    }


    [Ignore]
    [Fact]
    public async Task Should_return_date_of_block()
    {
        var date = await _manager.GetBlockDate(38793245);
        Assert.Equal(new DateTime(2022, 11, 17, 11, 15, 33), date);
    }

    [Fact]
    public void Should_verify_message_sign()
    {
        var message = "Message to sign";
        var address = "0x94618601FE6cb8912b274E5a00453949A57f8C1e";
        var privateKey = "0x7580e7fb49df1c861f0050fae31c2224c6aba908e116b8da44ee8cd927b990b0";

        var signature = _manager.SignMessage(message, privateKey);
        var addressRecovered = _manager.VerifySignature(signature, message);

        Assert.Equal(addressRecovered, address);
    }

    [Fact]
    public void Shoud_return_generated_evm_address()
    {
        var keys = _manager.GenerateAddress();

        Assert.IsType<(string Key, string Secret)>(keys);
        Assert.False(string.IsNullOrEmpty(keys.Key));
        Assert.False(string.IsNullOrEmpty(keys.Secret));
    }

    [Fact]
    public void Should_return_correct_account_for_mnemo()
    {
        var mnemo = "twist enemy flame exchange summer roast beyond friend image pyramid topple need";
        var publicAddress = "0x3aBAD913A70554f416944F1a4C0EAbF3BCAFB959";
        var address = _manager.GetAddressFromMnemo(mnemo);
        Assert.NotNull(address);
        Assert.IsType<string>(address);
        Assert.Equal(publicAddress, address);
    }

    [Ignore]
    [Theory]
    [InlineData("0x0425dEAb364E9121F7CA284129dA854FD5cF22eD", Constants.Chains.Arbitrum)]
    // [InlineData("0x7002AE0Bae7fC67416230F025A32EfE086C0934E", Constants.Chains.Arbitrum)]
    public async Task Should_return_balances(string publicAddress, string chainName)
    {
        var chain = _chains.First(c => c.Name == chainName);
        var balances = await _manager.GetBalances(chain, 0, 500, publicAddress);

        Assert.IsType<List<EvmBalance>>(balances);
        Assert.NotEmpty(balances);
    }

    [Ignore]
    [Theory]
    //[InlineData("0x7002ae0bae7fc67416230f025a32efe086c0934e", Constants.Chains.Arbitrum)]
    [InlineData("0xc62F5499789b716Aa94a421A60c76c8c13A31ab6", Constants.Chains.Ethereum)]
    public async Task Should_return_all_balance(string publicAddress, string chainName)
    {
        var chain = _chains.First(c => c.Name == chainName);
        var balances = await _manager.GetAllBalances(chain, publicAddress);

        Assert.IsType<List<EvmBalance>>(balances);
        Assert.True(balances.Count > 1);
    }

    [Ignore]
    [Theory]
    [InlineData("", Constants.Chains.Arbitrum, Ticker.GMX)]
    public async void Should_return_token_balance(string publicAddress, string chainName, Ticker ticker)
    {
        var balance = await _manager.GetTokenBalance(chainName, ticker, publicAddress);

        Assert.IsType<EvmBalance>(balance);
        Assert.True(balance.Balance > 0);
    }

    [Ignore]
    [Theory]
    [InlineData("")]
    public async Task Should_return_balance_of_ethers(string publicAddress)
    {
        var chain = _chains.First(c => c.Name == Constants.Chains.Ethereum);
        var balance = await _manager.GetEtherBalance(chain, publicAddress);

        Assert.IsType<EvmBalance>(balance);
    }

    [Ignore]
    [Theory]
    [InlineData("")]
    public async Task Should_return_all_balance_for_all_chain(string publicAddress)
    {
        var balances = await _manager.GetAllBalancesOnAllChain(publicAddress);

        Assert.IsType<List<EvmBalance>>(balances);
        Assert.True(balances.Count > 0);
    }

    [Ignore]
    [Theory]
    [InlineData(Ticker.BTC, Timeframe.FiveMinutes)]
    public async Task Get_Prices(Ticker ticker, Timeframe timeframe)
    {
        var candles = await _manager.GetCandles(ticker, DateTime.UtcNow, timeframe);

        if (!candles.Any())
        {
            candles = await _manager.GetCandles(ticker, DateTime.UtcNow, timeframe);
        }

        Assert.NotNull(candles);
        Assert.True(candles.Any());
    }

    [Ignore]
    [Fact]
    public async Task Get_Available_Tickers()
    {
        var tickers = await _manager.GetAvailableTicker();

        Assert.NotEmpty(tickers);
    }

    [Ignore]
    [Fact]
    public async Task GetLastCandle()
    {
        var candle = await _manager.GetCandle(Ticker.BTC);

        Assert.NotNull(candle);
    }

    [Ignore]
    [Fact]
    public async Task Should_Init_Address_For_Trading()
    {
        var accountInitilized = await _manager.InitAddress(PublicAddress);

        Assert.NotNull(accountInitilized);
    }

    [Ignore]
    [Fact]
    public async Task Should_send_eth_from_account()
    {
        var chain = _chains.First(c => c.Name == Constants.Chains.Arbitrum);
        var balance = await _manager.GetEtherBalance(chain, PublicAddress);
        // Update receiver
        var receiverAddress = "";
        var sendResult = await _manager.Send(
            chain,
            Ticker.ETH,
            balance.Balance / 2,
            PublicAddress,
            "",
            receiverAddress);

        Assert.True(sendResult);
    }

    [Ignore]
    [Fact]
    public async Task Should_send_Gmx_from_account()
    {
        var chain = _chains.First(c => c.Name == Constants.Chains.Arbitrum);
        var receiverAddress = "";
        var balance = await _manager.GetTokenBalance(chain.Name, Ticker.GMX, PublicAddress);

        var sendResult = await _manager.Send(
            chain,
            Ticker.GMX,
            balance.Balance / 2,
            PublicAddress,
            "",
            receiverAddress);

        Assert.True(sendResult);
    }

    [Ignore]
    [Fact]
    public async Task Should_return_allowance()
    {
        var account = PrivateKeys.GetAccount();

        var allowance = await _manager.GetAllowance(account.Key, Ticker.USDC);
        Assert.IsType<decimal>(allowance);
    }

    [Ignore]
    [Fact]
    public async Task Should_set_allowance()
    {
        var account = PrivateKeys.GetAccount();

        // Get amount from balance
        var balance = await _manager.GetTokenBalance(Constants.Chains.Arbitrum, Ticker.USDC, account.Key);

        var result = await _manager.SetAllowance(account, Ticker.USDC, new BigInteger(10));
        Assert.True(result);
    }

    [Fact]
    public async Task Should_return_GmxGasPrice()
    {
        var result =
            await EvmBase.GetGasPrice(new Web3(_chains.First(c => c.Name == Constants.Chains.Arbitrum).RpcUrl));
        Assert.True(result > 0);
    }

    [Fact]
    public async Task Should_Sign_Message_Embedded_Account()
    {
        var message = "Hello eth";
        var walletId = "cm7vxs99f0007blcl8cmzv74t";
        var address = "0x932167388dD9aad41149b3cA23eBD489E2E2DD78";

        var signature = await _manager.SignMessageAsync(walletId, address, message);

        Assert.NotNull(signature);
    }

    // Helper method to create Web3ProxyService for tests
    public static IWeb3ProxyService CreateWebProxyService(string baseUrl = "http://localhost:4111")
    {
        var settings = new Web3ProxySettings { BaseUrl = baseUrl };
        var options = Options.Create(settings);
        return new Web3ProxyService(options);
    }
}