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

import "../interfaces/IYTAssetVault.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
import {AggregatorV3Interface} from "@chainlink/contracts/src/v0.8/shared/interfaces/AggregatorV3Interface.sol";

contract LendingPriceFeed is OwnableUpgradeable, UUPSUpgradeable {
    address public usdcAddress;
    AggregatorV3Interface internal usdcPriceFeed;

    error InvalidUsdcAddress();
    error InvalidUsdcPriceFeedAddress();
    error InvalidChainlinkPrice();

    /// @custom:oz-upgrades-unsafe-allow constructor
    constructor() {
        _disableInitializers();
    }

    function initialize(address _usdcAddress, address _usdcPriceFeed) external initializer {
        __UUPSUpgradeable_init();
        __Ownable_init(msg.sender);
        if (_usdcAddress == address(0)) revert InvalidUsdcAddress();
        if (_usdcPriceFeed == address(0)) revert InvalidUsdcPriceFeedAddress();
        usdcAddress = _usdcAddress;   
        usdcPriceFeed = AggregatorV3Interface(_usdcPriceFeed);
    }

    function _authorizeUpgrade(address newImplementation) internal override onlyOwner {}

    function setUsdcAddress(address _usdcAddress) external onlyOwner {
        if (_usdcAddress == address(0)) revert InvalidUsdcAddress();
        usdcAddress = _usdcAddress;
    }
    
    function getPrice(address _token) external view returns (uint256) {
        if (_token == usdcAddress) {
            return _getUSDCPrice();
        }
        return IYTAssetVault(_token).ytPrice();
    }

    function _getUSDCPrice() internal view returns (uint256) {
        (
            /* uint80 roundId */,
            int256 price,
            /* uint256 startedAt */,
            /* uint256 updatedAt */,
            /* uint80 answeredInRound */
        ) = usdcPriceFeed.latestRoundData();
        
        if (price <= 0) revert InvalidChainlinkPrice();
        
        return uint256(price) * 1e22; // 1e22 = 10^(30-8)
    }
}