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

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

/// @notice Deterministic GRU registry deploy via CREATE2Factory (cross-chain parity).
contract DeployGRUVaultRegistriesCreate2 is Script {
    uint256 constant SALT_IBAN = uint256(keccak256("GRUEntityIbanRegistry"));
    uint256 constant SALT_INDEX = uint256(keccak256("GRUVaultIndex"));

    function run() external {
        uint256 pk = vm.envUint("PRIVATE_KEY");
        address admin = vm.envOr("GRU_VAULT_ADMIN", vm.addr(pk));
        address factoryAddr = vm.envAddress("CREATE2_FACTORY_ADDRESS");

        CREATE2Factory factory = CREATE2Factory(factoryAddr);

        bytes memory ibanInit = abi.encodePacked(type(GRUEntityIbanRegistry).creationCode, abi.encode(admin));
        bytes memory indexInit = abi.encodePacked(type(GRUVaultIndex).creationCode, abi.encode(admin));

        address predictedIban = factory.computeAddress(ibanInit, SALT_IBAN);
        address predictedIndex = factory.computeAddress(indexInit, SALT_INDEX);

        vm.startBroadcast(pk);

        address ibanReg = predictedIban.code.length > 0
            ? predictedIban
            : factory.deploy(ibanInit, SALT_IBAN);
        address vaultIndex = predictedIndex.code.length > 0
            ? predictedIndex
            : factory.deploy(indexInit, SALT_INDEX);

        address factoryAddrVault = vm.envOr("VAULT_FACTORY_ADDRESS", address(0));
        if (factoryAddrVault != address(0) && factoryAddrVault.code.length > 0) {
            VaultFactory(factoryAddrVault).setGruVaultIndex(vaultIndex);
            GRUVaultIndex(vaultIndex).grantFactoryRole(factoryAddrVault);
            console2.log("Wired VaultFactory", factoryAddrVault);
        }

        vm.stopBroadcast();

        console2.log("CREATE2Factory", factoryAddr);
        console2.log("GRUEntityIbanRegistry", ibanReg);
        console2.log("GRUVaultIndex", vaultIndex);
    }
}
