package com.crm.ucard.util;

import cn.hutool.json.JSONObject;
import com.crm.ucard.model.TxResult;

/**
 * @author gao
 * @date 2026/1/13
 */
public class EncryptionHashQueryUtil {

    private static final String API ="https://eth.blockscout.com/api/v2/transactions/";
    private static final String TX_API = "https://apilist.tronscanapi.com/api/transaction-info?hash=";

    public static TxResult query(String txHash, String unit) throws Exception {
        switch (unit) {
            case "TRC":
                return TrcTxquery(txHash);
            case "ETH":
                return EthTxquery(txHash);
            default:
                return null;
        }
    }
    public static TxResult TrcTxquery(String txHash) throws Exception {

        String json = HttpUtil.get(TX_API + txHash);
        JSONObject obj = new JSONObject(json);
        String from = obj.getStr("ownerAddress");
        String to = obj.getStr("toAddress");
        Long confirmations = obj.getLong("confirmations");
        String contractRet = obj.getStr("contractRet");

        TxResult r = new TxResult();
        r.setFrom(from);
        r.setTo(to);
        r.setChain("TRC");
        r.setTxHash(txHash);
//        r.setBlockNumber(block);
        r.setConfirmations(confirmations);
        r.setStatus(
                "SUCCESS".equals(contractRet)
                        ? "SUCCESS"
                        : "FAILED"
        );

        return r;
    }
    public static TxResult EthTxquery(String txHash) throws Exception {

        String json = HttpUtil.get(API + txHash);
        if (json == null || json.contains("not found")) {
            return notFound(txHash);
        }

        JSONObject obj = new JSONObject(json);

        TxResult r = new TxResult();
        r.setChain("ETH");
        r.setTxHash(txHash);
        r.setFrom(obj.getJSONObject("from").getStr("hash"));
        r.setTo(obj.getJSONObject("to").getStr("hash"));
        r.setAmount(obj.getStr("value"));
        r.setBlockNumber(obj.getLong("block_number"));
        r.setConfirmations(obj.getLong("confirmations"));

        String status = obj.getStr("status");
        if ("ok".equalsIgnoreCase(status)) {
            if (r.getConfirmations() >= 12) {
                r.setStatus("SUCCESS");
            } else {
                r.setStatus("FAILED");
            }
        } else {
            r.setStatus("FAILED");
        }

        return r;
    }

    private static TxResult notFound(String hash) {
        TxResult r = new TxResult();
        r.setChain("ETH");
        r.setTxHash(hash);
        r.setStatus("FAILED");
        return r;
    }
}
