#!/bin/bash

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
TESTNET_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"
NEARDEV_DIR="$TESTNET_DIR/neardev"
BUILD_DIR="$TESTNET_DIR/build"
ROOT_DIR="$(cd "$TESTNET_DIR/../.." && pwd)"

mkdir -p "$NEARDEV_DIR"
mkdir -p "$BUILD_DIR"

# Create new mock tokens account
TIMESTAMP=$(date +%Y-%m-%d_%H-%M-%S)
MOCK_TOKENS_ACCOUNT="${TIMESTAMP}_mock_testnet_tokens.testnet"

echo "Creating new mock tokens account: $MOCK_TOKENS_ACCOUNT"
near create-account "$MOCK_TOKENS_ACCOUNT" --useFaucet
echo "$MOCK_TOKENS_ACCOUNT" > "$NEARDEV_DIR/mock-tokens-account"

# Build the mock MT contract
echo "Building mock MT contract..."
cd "$ROOT_DIR/mock_contracts/mock_mt/"
if ! cargo near build non-reproducible-wasm; then
    echo "Failed to build mock MT contract"
    exit 1
fi

# Copy the WASM file to testnet build folder
echo "Copying WASM file to testnet build directory..."
if ! cp "$ROOT_DIR/target/near/mock_mt/mock_mt.wasm" "$BUILD_DIR/mock_mt.wasm"; then
    echo "Failed to copy WASM file"
    exit 1
fi

# Deploy the mock MT contract using the copied WASM file
echo "Deploying mock MT contract..."
cd "$TESTNET_DIR"
if ! near deploy "$MOCK_TOKENS_ACCOUNT" "build/mock_mt.wasm"; then
    echo "Failed to deploy mock MT contract"
    exit 1
fi

# Initialize the mock MT contract
echo "Initializing mock MT contract..."
if ! near call "$MOCK_TOKENS_ACCOUNT" new '{}' --accountId="$MOCK_TOKENS_ACCOUNT" --gas=300000000000000; then
    echo "Failed to initialize mock MT contract"
    exit 1
fi

# Mock USDC - 1,000,000 tokens (6 decimals = 1,000,000 * 10^6)
echo "Minting mock USDC tokens..."
USDC_INITIAL_SUPPLY="1000000000000"
if ! near call "$MOCK_TOKENS_ACCOUNT" mint '{
    "account_id": "'"$MOCK_TOKENS_ACCOUNT"'",
    "token_id": "mock.usdc.testnet",
    "amount": "'"$USDC_INITIAL_SUPPLY"'"
}' --accountId="$MOCK_TOKENS_ACCOUNT" --gas=300000000000000; then
    echo "Failed to mint mock USDC"
    exit 1
fi

# Mock USDT - 1,000,000 tokens (6 decimals = 1,000,000 * 10^6)
echo "Minting mock USDT tokens..."
USDT_INITIAL_SUPPLY="1000000000000"
if ! near call "$MOCK_TOKENS_ACCOUNT" mint '{
    "account_id": "'"$MOCK_TOKENS_ACCOUNT"'",
    "token_id": "mock.usdt.testnet",
    "amount": "'"$USDT_INITIAL_SUPPLY"'"
}' --accountId="$MOCK_TOKENS_ACCOUNT" --gas=300000000000000; then
    echo "Failed to mint mock USDT"
    exit 1
fi

echo "Mock tokens deployed successfully: $MOCK_TOKENS_ACCOUNT"
echo "Account saved to: $NEARDEV_DIR/mock-tokens-account"
echo "WASM file copied to: $BUILD_DIR/mock_mt.wasm"