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

import {Script, console} from "forge-std/Script.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SimpleERC3156FlashVault} from "../../contracts/flash/SimpleERC3156FlashVault.sol";

/**
 * @title DeploySimpleERC3156FlashVault
 * @notice Deploy ERC-3156 flash vault for Chain 138; optional USDT whitelist + seed transfer from deployer.
 *
 * Env (broadcast):
 *   PRIVATE_KEY           — required
 *   FLASH_VAULT_OWNER     — optional; default: deployer
 *   FLASH_VAULT_FEE_BPS   — optional; default: 5 (0.05%)
 *   FLASH_VAULT_TOKEN     — optional; token to whitelist (default: official USDT Chain 138)
 *   FLASH_VAULT_SEED_AMOUNT — optional; raw token units to transfer from deployer into vault after deploy (0 = skip)
 *
 * Usage:
 *   forge script script/deploy/DeploySimpleERC3156FlashVault.s.sol:DeploySimpleERC3156FlashVault \
 *     --rpc-url $RPC_URL_138 --broadcast -vvvv
 */
contract DeploySimpleERC3156FlashVault is Script {
    /// @dev Canonical official USDT (Chain 138) per project config / explorer.
    address internal constant DEFAULT_USDT_138 = 0x004b63A7B5b0E06f6bB6adb4a5F9f590BF3182D1;

    function run() external {
        uint256 pk = vm.envUint("PRIVATE_KEY");
        address deployer = vm.addr(pk);
        address vaultOwner = vm.envOr("FLASH_VAULT_OWNER", deployer);
        uint256 feeBps = vm.envOr("FLASH_VAULT_FEE_BPS", uint256(5));
        address token = vm.envOr("FLASH_VAULT_TOKEN", DEFAULT_USDT_138);
        uint256 seedAmount = vm.envOr("FLASH_VAULT_SEED_AMOUNT", uint256(0));

        console.log("Deployer:", deployer);
        console.log("Vault owner:", vaultOwner);
        console.log("feeBps:", feeBps);
        console.log("Whitelist token:", token);

        vm.startBroadcast(pk);

        SimpleERC3156FlashVault vault = new SimpleERC3156FlashVault(vaultOwner, feeBps);
        console.log("SimpleERC3156FlashVault:", address(vault));

        if (vaultOwner == deployer) {
            vault.setTokenSupported(token, true);
            console.log("setTokenSupported: true");
            if (seedAmount > 0) {
                IERC20(token).transfer(address(vault), seedAmount);
                console.log("Seeded vault (raw units):", seedAmount);
                console.log("Vault balance:", IERC20(token).balanceOf(address(vault)));
            }
        } else {
            console.log("Owner != deployer: owner must call setTokenSupported + seed separately.");
        }

        vm.stopBroadcast();
    }
}
