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

import {CheckpointExtensionBase} from "./CheckpointExtensionBase.sol";
import {CheckpointStorage} from "../storage/CheckpointStorage.sol";
import {AccessControl} from "@openzeppelin/contracts/access/AccessControl.sol";

/// @notice On-chain registry of Chain 138 blockHash/stateRoot per height (keeper-updated).
contract BlockHeaderOracleExtension is CheckpointExtensionBase, AccessControl {
    bytes32 public constant ORACLE_UPDATER_ROLE = keccak256("ORACLE_UPDATER_ROLE");

    mapping(uint256 => bytes32) public blockHashes;
    mapping(uint256 => bytes32) public stateRoots;
    bool public requireOracleRecord;

    event BlockHeaderRecorded(uint256 indexed blockNumber, bytes32 blockHash, bytes32 stateRoot);

    constructor(address admin) {
        _grantRole(DEFAULT_ADMIN_ROLE, admin);
        _grantRole(ORACLE_UPDATER_ROLE, admin);
    }

    function setRequireOracleRecord(bool required) external onlyRole(DEFAULT_ADMIN_ROLE) {
        requireOracleRecord = required;
    }

    function setBlockHeader(uint256 blockNumber, bytes32 blockHash, bytes32 stateRoot)
        external
        onlyRole(ORACLE_UPDATER_ROLE)
    {
        require(blockHash != bytes32(0) && stateRoot != bytes32(0), "zero");
        blockHashes[blockNumber] = blockHash;
        stateRoots[blockNumber] = stateRoot;
        emit BlockHeaderRecorded(blockNumber, blockHash, stateRoot);
    }

    function HOOK_BEFORE_SUBMIT() external pure override returns (uint32) {
        return 1 << 0;
    }

    function HOOK_AFTER_SUBMIT() external pure override returns (uint32) {
        return 0;
    }

    function HOOK_ON_CCIP() external pure override returns (uint32) {
        return 0;
    }

    function beforeSubmit(CheckpointStorage.CheckpointHeader calldata header, bytes calldata) external view {
        if (!requireOracleRecord) return;
        bytes32 expectedHash = blockHashes[header.checkpointBlock];
        bytes32 expectedRoot = stateRoots[header.checkpointBlock];
        require(expectedHash != bytes32(0) && expectedRoot != bytes32(0), "oracle missing");
        require(header.blockHash == expectedHash, "blockHash");
        require(header.stateRoot == expectedRoot, "stateRoot");
    }

    function afterSubmit(CheckpointStorage.CheckpointHeader calldata, bytes calldata) external pure override {}

    function onCCIPReceive(bytes calldata) external pure override {}
}
