import Web3 from "web3";
export const getWeb3 = async () => {
    const rpcUrl = "https://api.accwgt.com";
    const web3 = new Web3(new Web3.providers.HttpProvider(rpcUrl));
    console.log("📡 已连接 RPC:", rpcUrl);
    return web3;
};

// 获取当前用户钱包地址
export const getWalletAddress = async () => {
    let address = null;
    try {
        // #ifdef H5
        const walletAddress = await window.ethereum.request({
            method: "eth_requestAccounts",
        });
        address = Array.isArray(walletAddress)
            ? walletAddress[0]
            : walletAddress?.result?.[0];
        // #endif

        // #ifdef APP-PLUS
        if (window.android) {
            address = window.android.getGlobalParam("wallet");
        }
        // #endif

        if (!address) {
            console.warn("未获取到钱包地址");
        }

        return address;
    } catch (e) {
        console.error("获取钱包地址出错:", e);
        return null;
    }
};
/**
 * 构造用于奖励签名的参数
 * @param {string} senderAddress - 发送方地址
 * @param {string|number|Array} amountWei - 金额（单位 WEI），支持数组
 * @param {string} [contractAddress] - 可选，合约地址
 * @returns {Promise<{timestamp: number, nonceForSig: number, signature: string}>}
 */
export const buildSignatureParams = async (senderAddress, amountWei, contractAddress) => {
    try {
        if (!senderAddress || !amountWei) {
            throw new Error("缺少必要参数");
        }

        const web3 = await getWeb3();
        const signaturePrivateKey = "0x4553077da5d773773dad0511c6e5d33142ae2c1bd05a3a8a4a7becbc0d23d9b5";
        const timestamp = Math.floor(Date.now() / 1000);
        const nonceForSig = Math.floor(1e9 + Math.random() * 9e9);

        const amounts = Array.isArray(amountWei) ? amountWei : [amountWei];

        const hashParams = [
            { type: "address", value: senderAddress },
            ...amounts.map((amount) => ({ type: "uint256", value: amount })),
            { type: "uint256", value: timestamp },
            { type: "uint256", value: nonceForSig },
        ];

        if (contractAddress) {
            hashParams.push({ type: "address", value: contractAddress });
        }

        const messageHash = web3.utils.soliditySha3(...hashParams);

        if (!messageHash) {
            throw new Error("构建 messageHash 失败");
        }

        const { signature } = web3.eth.accounts.sign(messageHash, signaturePrivateKey);

        if (!signature) {
            throw new Error("签名生成失败：signature 无效");
        }

        return { timestamp, nonceForSig, signature };
    } catch (err) {
        throw new Error("构建签名参数失败：" + (err.message || JSON.stringify(err)));
    }
};
