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

import {Test} from "forge-std/Test.sol";
import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import {IERC3156FlashBorrower} from "@openzeppelin/contracts/interfaces/IERC3156FlashBorrower.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SimpleERC3156FlashVault} from "../../contracts/flash/SimpleERC3156FlashVault.sol";
import {MinimalERC3156FlashBorrower} from "../../contracts/flash/MinimalERC3156FlashBorrower.sol";

contract MockERC20Mint is ERC20 {
    constructor() ERC20("Mock", "MCK") {}

    function mint(address to, uint256 v) external {
        _mint(to, v);
    }
}

contract MinimalERC3156FlashBorrowerTest is Test {
    SimpleERC3156FlashVault internal vault;
    MockERC20Mint internal token;
    MinimalERC3156FlashBorrower internal borrower;

    address internal owner = address(0xA11);
    address internal user = address(0xB22);

    function setUp() public {
        vm.startPrank(owner);
        vault = new SimpleERC3156FlashVault(owner, 5);
        token = new MockERC20Mint();
        token.mint(address(vault), 1_000_000e18);
        vault.setTokenSupported(address(token), true);
        vm.stopPrank();

        borrower = new MinimalERC3156FlashBorrower(address(vault));
    }

    function test_oneUnitFlash_repayWithPrefundedFee() public {
        uint256 amount = 1000e18;
        uint256 fee = vault.flashFee(address(token), amount);
        token.mint(address(borrower), fee);

        uint256 vaultBefore = token.balanceOf(address(vault));
        vm.prank(user);
        vault.flashLoan(IERC3156FlashBorrower(address(borrower)), address(token), amount, "");

        assertEq(token.balanceOf(address(vault)), vaultBefore + fee);
    }

    function test_onFlashLoan_revert_wrongLender() public {
        vm.expectRevert(MinimalERC3156FlashBorrower.UntrustedLender.selector);
        borrower.onFlashLoan(user, address(token), 1, 0, "");
    }
}
