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

import "@openzeppelin/contracts/access/AccessControl.sol";
import "../RWAStorage.sol";
import "../interfaces/IRWAInstrumentFacet.sol";

/**
 * @title RWAInstrumentFacet
 * @notice Issuance mode + ISIN/CUSIP identity hashes + pointer to external ERC-20 (tokenization).
 * @dev Private closed-loop: ISIN/CUSIP are internal accounting anchors (hashed on-chain; full strings in IPFS/Filecoin).
 */
contract RWAInstrumentFacet is AccessControl, IRWAInstrumentFacet {
    bytes32 public constant INSTRUMENT_ADMIN_ROLE = keccak256("INSTRUMENT_ADMIN_ROLE");

    constructor(address admin) {
        _grantRole(DEFAULT_ADMIN_ROLE, admin);
        _grantRole(INSTRUMENT_ADMIN_ROLE, admin);
        RWAStorage.layout().governance = admin;
    }

    function setIssuanceMode(bytes32 assetId, RWAStorage.IssuanceMode mode) external onlyRole(INSTRUMENT_ADMIN_ROLE) {
        require(mode != RWAStorage.IssuanceMode.Unset, "RWAInstrument: mode");
        RWAStorage.Layout storage l = RWAStorage.layout();
        l.assets[assetId].issuanceMode = mode;
        emit IssuanceModeSet(assetId, mode);
    }

    function setInstrumentIdentity(
        bytes32 assetId,
        bytes32 isinHash,
        bytes32 cusipHash,
        bytes32 issuerLeiHash,
        bytes32 underlyingIsinHash
    ) external onlyRole(INSTRUMENT_ADMIN_ROLE) {
        RWAStorage.InstrumentIdentity storage id = RWAStorage.layout().assets[assetId].identity;
        id.isinHash = isinHash;
        id.cusipHash = cusipHash;
        id.issuerLeiHash = issuerLeiHash;
        id.underlyingIsinHash = underlyingIsinHash;
        emit InstrumentIdentitySet(assetId, isinHash, cusipHash, issuerLeiHash);
    }

    function setTokenPointer(bytes32 assetId, address token) external onlyRole(INSTRUMENT_ADMIN_ROLE) {
        require(token != address(0), "RWAInstrument: token");
        RWAStorage.layout().assets[assetId].tokenPointer = token;
        emit TokenPointerSet(assetId, token);
    }

    function getIssuanceMode(bytes32 assetId) external view returns (RWAStorage.IssuanceMode) {
        return RWAStorage.layout().assets[assetId].issuanceMode;
    }

    function getTokenPointer(bytes32 assetId) external view returns (address) {
        return RWAStorage.layout().assets[assetId].tokenPointer;
    }
}
