package agentd

import (
	"crypto/tls"
	"crypto/x509"
	"encoding/pem"
	"os"
	"path/filepath"
	"testing"
)

func TestEnsureSelfSignedCert(t *testing.T) {
	dir := t.TempDir()
	cert := filepath.Join(dir, "hy2.crt")
	key := filepath.Join(dir, "hy2.key")

	if err := ensureSelfSignedCert(cert, key, "www.apple.com"); err != nil {
		t.Fatalf("generate: %v", err)
	}

	// 必须是 sing-box(crypto/tls)能加载的有效 keypair。
	pair, err := tls.LoadX509KeyPair(cert, key)
	if err != nil {
		t.Fatalf("LoadX509KeyPair: %v", err)
	}
	leaf, err := x509.ParseCertificate(pair.Certificate[0])
	if err != nil {
		t.Fatalf("parse cert: %v", err)
	}
	if leaf.Subject.CommonName != "pangolin-hy2" {
		t.Errorf("CN = %q, want pangolin-hy2", leaf.Subject.CommonName)
	}
	if len(leaf.DNSNames) != 1 || leaf.DNSNames[0] != "www.apple.com" {
		t.Errorf("SAN = %v, want [www.apple.com]", leaf.DNSNames)
	}

	// key 文件权限 0600。
	info, err := os.Stat(key)
	if err != nil {
		t.Fatal(err)
	}
	if perm := info.Mode().Perm(); perm != 0o600 {
		t.Errorf("key perm = %o, want 600", perm)
	}

	// 幂等:第二次调用不应重写(内容不变)。
	before, _ := os.ReadFile(cert)
	if err := ensureSelfSignedCert(cert, key, "www.apple.com"); err != nil {
		t.Fatalf("second call: %v", err)
	}
	after, _ := os.ReadFile(cert)
	if string(before) != string(after) {
		t.Error("cert regenerated on second call; expected idempotent")
	}

	// cert 是 PEM CERTIFICATE 块。
	if blk, _ := pem.Decode(after); blk == nil || blk.Type != "CERTIFICATE" {
		t.Error("cert is not a PEM CERTIFICATE block")
	}
}
