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

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

/// @notice Deploy GRU protocol registries and wire an existing or new VaultFactory.
/// @dev Run after DeployVaultSystem or pass VAULT_FACTORY_ADDRESS to wire index on live factory.
contract DeployGRUVaultProtocol is Script {
    function run() external {
        uint256 pk = vm.envUint("PRIVATE_KEY");
        address admin = vm.envOr("GRU_VAULT_ADMIN", vm.addr(pk));

        vm.startBroadcast(pk);

        GRUEntityIbanRegistry ibanRegistry = new GRUEntityIbanRegistry(admin);
        GRUVaultIndex vaultIndex = new GRUVaultIndex(admin);

        address factoryAddr = vm.envOr("VAULT_FACTORY_ADDRESS", address(0));
        if (factoryAddr != address(0)) {
            VaultFactory(factoryAddr).setGruVaultIndex(address(vaultIndex));
            vaultIndex.grantFactoryRole(factoryAddr);
            console2.log("Wired VaultFactory", factoryAddr);
        }

        vm.stopBroadcast();

        console2.log("GRUEntityIbanRegistry", address(ibanRegistry));
        console2.log("GRUVaultIndex", address(vaultIndex));
        console2.log("admin", admin);
    }
}
