package mxgateway

import (
	"crypto/tls"
	"testing"
)

// tlsConfigFromOptions is the internal helper under test.
// It extracts the *tls.Config from the no-CA TLS path of resolveTransportCredentials.
// We exercise it directly to avoid needing a real dial target.

func TestTLSInsecureSkipVerify_DefaultTrue(t *testing.T) {
	cfg := tlsConfigForOptions(Options{
		Endpoint: "localhost:5120",
	})
	if cfg == nil {
		t.Fatal("expected non-nil tls.Config")
	}
	if !cfg.InsecureSkipVerify {
		t.Error("InsecureSkipVerify should be true by default when no CA is pinned")
	}
}

func TestTLSInsecureSkipVerify_FalseWhenRequireCertificateValidation(t *testing.T) {
	cfg := tlsConfigForOptions(Options{
		Endpoint:                     "localhost:5120",
		RequireCertificateValidation: true,
	})
	if cfg == nil {
		t.Fatal("expected non-nil tls.Config")
	}
	if cfg.InsecureSkipVerify {
		t.Error("InsecureSkipVerify should be false when RequireCertificateValidation is true")
	}
}

func TestTLSInsecureSkipVerify_FalseWhenCACertFileSet(t *testing.T) {
	// When a CA file is pinned, the CA-verification path is taken instead.
	// tlsConfigForOptions should return nil (the CA path does not use our helper).
	cfg := tlsConfigForOptions(Options{
		Endpoint:   "localhost:5120",
		CACertFile: "/some/ca.pem",
	})
	if cfg != nil {
		t.Error("expected nil tls.Config when CACertFile is set (CA path taken)")
	}
}

func TestTLSInsecureSkipVerify_FalseWhenCustomTLSConfig(t *testing.T) {
	// When TLSConfig is supplied explicitly, our default skip-verify must not overwrite it.
	custom := &tls.Config{MinVersion: tls.VersionTLS13}
	cfg := tlsConfigForOptions(Options{
		Endpoint:  "localhost:5120",
		TLSConfig: custom,
	})
	if cfg != nil {
		t.Error("expected nil tls.Config when TLSConfig is already set (custom config path taken)")
	}
}
