package infra

import (
	"encoding/base64"
	"os/exec"
	"strings"
	"testing"
)

func TestWGKeygen(t *testing.T) {
	// Skip if wg binary is not present in PATH
	if _, err := exec.LookPath("wg"); err != nil {
		t.Skip("wg binary not found in PATH, skipping WireGuard keygen tests")
	}

	t.Run("genera par de claves sin PSK", func(t *testing.T) {
		keys, err := WGKeygen(false)
		if err != nil {
			t.Fatalf("WGKeygen(false) error: %v", err)
		}
		if keys.PrivateKey == "" {
			t.Error("PrivateKey vacia")
		}
		if keys.PublicKey == "" {
			t.Error("PublicKey vacia")
		}
		if keys.PresharedKey != "" {
			t.Errorf("PresharedKey debe estar vacia sin PSK, got %q", keys.PresharedKey)
		}
		// WireGuard keys are 32-byte Curve25519, base64-encoded → 44 chars with padding
		if len(strings.TrimSpace(keys.PrivateKey)) != 44 {
			t.Errorf("PrivateKey len esperado 44, got %d", len(keys.PrivateKey))
		}
		if len(strings.TrimSpace(keys.PublicKey)) != 44 {
			t.Errorf("PublicKey len esperado 44, got %d", len(keys.PublicKey))
		}
		// Validate they are valid base64
		if _, err := base64.StdEncoding.DecodeString(keys.PrivateKey); err != nil {
			t.Errorf("PrivateKey no es base64 valido: %v", err)
		}
		if _, err := base64.StdEncoding.DecodeString(keys.PublicKey); err != nil {
			t.Errorf("PublicKey no es base64 valido: %v", err)
		}
	})

	t.Run("genera par de claves con PSK", func(t *testing.T) {
		keys, err := WGKeygen(true)
		if err != nil {
			t.Fatalf("WGKeygen(true) error: %v", err)
		}
		if keys.PrivateKey == "" {
			t.Error("PrivateKey vacia")
		}
		if keys.PublicKey == "" {
			t.Error("PublicKey vacia")
		}
		if keys.PresharedKey == "" {
			t.Error("PresharedKey debe estar presente con withPSK=true")
		}
		if len(strings.TrimSpace(keys.PresharedKey)) != 44 {
			t.Errorf("PresharedKey len esperado 44, got %d", len(keys.PresharedKey))
		}
		if _, err := base64.StdEncoding.DecodeString(keys.PresharedKey); err != nil {
			t.Errorf("PresharedKey no es base64 valido: %v", err)
		}
	})
}
