package rpcclient

import (
	"strings"

	"github.com/ethereum/go-ethereum/ethclient"
	"github.com/ethereum/go-ethereum/rpc"
	"github.com/tech/sendico/gateway/tron/shared"
	"github.com/tech/sendico/pkg/merrors"
)

// Registry binds static network metadata with prepared RPC clients.
type Registry struct {
	networks map[string]shared.Network
	clients  *Clients
}

// NewRegistry constructs a registry keyed by lower-cased network name.
func NewRegistry(networks map[string]shared.Network, clients *Clients) *Registry {
	return &Registry{
		networks: networks,
		clients:  clients,
	}
}

// Network fetches network metadata by key (case-insensitive).
func (r *Registry) Network(key string) (shared.Network, bool) {
	if r == nil || len(r.networks) == 0 {
		return shared.Network{}, false
	}
	n, ok := r.networks[strings.ToLower(strings.TrimSpace(key))]
	return n, ok
}

// Client returns the prepared RPC client for the given network name.
func (r *Registry) Client(key string) (*ethclient.Client, error) {
	if r == nil || r.clients == nil {
		return nil, merrors.Internal("rpc clients not initialised")
	}
	return r.clients.Client(strings.ToLower(strings.TrimSpace(key)))
}

// RPCClient returns the raw RPC client for low-level calls.
func (r *Registry) RPCClient(key string) (*rpc.Client, error) {
	if r == nil || r.clients == nil {
		return nil, merrors.Internal("rpc clients not initialised")
	}
	return r.clients.RPCClient(strings.ToLower(strings.TrimSpace(key)))
}

// Networks exposes the registry map for iteration when needed.
func (r *Registry) Networks() map[string]shared.Network {
	return r.networks
}
