package cql

import (
	"crypto/tls"
	"crypto/x509"
	"testing"
)

func TestTLSConfigAutoGeneratesCertificate(t *testing.T) {
	hostname := "auto-tls.test"
	cfg := TLSConfig{Mode: "auto"}

	tlsCfg, err := cfg.buildTLSConfig(hostname)
	if err != nil {
		t.Fatalf("build tls config failed: %v", err)
	}
	if tlsCfg == nil {
		t.Fatalf("expected tls config")
	}
	if tlsCfg.MinVersion != tls.VersionTLS12 {
		t.Fatalf("expected min version tls1.2, got %v", tlsCfg.MinVersion)
	}
	if len(tlsCfg.Certificates) == 0 || len(tlsCfg.Certificates[0].Certificate) == 0 {
		t.Fatalf("expected certificate data")
	}
	cert, err := x509.ParseCertificate(tlsCfg.Certificates[0].Certificate[0])
	if err != nil {
		t.Fatalf("parse certificate failed: %v", err)
	}
	found := false
	for _, name := range cert.DNSNames {
		if name == hostname {
			found = true
			break
		}
	}
	if !found {
		t.Fatalf("expected dns name %q in certificate, got %v", hostname, cert.DNSNames)
	}
}

func TestTLSConfigModeDisabledReturnsNil(t *testing.T) {
	cfg := TLSConfig{Mode: "disabled"}

	tlsCfg, err := cfg.buildTLSConfig("example")
	if err != nil {
		t.Fatalf("build tls config failed: %v", err)
	}
	if tlsCfg != nil {
		t.Fatalf("expected nil tls config")
	}
}
