package wallet

import (
	"context"
	"fmt"
	"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"
	moneyv1 "github.com/tech/sendico/pkg/proto/common/money/v1"
	"go.uber.org/zap"
)

func OnChainWalletBalances(ctx context.Context, deps Deps, wallet *model.ManagedWallet) (*moneyv1.Money, *moneyv1.Money, error) {
	logger := deps.Logger
	if wallet == nil {
		return nil, nil, merrors.InvalidArgument("wallet is required")
	}
	if deps.Networks == nil {
		return nil, nil, merrors.Internal("rpc clients not initialised")
	}
	if deps.Drivers == nil {
		return nil, nil, merrors.Internal("chain drivers not configured")
	}

	networkKey := strings.ToLower(strings.TrimSpace(wallet.Network))
	network, ok := deps.Networks.Network(networkKey)
	if !ok {
		logger.Warn("Requested network is not configured",
			zap.String("wallet_ref", wallet.WalletRef),
			zap.String("network", networkKey),
		)
		return nil, nil, merrors.Internal(fmt.Sprintf("Requested network '%s' is not configured", networkKey))
	}

	chainDriver, err := deps.Drivers.Driver(networkKey)
	if err != nil {
		logger.Warn("Chain driver not configured",
			zap.String("wallet_ref", wallet.WalletRef),
			zap.String("network", networkKey),
			zap.Error(err),
		)
		return nil, nil, merrors.InvalidArgument("unsupported chain")
	}

	driverDeps := driver.Deps{
		Logger:       deps.Logger,
		Registry:     deps.Networks,
		TronRegistry: deps.TronClients,
		KeyManager:   deps.KeyManager,
		RPCTimeout:   deps.RPCTimeout,
	}
	tokenBalance, err := chainDriver.Balance(ctx, driverDeps, network, wallet)
	if err != nil {
		return nil, nil, err
	}
	nativeBalance, err := chainDriver.NativeBalance(ctx, driverDeps, network, wallet)
	if err != nil {
		return nil, nil, err
	}
	return tokenBalance, nativeBalance, nil
}
