package runtimegrpc

import (
	"reflect"
	"testing"
	"time"
)

func TestRuntimeClientConfigReleasedFieldShape(t *testing.T) {
	// These positional literals model already-released downstream source. A
	// field added to either public struct makes this package fail to compile.
	_ = RuntimeClientConfig{"", "", "", "", "", "", "", 0}
	_ = RuntimeClientMetrics{0, 0}

	typeOfConfig := reflect.TypeOf(RuntimeClientConfig{})
	want := []string{
		"Target", "AppInstallationID", "WorkloadToken", "CAFile", "ServerName",
		"ClientCertificateFile", "ClientKeyFile", "AttemptTimeout",
	}
	if typeOfConfig.NumField() != len(want) {
		t.Fatalf("RuntimeClientConfig fields = %d, want released shape %d", typeOfConfig.NumField(), len(want))
	}
	for index, name := range want {
		if got := typeOfConfig.Field(index).Name; got != name {
			t.Fatalf("RuntimeClientConfig field %d = %q, want %q", index, got, name)
		}
	}
}

func TestRuntimeClientGroupOptionsAreAdditiveAndValidated(t *testing.T) {
	config := RuntimeClientConfig{Target: "passthrough:///runtime-a:9090"}
	group, err := NewRuntimeClientGroupWithOptions(config, WithRecordMutationAdmissionRetryBudget(750*time.Millisecond))
	if err != nil {
		t.Fatal(err)
	}
	if group.options.recordMutationAdmissionRetryBudget != 750*time.Millisecond {
		t.Fatalf("options = %#v", group.options)
	}
	if _, err := NewRuntimeClientGroupWithOptions(config, WithRecordMutationAdmissionRetryBudget(-1)); err == nil {
		t.Fatal("negative admission retry budget was accepted")
	}
}

func TestRuntimeClientGroupCapturesOneAuthorityByValue(t *testing.T) {
	config := RuntimeClientConfig{Target: "passthrough:///runtime-a:9090", WorkloadToken: "workload-a"}
	group := NewRuntimeClientGroup(config)
	config.Target = "passthrough:///runtime-b:9090"
	config.WorkloadToken = "workload-b"

	if group.config.Target != "passthrough:///runtime-a:9090" || group.config.WorkloadToken != "workload-a" {
		t.Fatalf("group authority changed with caller config: %#v", group.config)
	}
	wantAuthority := runtimeIdentityAuthority(group.config)
	if group.identityCoordinator == nil || group.identityCoordinator.bursts.authority != wantAuthority {
		t.Fatal("group coordinator is not bound to its captured Runtime/workload authority")
	}
}
