package configbuilder

import (
	"testing"

	"github.com/metacubex/mihomo/hub/executor"
	"github.com/prism/proxy/internal/store"
)

func TestSanitizeRulesSkipsUnknownTarget(t *testing.T) {
	nameMap := map[string]string{
		"节点选择": "grp1_auto",
		"grp1_auto": "grp1_auto",
	}
	valid := map[string]bool{
		"DIRECT":    true,
		"REJECT":    true,
		"grp1_auto": true,
	}
	merged := []store.MergedRule{
		{Rule: "DOMAIN,google.com,不存在组"},
		{Rule: "DOMAIN,example.com,节点选择"},
		{Rule: "MATCH,DIRECT", Source: "system"},
	}
	rules := sanitizeRules(merged, nameMap, valid, "DIRECT", true)
	if len(rules) != 2 {
		t.Fatalf("expected 2 rules, got %d: %v", len(rules), rules)
	}
	if rules[0] != "DOMAIN,example.com,grp1_auto" {
		t.Fatalf("unexpected rule: %s", rules[0])
	}
	if rules[1] != "MATCH,DIRECT" {
		t.Fatalf("unexpected match: %s", rules[1])
	}
}

func TestRemapCountryTarget(t *testing.T) {
	nameMap := map[string]string{"country:HK": "country_HK"}
	line := remapRuleTarget("DOMAIN-SUFFIX,google.com,country:HK", nameMap)
	if line != "DOMAIN-SUFFIX,google.com,country_HK" {
		t.Fatalf("unexpected: %s", line)
	}
}

func TestApplyInboundAuth(t *testing.T) {
	cfg := map[string]any{}
	applyInboundAuth(cfg, map[string]string{})
	if _, ok := cfg["authentication"]; ok {
		t.Fatal("expected no authentication when empty")
	}

	applyInboundAuth(cfg, map[string]string{
		"proxy_auth_user": "proxy",
		"proxy_auth_pass": "secret",
	})
	auth, ok := cfg["authentication"].([]string)
	if !ok || len(auth) != 1 || auth[0] != "proxy:secret" {
		t.Fatalf("unexpected authentication: %#v", cfg["authentication"])
	}
	prefixes, ok := cfg["skip-auth-prefixes"].([]string)
	if !ok || len(prefixes) != 2 {
		t.Fatalf("unexpected skip-auth-prefixes: %#v", cfg["skip-auth-prefixes"])
	}
}

func TestBuiltConfigValidatesWithSanitizedRules(t *testing.T) {
	yaml := []byte(`port: 7890
socks-port: 7891
mode: rule
log-level: info
proxies:
  - name: sub1_node
    type: ss
    server: 1.2.3.4
    port: 8388
    cipher: aes-256-gcm
    password: test
proxy-groups:
  - name: grp1_auto
    type: select
    proxies: [sub1_node, DIRECT]
rules:
  - DOMAIN,example.com,grp1_auto
  - MATCH,grp1_auto
`)
	if _, err := executor.ParseWithBytes(yaml); err != nil {
		t.Fatalf("config should validate: %v", err)
	}
}
