package config

import "testing"

func TestCredentialModeRequiresCompleteTLSComposition(t *testing.T) {
	node := &NodeConfig{CredentialPlane: NodeCredentialPlaneConf{Enabled: true, RecipientKeyID: "recipient", RecipientPrivateKey: "/key", IssuerKeyID: "issuer", IssuerPublicKey: "/pub", ReplayCacheSize: 1}}
	if err := validateNodeCredentialPlane(node); err == nil {
		t.Fatal("credential Node accepted plaintext Edge transport")
	}
	node.Transport.TLS = TLSConf{Enabled: true, Cert: "/cert", Key: "/key", CA: "/ca", ServerName: "edge", PeerRole: "edge"}
	if err := validateNodeCredentialPlane(node); err != nil {
		t.Fatalf("complete credential Node config rejected: %v", err)
	}

	edge := &EdgeConfig{CredentialPlane: EdgeCredentialPlaneConf{Enabled: true, LeaseTTLSeconds: 30, LeaseCacheSize: 1}}
	if err := validateEdgeCredentialPlane(edge); err == nil {
		t.Fatal("credential Edge accepted incomplete TLS composition")
	}
	edge.TLS = TLSConf{Enabled: true, Cert: "/cert", Key: "/key", CA: "/ca", PeerRole: "node"}
	edge.ControlPlane = EdgeControlPlaneConf{Enabled: true, WireAddr: "control-plane:19081", TLS: TLSConf{Enabled: true, Cert: "/cert", Key: "/key", CA: "/ca", ServerName: "control-plane", PeerRole: "control-plane"}}
	if err := validateEdgeCredentialPlane(edge); err != nil {
		t.Fatalf("complete credential Edge config rejected: %v", err)
	}
	edge.OpenAI.Enabled = true
	if err := validateEdgeCredentialPlane(edge); err == nil {
		t.Fatal("credential ingress accepted plaintext HTTP")
	}
	edge.OpenAI.TLS = TLSConf{Enabled: true, Cert: "/cert", Key: "/key"}
	if err := validateEdgeCredentialPlane(edge); err != nil {
		t.Fatalf("credential HTTPS config rejected: %v", err)
	}
}

func TestTLSClientRequiresDNSNameAndRole(t *testing.T) {
	base := TLSConf{Enabled: true, Cert: "/cert", Key: "/key", CA: "/ca"}
	if err := base.ValidateClient("edge"); err == nil {
		t.Fatal("mTLS client accepted missing server_name")
	}
	base.ServerName = "edge.internal"
	if err := base.ValidateClient("edge"); err != nil {
		t.Fatalf("valid mTLS client rejected: %v", err)
	}
	if base.EffectivePeerRole("edge") != "edge" {
		t.Fatal("default peer role was not applied")
	}
}
