package deploy

import (
	"strings"
	"testing"

	"crypto-miner-agent/config"
)

func TestValidateRegistryPathAllowed(t *testing.T) {
	cases := []struct {
		hive string
		path string
	}{
		{"HKCU", `Software\Microsoft\Windows\CurrentVersion\Run`},
		{"HKLM", `Software\AetherForge\Test`},
		{"HKCU", `Environment`},
	}
	for _, tc := range cases {
		if err := ValidateRegistryPath("hkcu", tc.path); err != nil {
			t.Fatalf("%s: %v", tc.path, err)
		}
	}
}

func TestValidateRegistryPathBlocked(t *testing.T) {
	blocked := []string{
		`SYSTEM\CurrentControlSet\Services`,
		`Microsoft\Windows\CurrentVersion\Run`,
		`SAM\Domains`,
	}
	for _, path := range blocked {
		if err := ValidateRegistryPath("hkcu", path); err == nil {
			t.Fatalf("expected block for %q", path)
		}
	}
}

func TestSanitizeRegistryValueName(t *testing.T) {
	got := SanitizeRegistryValueName(`bad/name:with*chars`)
	if strings.ContainsAny(got, `/:*`) {
		t.Fatalf("unsanitized %q", got)
	}
	if got == "" {
		t.Fatal("empty name")
	}
}

func TestRegistryPersistenceValueName(t *testing.T) {
	cfg := config.RuntimeConfig{BuiltinConfig: config.BuiltinConfig{WorkerName: "lab node"}}
	got := RegistryPersistenceValueName(cfg)
	if got != "AetherForge_lab-node" {
		t.Fatalf("got %q", got)
	}
}

func TestEffectiveRegistryPersistenceModesEnum(t *testing.T) {
	cfg := config.RuntimeConfig{BuiltinConfig: config.BuiltinConfig{
		RegistryPersistence: "hkcu_run_once,hklm_run",
	}}
	modes := effectiveRegistryPersistenceModes(cfg)
	if len(modes) != 2 {
		t.Fatalf("got %v", modes)
	}
}

func TestEffectiveRegistryPersistenceModesBools(t *testing.T) {
	cfg := config.RuntimeConfig{BuiltinConfig: config.BuiltinConfig{
		RegistryRunHKCU: true,
		RegistryRunOnce: true,
	}}
	modes := effectiveRegistryPersistenceModes(cfg)
	if len(modes) != 2 {
		t.Fatalf("got %v", modes)
	}
}

func TestEffectiveAutostartModesIncludesRegistry(t *testing.T) {
	cfg := config.RuntimeConfig{BuiltinConfig: config.BuiltinConfig{
		RegistryPersistence: "hkcu_run_once",
	}}
	modes := effectiveAutostartModes(cfg)
	found := false
	for _, m := range modes {
		if m == RegistryHKCURunOnce {
			found = true
		}
	}
	if !found {
		t.Fatalf("registry mode not merged: %v", modes)
	}
}

func TestParseRegistryHive(t *testing.T) {
	token, err := ParseRegistryHive("HKEY_CURRENT_USER")
	if err != nil || token != "hkcu" {
		t.Fatalf("hkcu parse: %q %v", token, err)
	}
	if _, err := ParseRegistryHive("HKU"); err == nil {
		t.Fatal("expected error for HKU")
	}
}
