#!/usr/bin/env bash
# Simple LINK Token Deployment
# Deploys MockLinkToken and returns the address
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"

source "$PROJECT_ROOT/.env" 2>/dev/null || source "$PROJECT_ROOT/../.env" 2>/dev/null || true

RPC_URL="${RPC_URL_138:-http://192.168.11.250:8545}"
TEMP_DIR=$(mktemp -d)
trap "rm -rf $TEMP_DIR" EXIT

cd "$TEMP_DIR"
forge init --no-git --force . > /dev/null 2>&1

cat > src/MockLinkToken.sol << 'EOF'
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
contract MockLinkToken {
    string public name = "Chainlink Token";
    string public symbol = "LINK";
    uint8 public decimals = 18;
    mapping(address => uint256) public balanceOf;
    mapping(address => mapping(address => uint256)) public allowance;
    uint256 public totalSupply;
    event Transfer(address indexed from, address indexed to, uint256 value);
    event Approval(address indexed owner, address indexed spender, uint256 value);
    function mint(address to, uint256 amount) external {
        balanceOf[to] += amount;
        totalSupply += amount;
        emit Transfer(address(0), to, amount);
    }
    function transfer(address to, uint256 amount) external returns (bool) {
        require(balanceOf[msg.sender] >= amount, "insufficient balance");
        balanceOf[msg.sender] -= amount;
        balanceOf[to] += amount;
        emit Transfer(msg.sender, to, amount);
        return true;
    }
    function transferFrom(address from, address to, uint256 amount) external returns (bool) {
        require(balanceOf[from] >= amount, "insufficient balance");
        require(allowance[from][msg.sender] >= amount, "insufficient allowance");
        balanceOf[from] -= amount;
        balanceOf[to] += amount;
        allowance[from][msg.sender] -= amount;
        emit Transfer(from, to, amount);
        return true;
    }
    function approve(address spender, uint256 amount) external returns (bool) {
        allowance[msg.sender][spender] = amount;
        emit Approval(msg.sender, spender, amount);
        return true;
    }
}
EOF

GAS_PRICE=$(cast gas-price --rpc-url "$RPC_URL" 2>/dev/null || echo "1000000000")
echo "Deploying MockLinkToken..."
DEPLOY_OUTPUT=$(forge create src/MockLinkToken.sol:MockLinkToken \
    --rpc-url "$RPC_URL" \
    --private-key "$PRIVATE_KEY" \
    --gas-price "$GAS_PRICE" \
    --json 2>&1)

LINK_ADDRESS=$(echo "$DEPLOY_OUTPUT" | jq -r '.deployedTo' 2>/dev/null || echo "")
if [ -z "$LINK_ADDRESS" ] || [ "$LINK_ADDRESS" = "null" ]; then
    LINK_ADDRESS=$(echo "$DEPLOY_OUTPUT" | grep -oE "Deployed to: 0x[0-9a-fA-F]{40}" | awk '{print $3}')
fi

if [ -n "$LINK_ADDRESS" ] && [ "$LINK_ADDRESS" != "null" ]; then
    echo "$LINK_ADDRESS"
    exit 0
else
    echo "ERROR: Deployment failed" >&2
    echo "$DEPLOY_OUTPUT" >&2
    exit 1
fi

