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

import "forge-std/Script.sol";
import {CREATE2Factory} from "../../contracts/utils/CREATE2Factory.sol";
import {CompliantFiatToken} from "../../contracts/tokens/CompliantFiatToken.sol";

/**
 * @title DeployCAUSDT
 * @notice Deterministically deploy the Chain 138 cAUSDT contract via CREATE2.
 *
 * Env:
 *   PRIVATE_KEY (required)
 *   CREATE2_FACTORY_ADDRESS (required; CREATE2_FACTORY accepted as fallback)
 *   OWNER / ADMIN (optional; default deployer)
 *   INITIAL_SUPPLY_CAUSDT (optional; defaults to 1_000_000e6)
 */
contract DeployCAUSDT is Script {
    uint8 constant DECIMALS = 6;
    string constant SYMBOL = "cAUSDT";
    string constant NAME = "Alltra USD Token (Compliant)";
    string constant CURRENCY_CODE = "USD";

    function run() external returns (address deployed) {
        uint256 pk = vm.envUint("PRIVATE_KEY");
        address deployer = vm.addr(pk);
        address owner = vm.envOr("OWNER", deployer);
        address admin = vm.envOr("ADMIN", deployer);
        uint256 initialSupply = vm.envOr("INITIAL_SUPPLY_CAUSDT", uint256(1_000_000 * 10**6));

        address factoryAddr = vm.envOr("CREATE2_FACTORY_ADDRESS", vm.envAddress("CREATE2_FACTORY"));
        require(factoryAddr != address(0), "CREATE2 factory required");
        CREATE2Factory factory = CREATE2Factory(factoryAddr);

        uint256 salt = uint256(keccak256(abi.encodePacked("CompliantFiatToken.", SYMBOL)));
        bytes memory bytecode = abi.encodePacked(
            type(CompliantFiatToken).creationCode,
            abi.encode(NAME, SYMBOL, uint8(DECIMALS), CURRENCY_CODE, owner, admin, initialSupply)
        );

        deployed = factory.computeAddress(bytecode, salt);
        if (deployed.code.length > 0) {
            console.log("cAUSDT already deployed", deployed);
            return deployed;
        }

        vm.startBroadcast(pk);
        deployed = factory.deploy(bytecode, salt);
        vm.stopBroadcast();

        console.log("cAUSDT", deployed);
    }
}
