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

import {CheckpointLeaf} from "./CheckpointLeaf.sol";
import {CheckpointErrors} from "./CheckpointErrors.sol";

/// @notice External library to keep hub implementation under 24KB (EIP-170).
library CheckpointPaymentsLib {
    function assertPaymentsRootV1(
        uint64 chainId,
        bytes32 paymentsRoot,
        CheckpointLeaf.PaymentLeafV1[] calldata leaves
    ) external pure {
        if (leaves.length == 0) revert CheckpointErrors.LeavesEmpty();
        bytes32[] memory hashes = new bytes32[](leaves.length);
        for (uint256 i = 0; i < leaves.length; i++) {
            hashes[i] = CheckpointLeaf.paymentLeafV1(chainId, leaves[i]);
        }
        if (CheckpointLeaf.buildMerkleRoot(hashes) != paymentsRoot) revert CheckpointErrors.RootMismatch();
    }

    function assertPaymentsRootV2(
        uint64 chainId,
        bytes32 paymentsRoot,
        CheckpointLeaf.PaymentLeafV2[] calldata leaves
    ) external pure {
        if (leaves.length == 0) revert CheckpointErrors.LeavesEmpty();
        bytes32[] memory hashes = new bytes32[](leaves.length);
        for (uint256 i = 0; i < leaves.length; i++) {
            hashes[i] = CheckpointLeaf.paymentLeafV2(chainId, leaves[i]);
        }
        if (CheckpointLeaf.buildMerkleRoot(hashes) != paymentsRoot) revert CheckpointErrors.RootMismatch();
    }

    function enforceMinPaymentValueV1(bytes calldata extensionData, uint256 minWei) external pure {
        if (minWei == 0 || extensionData.length == 0) return;
        CheckpointLeaf.PaymentLeafV1[] memory leaves = abi.decode(extensionData, (CheckpointLeaf.PaymentLeafV1[]));
        for (uint256 i = 0; i < leaves.length; i++) {
            if (leaves[i].value < minWei) revert CheckpointErrors.BelowMinPayment();
        }
    }
}
