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

import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "./UniversalCCIPBridge.sol";

contract VaultBridgeAdapter is AccessControl, ReentrancyGuard {
    using SafeERC20 for IERC20;

    bytes32 public constant ADAPTER_ADMIN_ROLE = keccak256("ADAPTER_ADMIN_ROLE");

    address public vaultFactory;
    UniversalCCIPBridge public bridge;
    
    mapping(address => address) public userVaults;

    event VaultCreated(address indexed user, address indexed vault);

    constructor(address _vaultFactory, address _bridge, address admin) {
        require(_vaultFactory != address(0), "Zero factory");
        require(_bridge != address(0), "Zero bridge");
        
        vaultFactory = _vaultFactory;
        bridge = UniversalCCIPBridge(payable(_bridge));
        
        _grantRole(DEFAULT_ADMIN_ROLE, admin);
        _grantRole(ADAPTER_ADMIN_ROLE, admin);
    }

    function getOrCreateVault(address user) public returns (address vault) {
        vault = userVaults[user];
        if (vault == address(0)) {
            (bool success, bytes memory data) = vaultFactory.call(
                abi.encodeWithSignature("createVault(address)", user)
            );
            if (success) {
                vault = abi.decode(data, (address));
                userVaults[user] = vault;
                emit VaultCreated(user, vault);
            }
        }
        return vault;
    }
}
