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

import {Script, console2} from "forge-std/Script.sol";
import {RegulatedEntityRegistry} from "../../../contracts/vault/RegulatedEntityRegistry.sol";
import {GRUEntityIbanRegistry} from "../../../contracts/vault/GRUEntityIbanRegistry.sol";

/// @notice Register OMNL/DBIS entity + IBAN binding for GRU vault operations.
contract RegisterGRUEntityAndIban is Script {
    function run() external {
        uint256 pk = vm.envUint("PRIVATE_KEY");
        address entity = vm.envOr("GRU_OMNL_ENTITY_ADDRESS", vm.addr(pk));
        address entityRegistryAddr = vm.envAddress("REGULATED_ENTITY_REGISTRY");
        address ibanRegistryAddr = vm.envAddress("GRU_ENTITY_IBAN_REGISTRY");

        bytes32 jurisdictionHash = vm.envOr("GRU_JURISDICTION_HASH", keccak256("OMNL"));
        bytes32 ibanHash = vm.envBytes32("GRU_IBAN_HASH");
        address directIban = vm.envOr("GRU_DIRECT_IBAN_ADDRESS", entity);

        RegulatedEntityRegistry entityRegistry = RegulatedEntityRegistry(entityRegistryAddr);
        GRUEntityIbanRegistry ibanRegistry = GRUEntityIbanRegistry(ibanRegistryAddr);

        vm.startBroadcast(pk);

        if (!entityRegistry.isEligible(entity)) {
            address[] memory wallets = new address[](1);
            wallets[0] = entity;
            entityRegistry.registerEntity(entity, jurisdictionHash, wallets);
            console2.log("Registered entity", entity);
        } else {
            console2.log("Entity already registered", entity);
        }

        (address existing,,, bool active) = ibanRegistry.getRecord(ibanHash);
        if (!active) {
            ibanRegistry.registerIban(ibanHash, entity, jurisdictionHash, directIban);
            console2.log("Registered IBAN hash", vm.toString(ibanHash));
        } else {
            console2.log("IBAN already active for entity", existing);
        }

        vm.stopBroadcast();
    }
}
