// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;

import {Test, console} from "forge-std/Test.sol";
import "../../../contracts/bridge/trustless/BondManager.sol";
import "../../../contracts/bridge/trustless/ChallengeManager.sol";
import "../../../contracts/bridge/trustless/InboxETH.sol";
import "../../../contracts/bridge/trustless/LiquidityPoolETH.sol";
import "../../../contracts/bridge/trustless/EnhancedSwapRouter.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";

contract MockERC20 is ERC20 {
    constructor(string memory name, string memory symbol) ERC20(name, symbol) {
        _mint(msg.sender, 1000000 ether);
    }
}

/**
 * @title StressTests
 * @notice Tests system under extreme load conditions
 */
contract StressTests is Test {
    BondManager public bondManager;
    ChallengeManager public challengeManager;
    LiquidityPoolETH public liquidityPool;
    InboxETH public inbox;
    EnhancedSwapRouter public swapRouter;
    
    MockERC20 public weth;
    MockERC20 public usdt;
    MockERC20 public usdc;
    MockERC20 public dai;

    address public deployer = address(0xDE0001);
    address public relayer = address(0x1111);
    address public lp = address(0x2222);

    uint256 public constant BOND_MULTIPLIER = 11000; // 110% in basis points
    uint256 public constant MIN_BOND = 1 ether;
    uint256 public constant CHALLENGE_WINDOW = 30 minutes;

    // Mock protocol addresses
    address public uniswapV3Router = address(0x1111111111111111111111111111111111111111);
    address public curve3Pool = address(0x2222222222222222222222222222222222222222);
    address public dodoexRouter = address(0x3333333333333333333333333333333333333333);
    address public balancerVault = address(0x4444444444444444444444444444444444444444);
    address public oneInchRouter = address(0x5555555555555555555555555555555555555555);

    function setUp() public {
        vm.startPrank(deployer);

        weth = new MockERC20("Wrapped Ether", "WETH");
        usdt = new MockERC20("Tether USD", "USDT");
        usdc = new MockERC20("USD Coin", "USDC");
        dai = new MockERC20("Dai Stablecoin", "DAI");

        bondManager = new BondManager(BOND_MULTIPLIER, MIN_BOND);
        challengeManager = new ChallengeManager(address(bondManager), CHALLENGE_WINDOW);
        liquidityPool = new LiquidityPoolETH(address(weth), 5, 11000);
        inbox = new InboxETH(address(bondManager), address(challengeManager), address(liquidityPool));
        
        swapRouter = new EnhancedSwapRouter(
            uniswapV3Router,
            curve3Pool,
            dodoexRouter,
            balancerVault,
            oneInchRouter,
            address(weth),
            address(usdt),
            address(usdc),
            address(dai)
        );

        liquidityPool.authorizeRelease(address(inbox));
        swapRouter.grantRole(swapRouter.ROUTING_MANAGER_ROLE(), deployer);

        // Fund with large amounts for stress tests
        vm.deal(relayer, 100000 ether);
        vm.deal(lp, 1000000 ether);
        vm.warp(1000);

        // Provide substantial liquidity
        vm.stopPrank();
        vm.prank(lp);
        liquidityPool.provideLiquidity{value: 10000 ether}(LiquidityPoolETH.AssetType.ETH);
    }

    /// @notice Stress test: Submit 100 concurrent claims
    function testStress_100ConcurrentClaims() public {
        uint256 numClaims = 100;
        uint256 amount = 1 ether;
        uint256 bond = bondManager.getRequiredBond(amount);
        
        uint256 gasStart = gasleft();
        
        for (uint256 i = 1; i <= numClaims; i++) {
            vm.warp(1000 + (i - 1) * 61); // 60s cooldown between claims
            vm.prank(relayer);
            inbox.submitClaim{value: bond}(i, address(0), amount, address(0x3333), "");
        }
        
        uint256 gasUsed = gasStart - gasleft();
        uint256 avgGasPerClaim = gasUsed / numClaims;
        
        console.log("Total gas for", numClaims, "claims:", gasUsed);
        console.log("Average gas per claim:", avgGasPerClaim);
        
        // Verify all bonds were posted
        for (uint256 i = 1; i <= numClaims; i++) {
            (, uint256 bondAmount, , , ) = bondManager.bonds(i);
            assertGe(bondAmount, MIN_BOND, "Bond should be posted");
        }
        
        // Average should be reasonable even under load
        assertLt(avgGasPerClaim, 500000, "Average gas per claim should be reasonable");
    }

    /// @notice Stress test: Batch release 50 bonds
    function testStress_BatchRelease50Bonds() public {
        uint256 numBonds = 50;
        uint256 amount = 1 ether;
        uint256 bond = bondManager.getRequiredBond(amount);
        
        // Submit claims (warp between to avoid 60s cooldown)
        for (uint256 i = 1; i <= numBonds; i++) {
            vm.warp(1000 + (i - 1) * 61);
            vm.prank(relayer);
            inbox.submitClaim{value: bond}(i, address(0), amount, address(0x3333), "");
        }
        
        // Wait for challenge window
        vm.warp(block.timestamp + CHALLENGE_WINDOW + 1);
        
        // Finalize all
        for (uint256 i = 1; i <= numBonds; i++) {
            challengeManager.finalizeClaim(i);
        }
        
        // Prepare batch array
        uint256[] memory depositIds = new uint256[](numBonds);
        for (uint256 i = 0; i < numBonds; i++) {
            depositIds[i] = i + 1;
        }
        
        uint256 gasStart = gasleft();
        
        bondManager.releaseBondsBatch(depositIds);
        
        uint256 gasUsed = gasStart - gasleft();
        uint256 avgGasPerRelease = gasUsed / numBonds;
        
        console.log("Total gas for batch release of", numBonds, "bonds:", gasUsed);
        console.log("Average gas per release:", avgGasPerRelease);
        
        // Verify all bonds were released
        for (uint256 i = 1; i <= numBonds; i++) {
            (, , , , bool released) = bondManager.bonds(i);
            assertTrue(released, "Bond should be released");
        }
        
        // Batch should be efficient
        assertLt(avgGasPerRelease, 100000, "Average gas per batch release should be efficient");
    }

    /// @notice Stress test: Rapid provider toggling
    function testStress_RapidProviderToggle() public {
        uint256 numToggles = 100;
        
        uint256 gasStart = gasleft();
        
        for (uint256 i = 0; i < numToggles; i++) {
            EnhancedSwapRouter.SwapProvider provider = EnhancedSwapRouter.SwapProvider(i % 5);
            bool enabled = (i % 2 == 0);
            
            vm.prank(deployer);
            swapRouter.setProviderEnabled(provider, enabled);
        }
        
        uint256 gasUsed = gasStart - gasleft();
        uint256 avgGasPerToggle = gasUsed / numToggles;
        
        console.log("Total gas for", numToggles, "toggles:", gasUsed);
        console.log("Average gas per toggle:", avgGasPerToggle);
        
        // Should be very efficient
        assertLt(avgGasPerToggle, 100000, "Provider toggle should be efficient");
    }

    /// @notice Stress test: Multiple routing config updates
    function testStress_MultipleRoutingConfigs() public {
        uint256 numConfigs = 20;
        
        EnhancedSwapRouter.SwapProvider[] memory providers = new EnhancedSwapRouter.SwapProvider[](3);
        providers[0] = EnhancedSwapRouter.SwapProvider.Dodoex;
        providers[1] = EnhancedSwapRouter.SwapProvider.Balancer;
        providers[2] = EnhancedSwapRouter.SwapProvider.UniswapV3;
        
        uint256 gasStart = gasleft();
        
        for (uint256 i = 0; i < numConfigs; i++) {
            uint256 category = i % 3; // Cycle through small/medium/large
            
            vm.prank(deployer);
            swapRouter.setRoutingConfig(category, providers);
        }
        
        uint256 gasUsed = gasStart - gasleft();
        uint256 avgGasPerConfig = gasUsed / numConfigs;
        
        console.log("Total gas for", numConfigs, "config updates:", gasUsed);
        console.log("Average gas per config:", avgGasPerConfig);
        
        // Should be efficient
        assertLt(avgGasPerConfig, 150000, "Routing config update should be efficient");
    }

    /// @notice Stress test: High-frequency quote requests
    function testStress_HighFrequencyQuotes() public view {
        uint256 numQuotes = 1000;
        uint256 amount = 1 ether;
        
        uint256 gasStart = gasleft();
        
        for (uint256 i = 0; i < numQuotes; i++) {
            swapRouter.getQuotes(address(usdt), amount);
        }
        
        uint256 gasUsed = gasStart - gasleft();
        uint256 avgGasPerQuote = gasUsed / numQuotes;
        
        console.log("Total gas for", numQuotes, "quotes:", gasUsed);
        console.log("Average gas per quote:", avgGasPerQuote);
        
        // View functions should be very cheap
        assertLt(avgGasPerQuote, 50000, "Quote requests should be very cheap");
    }

    /// @notice Stress test: Large bond amounts
    function testStress_LargeBondAmounts() public {
        uint256[] memory largeAmounts = new uint256[](10);
        largeAmounts[0] = 1000 ether;
        largeAmounts[1] = 5000 ether;
        largeAmounts[2] = 10000 ether;
        largeAmounts[3] = 50000 ether;
        largeAmounts[4] = 100000 ether;
        largeAmounts[5] = 500000 ether;
        largeAmounts[6] = 1000000 ether;
        largeAmounts[7] = 5000000 ether;
        largeAmounts[8] = 10000000 ether;
        largeAmounts[9] = 50000000 ether;
        
        for (uint256 i = 0; i < largeAmounts.length; i++) {
            uint256 amount = largeAmounts[i];
            uint256 bond = bondManager.getRequiredBond(amount);
            
            console.log("Amount (ETH):", amount / 1e18);
            console.log("Bond (ETH):", bond / 1e18);
            
            // Bond should always be >= MIN_BOND
            assertGe(bond, MIN_BOND, "Bond should be at least MIN_BOND");
            
            // Bond should scale with amount
            if (amount > 0) {
                uint256 minExpected = (amount * BOND_MULTIPLIER) / 10000;
                assertGe(bond, minExpected, "Bond should respect multiplier");
            }
        }
    }

    /// @notice Stress test: System under maximum load
    function testStress_MaximumLoad() public {
        // Submit maximum number of claims
        uint256 maxClaims = 200;
        uint256 amount = 1 ether;
        uint256 bond = bondManager.getRequiredBond(amount);
        
        console.log("Submitting", maxClaims, "claims...");
        
        uint256 successCount = 0;
        for (uint256 i = 1; i <= maxClaims; i++) {
            vm.warp(1000 + (i - 1) * 61); // 60s cooldown between claims
            vm.prank(relayer);
            try inbox.submitClaim{value: bond}(i, address(0), amount, address(0x3333), "") {
                successCount++;
            } catch {
                // Some failures are acceptable under extreme load
            }
        }
        
        console.log("Successfully submitted", successCount, "claims out of", maxClaims);
        
        // System should handle at least 90% of requests
        assertGe(successCount, (maxClaims * 90) / 100, "System should handle most requests");
    }
}

