// File: src/LynxStaking.sol



//SPDX-License-Identifier: MIT
pragma solidity 0.8.21;

import "./interfaces/ILynxStaking.sol";
import "./interfaces/ILynxVault.sol";
import "openzeppelin/token/ERC20/IERC20.sol";
import "openzeppelin/security/ReentrancyGuard.sol";

error LYNXStaking__InvalidDepositAmount();
error LYNXStaking__InvalidAprSelected();
error LYNXStaking__WithdrawLocked(uint lockEndTime);

contract LynxStaking is ILynxStaking, ReentrancyGuard {
    //--------------------------------------------------------------------
    // State Variables
    //--------------------------------------------------------------------
    mapping(address => Stake) public stake;
    uint256 private immutable apr;
    uint256 private immutable dur;
    AprConfig public aprConfig;

    address[] public stakers;
    IERC20 public lynx;
    ILynxVault public vault;
    uint256 public totalStaked;
    uint256 public totalClaimed;
    uint256 public constant REWARD_APR_BASE = 100_00; // 100.00%
    uint256 public immutable LockStart;

    //--------------------------------------------------------------------
    // Construtor
    //--------------------------------------------------------------------
    /**
     * @notice Constructor to set up the contract
     * @param weekStart - timestamp of when the weeks start
     * @param _lynx - address of lynx token.
     * @param _vault - address of vault that holds lynx to send/withdraw funds from
     * @param _apr - the expected APR to give back to users.
     * @param time_lock - the amount of weeks to lock tokens for
     */
    constructor(
        uint weekStart,
        address _lynx,
        address _vault,
        uint _apr,
        uint256 time_lock
    ) {
        time_lock = time_lock * 1 weeks;
        LockStart = weekStart;
        apr = _apr;
        dur = time_lock;
        aprConfig = AprConfig(true, _apr, time_lock);
        lynx = IERC20(_lynx);
        vault = ILynxVault(_vault);
    }

    //--------------------------------------------------------------------
    // External / Public Functions
    //--------------------------------------------------------------------
    function deposit(uint amount) external nonReentrant {
        if (amount == 0) revert LYNXStaking__InvalidDepositAmount();
        Stake storage currentStake = stake[msg.sender];
        uint256 duration = dur;

        if (currentStake.set) {
            uint reward = currentRewards(msg.sender);
            // IF reward time is over, claim rewards and reset the user
            if (currentStake.rewardEnd < block.timestamp) {
                // claim rewards
                totalClaimed += reward + currentStake.lockedRewards;
                currentStake.lockedRewards = 0;
                vault.withdrawTo(msg.sender, reward);
                emit ClaimRewards(msg.sender, reward);
            }
            // ELSE
            else {
                // lock rewards accrued so far and add the new deposit to the existing one
                currentStake.lockedRewards += reward;
                emit LockedRewards(msg.sender, reward);
            }
            currentStake.depositAmount += amount;
        } else {
            currentStake.depositAmount = amount;
            currentStake.posIndex = stakers.length;
            currentStake.set = true;
            stakers.push(msg.sender);
        }
        totalStaked += amount;
        currentStake.startStake = block.timestamp;
        currentStake.rewardEnd = calculateEndTime(duration);
        // Transfer Deposit amounts to Vault
        lynx.transferFrom(msg.sender, address(vault), amount);
        emit Deposit(msg.sender, amount, duration, currentStake.rewardEnd);
    }

    function withdraw() external nonReentrant {
        Stake storage currentStake = stake[msg.sender];
        if (block.timestamp < currentStake.rewardEnd)
            revert LYNXStaking__WithdrawLocked(currentStake.rewardEnd);

        // Claim rewards
        uint reward = currentRewards(msg.sender);
        reward += currentStake.lockedRewards;
        emit ClaimRewards(msg.sender, reward);
        reward += currentStake.depositAmount;
        emit Withdraw(msg.sender, currentStake.depositAmount);
        // remove user from stake list
        address lastIdxUser = stakers[stakers.length - 1];
        stakers[currentStake.posIndex] = lastIdxUser;
        stake[lastIdxUser].posIndex = currentStake.posIndex;
        stakers.pop();
        totalStaked -= currentStake.depositAmount;
        // reset the user
        stake[msg.sender] = Stake(0, 0, 0, 0, 0, false);
        vault.withdrawTo(msg.sender, reward);
    }

    function currentRewards(address user) public view returns (uint256) {
        Stake storage currentStake = stake[user];

        if (currentStake.depositAmount == 0 || !currentStake.set) return 0;

        uint256 rewardEnd = currentStake.rewardEnd;
        uint256 rewardAmount = 0;

        if (block.timestamp > rewardEnd) {
            rewardAmount = rewardEnd - currentStake.startStake;
        } else {
            rewardAmount = block.timestamp - currentStake.startStake;
        }

        rewardAmount =
            (currentStake.depositAmount * rewardAmount * apr) /
            (REWARD_APR_BASE * 365 days);

        return rewardAmount;
    }

    function calculateEndTime(uint256 duration) public view returns (uint256) {
        uint currentWeek = (block.timestamp - LockStart) / 1 weeks;
        return LockStart + (currentWeek * 1 weeks) + duration + 1 weeks;
    }

    function getStakers()
        external
        view
        returns (address[] memory users, uint256[] memory balances)
    {
        users = new address[](stakers.length);
        balances = new uint256[](stakers.length);
        for (uint i = 0; i < stakers.length; i++) {
            users[i] = stakers[i];
            balances[i] = stake[stakers[i]].depositAmount;
        }
    }
}

// File: src/interfaces/ILynxStaking.sol



//SPDX-License-Identifier: MIT
pragma solidity 0.8.21;

interface ILynxStaking {
    struct Stake {
        uint256 depositAmount;
        uint256 startStake;
        uint256 rewardEnd;
        uint256 posIndex;
        uint256 lockedRewards;
        bool set;
    }

    struct AprConfig {
        bool setup; // This is a flag to indicate if the APR has been set up
        uint256 apr; // This is the APR for the staking - this has to be in the format XX_00 since there are 2 decimals in the APR value;
        uint256 duration; // This is the duration in weeks of when the staking should end
    }

    /**
     * Deposit tokens in the Staking pool and start earning rewards while the tokens are locked.
     * @param amount The amount of LYNX to deposit
     * @dev if the user is already staked in, claim the current rewards and add the new deposit to the existing one, then relock the tokens for duration.
     */
    function deposit(uint amount) external;

    /**
     * Withdraw tokens from the Staking pool along with the rewards earned.
     */
    function withdraw() external;

    /**
     * Gives the current reward amount for the user.
     * @param user The address of the user to check
     * @return The amount of LYNX the user has been rewarded with
     * @dev If the user is staked for longer than the lock amount, no additional rewards are given.
     */
    function currentRewards(address user) external view returns (uint256);

    event Deposit(
        address indexed user,
        uint256 amount,
        uint256 duration,
        uint256 rewardEnd
    );

    event ClaimRewards(address indexed user, uint256 amount);
    event LockedRewards(address indexed user, uint256 amount);
    event Withdraw(address indexed user, uint256 amount);
}

// File: src/interfaces/ILynxVault.sol



//SPDX-License-Identifier: MIT
pragma solidity 0.8.21;

interface ILynxVault {
    function withdraw(uint amount) external;

    function withdrawTo(address _address, uint amount) external;
}

// File: lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/IERC20.sol)

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC20 standard as defined in the EIP.
 */
interface IERC20 {
    /**
     * @dev Emitted when `value` tokens are moved from one account (`from`) to
     * another (`to`).
     *
     * Note that `value` may be zero.
     */
    event Transfer(address indexed from, address indexed to, uint256 value);

    /**
     * @dev Emitted when the allowance of a `spender` for an `owner` is set by
     * a call to {approve}. `value` is the new allowance.
     */
    event Approval(address indexed owner, address indexed spender, uint256 value);

    /**
     * @dev Returns the amount of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

    /**
     * @dev Returns the amount of tokens owned by `account`.
     */
    function balanceOf(address account) external view returns (uint256);

    /**
     * @dev Moves `amount` tokens from the caller's account to `to`.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transfer(address to, uint256 amount) external returns (bool);

    /**
     * @dev Returns the remaining number of tokens that `spender` will be
     * allowed to spend on behalf of `owner` through {transferFrom}. This is
     * zero by default.
     *
     * This value changes when {approve} or {transferFrom} are called.
     */
    function allowance(address owner, address spender) external view returns (uint256);

    /**
     * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * IMPORTANT: Beware that changing an allowance with this method brings the risk
     * that someone may use both the old and the new allowance by unfortunate
     * transaction ordering. One possible solution to mitigate this race
     * condition is to first reduce the spender's allowance to 0 and set the
     * desired value afterwards:
     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
     *
     * Emits an {Approval} event.
     */
    function approve(address spender, uint256 amount) external returns (bool);

    /**
     * @dev Moves `amount` tokens from `from` to `to` using the
     * allowance mechanism. `amount` is then deducted from the caller's
     * allowance.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(address from, address to, uint256 amount) external returns (bool);
}

// File: lib/openzeppelin-contracts/contracts/security/ReentrancyGuard.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (security/ReentrancyGuard.sol)

pragma solidity ^0.8.0;

/**
 * @dev Contract module that helps prevent reentrant calls to a function.
 *
 * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
 * available, which can be applied to functions to make sure there are no nested
 * (reentrant) calls to them.
 *
 * Note that because there is a single `nonReentrant` guard, functions marked as
 * `nonReentrant` may not call one another. This can be worked around by making
 * those functions `private`, and then adding `external` `nonReentrant` entry
 * points to them.
 *
 * TIP: If you would like to learn more about reentrancy and alternative ways
 * to protect against it, check out our blog post
 * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
 */
abstract contract ReentrancyGuard {
    // Booleans are more expensive than uint256 or any type that takes up a full
    // word because each write operation emits an extra SLOAD to first read the
    // slot's contents, replace the bits taken up by the boolean, and then write
    // back. This is the compiler's defense against contract upgrades and
    // pointer aliasing, and it cannot be disabled.

    // The values being non-zero value makes deployment a bit more expensive,
    // but in exchange the refund on every call to nonReentrant will be lower in
    // amount. Since refunds are capped to a percentage of the total
    // transaction's gas, it is best to keep them low in cases like this one, to
    // increase the likelihood of the full refund coming into effect.
    uint256 private constant _NOT_ENTERED = 1;
    uint256 private constant _ENTERED = 2;

    uint256 private _status;

    constructor() {
        _status = _NOT_ENTERED;
    }

    /**
     * @dev Prevents a contract from calling itself, directly or indirectly.
     * Calling a `nonReentrant` function from another `nonReentrant`
     * function is not supported. It is possible to prevent this from happening
     * by making the `nonReentrant` function external, and making it call a
     * `private` function that does the actual work.
     */
    modifier nonReentrant() {
        _nonReentrantBefore();
        _;
        _nonReentrantAfter();
    }

    function _nonReentrantBefore() private {
        // On the first call to nonReentrant, _status will be _NOT_ENTERED
        require(_status != _ENTERED, "ReentrancyGuard: reentrant call");

        // Any calls to nonReentrant after this point will fail
        _status = _ENTERED;
    }

    function _nonReentrantAfter() private {
        // By storing the original value once again, a refund is triggered (see
        // https://eips.ethereum.org/EIPS/eip-2200)
        _status = _NOT_ENTERED;
    }

    /**
     * @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
     * `nonReentrant` function in the call stack.
     */
    function _reentrancyGuardEntered() internal view returns (bool) {
        return _status == _ENTERED;
    }
}