contract StakingLPRewardFixedAPY is IStakingRewards, ReentrancyGuard, Ownable {
    using SafeERC20 for IERC20;

    IERC20 public immutable rewardsToken;
    INimbusPair public immutable stakingLPToken;
    INimbusRouter public swapRouter;
    address public immutable lPPairTokenA;
    address public immutable lPPairTokenB;
    uint256 public rewardRate; 
    uint256 public constant rewardDuration = 365 days; 

    mapping(address => uint256) public weightedStakeDate;
    mapping(address => mapping(uint256 => uint256)) public stakeAmounts;
    mapping(address => mapping(uint256 => uint256)) public stakeAmountsRewardEquivalent;
    mapping(address => uint256) public stakeNonces;

    uint256 private _totalSupply;
    uint256 private _totalSupplyRewardEquivalent;
    uint256 private immutable _tokenADecimalCompensate;
    uint256 private immutable _tokenBDecimalCompensate;
    mapping(address => uint256) private _balances;
    mapping(address => uint256) private _balancesRewardEquivalent;

    event RewardUpdated(uint256 reward);
    event Staked(address indexed user, uint256 amount);
    event Withdrawn(address indexed user, uint256 amount);
    event RewardPaid(address indexed user, uint256 reward);
    event Rescue(address indexed to, uint256 amount);
    event RescueToken(address indexed to, address indexed token, uint256 amount);

    constructor(
        address _rewardsToken,
        address _stakingLPToken,
        address _lPPairTokenA,
        address _lPPairTokenB,
        address _swapRouter,
        uint _rewardRate
    ) {
        rewardsToken = IERC20(_rewardsToken);
        stakingLPToken = INimbusPair(_stakingLPToken);
        swapRouter = INimbusRouter(_swapRouter);
        rewardRate = _rewardRate;
        lPPairTokenA = _lPPairTokenA;
        lPPairTokenB = _lPPairTokenB;
        uint tokenADecimals = IERC20(_lPPairTokenA).decimals();
        require(tokenADecimals >= 6, "StakingLPRewardFixedAPY: small amount of decimals");
        _tokenADecimalCompensate = tokenADecimals - 6;
        uint tokenBDecimals = IERC20(_lPPairTokenB).decimals();
        require(tokenBDecimals >= 6, "StakingLPRewardFixedAPY: small amount of decimals");
        _tokenBDecimalCompensate = tokenBDecimals - 6;
    }

    function totalSupply() external view override returns (uint256) {
        return _totalSupply;
    }

    function totalSupplyRewardEquivalent() external view returns (uint256) {
        return _totalSupplyRewardEquivalent;
    }

    function getDecimalPriceCalculationCompensate() external view returns (uint tokenADecimalCompensate, uint tokenBDecimalCompensate) { 
        tokenADecimalCompensate = _tokenADecimalCompensate;
        tokenBDecimalCompensate = _tokenBDecimalCompensate;
    }

    function balanceOf(address account) external view override returns (uint256) {
        return _balances[account];
    }
    
    function balanceOfRewardEquivalent(address account) external view returns (uint256) {
        return _balancesRewardEquivalent[account];
    }

    function earned(address account) public view override returns (uint256) {
        return (_balancesRewardEquivalent[account] * ((block.timestamp - weightedStakeDate[account]) * rewardRate)) / (100 * rewardDuration);
    }

    function stakeWithPermit(uint256 amount, uint deadline, uint8 v, bytes32 r, bytes32 s) external nonReentrant {
        require(amount > 0, "StakingLPRewardFixedAPY: Cannot stake 0");
        // permit
        IERC20Permit(address(stakingLPToken)).permit(msg.sender, address(this), amount, deadline, v, r, s);
        _stake(amount, msg.sender);
    }

    function stake(uint256 amount) external override nonReentrant {
        require(amount > 0, "StakingLPRewardFixedAPY: Cannot stake 0");
        _stake(amount, msg.sender);
    }

    function stakeFor(uint256 amount, address user) external override nonReentrant {
        require(amount > 0, "StakingLPRewardFixedAPY: Cannot stake 0");
        require(user != address(0), "StakingLPRewardFixedAPY: Cannot stake for zero address");
        _stake(amount, user);
    }

    function _stake(uint256 amount, address user) private {
        IERC20(stakingLPToken).safeTransferFrom(msg.sender, address(this), amount);
        uint amountRewardEquivalent = getCurrentLPPrice() * amount / 1e18;

        _totalSupply += amount;
        _totalSupplyRewardEquivalent += amountRewardEquivalent;
        uint previousAmount = _balances[user];
        uint newAmount = previousAmount + amount;
        weightedStakeDate[user] = (weightedStakeDate[user] * previousAmount / newAmount) + (block.timestamp * amount / newAmount);
        _balances[user] = newAmount;

        uint stakeNonce = stakeNonces[user]++;
        stakeAmounts[user][stakeNonce] = amount;
        
        stakeAmountsRewardEquivalent[user][stakeNonce] = amountRewardEquivalent;
        _balancesRewardEquivalent[user] += amountRewardEquivalent;
        emit Staked(user, amount);
    }


    //A user can withdraw its staking tokens even if there is no rewards tokens on the contract account
    function withdraw(uint256 nonce) public override nonReentrant {
        require(stakeAmounts[msg.sender][nonce] > 0, "StakingLPRewardFixedAPY: This stake nonce was withdrawn");
        uint amount = stakeAmounts[msg.sender][nonce];
        uint amountRewardEquivalent = stakeAmountsRewardEquivalent[msg.sender][nonce];
        _totalSupply -= amount;
        _totalSupplyRewardEquivalent -= amountRewardEquivalent;
        _balances[msg.sender] -= amount;
        _balancesRewardEquivalent[msg.sender] -= amountRewardEquivalent;
        IERC20(stakingLPToken).safeTransfer(msg.sender, amount);
        stakeAmounts[msg.sender][nonce] = 0;
        stakeAmountsRewardEquivalent[msg.sender][nonce] = 0;
        emit Withdrawn(msg.sender, amount);
    }

    function getReward() public override nonReentrant {
        uint256 reward = earned(msg.sender);
        if (reward > 0) {
            weightedStakeDate[msg.sender] = block.timestamp;
            rewardsToken.safeTransfer(msg.sender, reward);
            emit RewardPaid(msg.sender, reward);
        }
    }

    function withdrawAndGetReward(uint256 nonce) external override {
        getReward();
        withdraw(nonce);
    }

    function getCurrentLPPrice() public view returns (uint) {
        // LP PRICE = 2 * SQRT(reserveA * reaserveB ) * SQRT(token1/RewardTokenPrice * token2/RewardTokenPrice) / LPTotalSupply
        uint tokenAToRewardPrice;
        uint tokenBToRewardPrice;
        address rewardToken = address(rewardsToken);    
        address[] memory path = new address[](2);
        path[1] = address(rewardToken);

        if (lPPairTokenA != rewardToken) {
            path[0] = lPPairTokenA;
            tokenAToRewardPrice = swapRouter.getAmountsOut(10 ** 6, path)[1];
            if (_tokenADecimalCompensate > 0) 
                tokenAToRewardPrice = tokenAToRewardPrice * (10 ** _tokenADecimalCompensate);
        } else {
            tokenAToRewardPrice = 1e18;
        }
        
        if (lPPairTokenB != rewardToken) {
            path[0] = lPPairTokenB;
            tokenBToRewardPrice = swapRouter.getAmountsOut(10 ** 6, path)[1];
            if (_tokenBDecimalCompensate > 0)
                tokenBToRewardPrice = tokenBToRewardPrice * (10 ** _tokenBDecimalCompensate);
        } else {
            tokenBToRewardPrice = 1e18;
        }

        uint totalLpSupply = IERC20(stakingLPToken).totalSupply();
        require(totalLpSupply > 0, "StakingLPRewardFixedAPY: No liquidity for pair");
        (uint reserveA, uint reaserveB,) = stakingLPToken.getReserves();
        uint price = 
            uint(2) * Math.sqrt(reserveA * reaserveB)
            * Math.sqrt(tokenAToRewardPrice * tokenBToRewardPrice) / totalLpSupply;
        
        return price;
    }


    function updateRewardAmount(uint256 reward) external onlyOwner {
        rewardRate = reward;
        emit RewardUpdated(reward);
    }

    function updateSwapRouter(address newSwapRouter) external onlyOwner {
        require(newSwapRouter != address(0), "StakingLPRewardFixedAPY: Address is zero");
        swapRouter = INimbusRouter(newSwapRouter);
    }

    function rescue(address to, IERC20 token, uint256 amount) external onlyOwner {
        require(to != address(0), "StakingLPRewardFixedAPY: Cannot rescue to the zero address");
        require(amount > 0, "StakingLPRewardFixedAPY: Cannot rescue 0");
        require(token != stakingLPToken, "StakingLPRewardFixedAPY: Cannot rescue staking token");
        //owner can rescue rewardsToken if there is spare unused tokens on staking contract balance

        token.safeTransfer(to, amount);
        emit RescueToken(to, address(token), amount);
    }

    function rescue(address payable to, uint256 amount) external onlyOwner {
        require(to != address(0), "StakingLPRewardFixedAPY: Cannot rescue to the zero address");
        require(amount > 0, "StakingLPRewardFixedAPY: Cannot rescue 0");

        to.transfer(amount);
        emit Rescue(to, amount);
    }
}
function withdraw(uint256 nonce) public override nonReentrant {
    require(stakeAmounts[msg.sender][nonce] > 0, "StakingLPRewardFixedAPY: This stake nonce was withdrawn");
    uint amount = stakeAmounts[msg.sender][nonce];
    uint amountRewardEquivalent = stakeAmountsRewardEquivalent[msg.sender][nonce];
    _totalSupply -= amount;
    _totalSupplyRewardEquivalent -= amountRewardEquivalent;
    _balances[msg.sender] -= amount;
    _balancesRewardEquivalent[msg.sender] -= amountRewardEquivalent;
    IERC20(stakingLPToken).safeTransfer(msg.sender, amount);
    stakeAmounts[msg.sender][nonce] = 0;
    stakeAmountsRewardEquivalent[msg.sender][nonce] = 0;
    emit Withdrawn(msg.sender, amount);
}

//A user can withdraw its staking tokens even if there is no rewards tokens on the contract account