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

import {IAggregatorV3} from "./interfaces/IAggregatorV3.sol";
import {CWTokenMarketRegistry} from "./CWTokenMarketRegistry.sol";

/**
 * @title CWTokenUsdFeed
 * @notice Per-token Chainlink AggregatorV3-compatible USD feed backed by CWTokenMarketRegistry.
 */
contract CWTokenUsdFeed is IAggregatorV3 {
    CWTokenMarketRegistry public immutable registry;
    address public immutable token;
    string public description_;

    constructor(CWTokenMarketRegistry _registry, address _token, string memory _description) {
        require(address(_registry) != address(0) && _token != address(0), "zero arg");
        registry = _registry;
        token = _token;
        description_ = _description;
    }

    function decimals() external pure returns (uint8) {
        return 8;
    }

    function description() external view returns (string memory) {
        return description_;
    }

    function version() external pure returns (uint256) {
        return 1;
    }

    function getRoundData(uint80 _roundId)
        external
        view
        returns (
            uint80 roundId,
            int256 answer,
            uint256 startedAt,
            uint256 updatedAt,
            uint80 answeredInRound
        )
    {
        (roundId, answer, startedAt, updatedAt, answeredInRound) = latestRoundData();
        if (_roundId != 0) {
            require(roundId == _roundId, "stale round");
        }
    }

    function latestRoundData()
        public
        view
        returns (
            uint80 roundId,
            int256 answer,
            uint256 startedAt,
            uint256 updatedAt,
            uint80 answeredInRound
        )
    {
        (roundId, answer, updatedAt) = registry.latestRoundDataForToken(token);
        startedAt = updatedAt;
        answeredInRound = roundId;
    }
}
