package walletapiimp

import (
	"testing"

	"github.com/tech/sendico/pkg/discovery"
	"github.com/tech/sendico/pkg/model"
)

func TestFindGatewayForRoute_PrefersGatewayID(t *testing.T) {
	gateways := []discovery.GatewaySummary{
		{
			ID:        "gw-fallback",
			Rail:      "CRYPTO",
			Healthy:   true,
			InvokeURI: "chain-gw:50070",
			Network:   "ethereum_mainnet",
		},
		{
			ID:        "gw-route",
			Rail:      "CRYPTO",
			Healthy:   true,
			InvokeURI: "tron-gw:50071",
			Network:   "tron_mainnet",
		},
	}

	route := &model.ChainWalletRoute{
		WalletRef: "wallet-1",
		Network:   "ethereum_mainnet",
		GatewayID: "gw-route",
	}

	selected := findGatewayForRoute(gateways, route)
	if selected == nil {
		t.Fatal("expected selected gateway")
	}
	if selected.ID != "gw-route" {
		t.Fatalf("expected gw-route, got %q", selected.ID)
	}
}

func TestFindGatewayForRoute_FallsBackToNetwork(t *testing.T) {
	gateways := []discovery.GatewaySummary{
		{
			ID:        "gw-chain",
			Rail:      "CRYPTO",
			Healthy:   true,
			InvokeURI: "chain-gw:50070",
			Network:   "ethereum_mainnet",
		},
		{
			ID:        "gw-tron",
			Rail:      "CRYPTO",
			Healthy:   true,
			InvokeURI: "tron-gw:50071",
			Network:   "tron_mainnet",
		},
	}

	route := &model.ChainWalletRoute{
		WalletRef: "wallet-1",
		Network:   "tron_mainnet",
		GatewayID: "unknown",
	}

	selected := findGatewayForRoute(gateways, route)
	if selected == nil {
		t.Fatal("expected selected gateway")
	}
	if selected.ID != "gw-tron" {
		t.Fatalf("expected gw-tron, got %q", selected.ID)
	}
}

func TestNormalizeNetworkName(t *testing.T) {
	tests := []struct {
		in   string
		want string
	}{
		{in: "CHAIN_NETWORK_TRON_MAINNET", want: "tron_mainnet"},
		{in: "tron_mainnet-USDT", want: "tron_mainnet"},
		{in: " ethereum_mainnet ", want: "ethereum_mainnet"},
		{in: "", want: ""},
	}

	for _, tc := range tests {
		got := normalizeNetworkName(tc.in)
		if got != tc.want {
			t.Fatalf("normalizeNetworkName(%q) = %q, want %q", tc.in, got, tc.want)
		}
	}
}
