package shared

import (
	"bytes"
	"crypto/sha256"
	"encoding/hex"
	"fmt"
	"strings"

	"github.com/shengdoushi/base58"
	"github.com/tech/sendico/pkg/merrors"
)

func TronBase58ToHex(addr string) (string, error) {
	const (
		tronAddrLen = 25
		tronPrefix  = byte(0x41)
	)

	raw, err := base58.Decode(strings.TrimSpace(addr), base58.BitcoinAlphabet)
	if err != nil {
		return "", merrors.InvalidArgument(
			fmt.Sprintf("tron address: base58 decode failed: %s", err.Error()),
		)
	}

	if len(raw) != tronAddrLen {
		return "", merrors.DataConflict(
			fmt.Sprintf("tron address: invalid length %d", len(raw)),
		)
	}

	// 21 байт: prefix + 20 байт EVM
	payload := raw[:21]
	checksum := raw[21:]

	if payload[0] != tronPrefix {
		return "", merrors.DataConflict("tron address: invalid prefix")
	}

	// validate checksum (double sha256)
	h1 := sha256.Sum256(payload)
	h2 := sha256.Sum256(h1[:])
	expectedChecksum := h2[:4]

	if !bytes.Equal(expectedChecksum, checksum) {
		return "", merrors.DataConflict("tron address: invalid checksum")
	}

	evm := payload[1:]
	return "0x" + hex.EncodeToString(evm), nil
}
