package transfer

import (
	"context"
	"strings"

	"github.com/tech/sendico/gateway/tron/internal/service/gateway/driver"
	"github.com/tech/sendico/gateway/tron/storage/model"
	"github.com/tech/sendico/pkg/merrors"
)

func destinationAddress(ctx context.Context, deps Deps, chainDriver driver.Driver, dest model.TransferDestination) (string, error) {
	if ref := strings.TrimSpace(dest.ManagedWalletRef); ref != "" {
		wallet, err := deps.Storage.Wallets().Get(ctx, ref)
		if err != nil {
			return "", err
		}
		if strings.TrimSpace(wallet.DepositAddress) == "" {
			return "", merrors.Internal("destination wallet missing deposit address")
		}
		return chainDriver.NormalizeAddress(wallet.DepositAddress)
	}
	if addr := strings.TrimSpace(dest.ExternalAddress); addr != "" {
		return chainDriver.NormalizeAddress(addr)
	}
	return "", merrors.InvalidArgument("transfer destination address not resolved")
}
