package systemconfig_test

import (
	"testing"

	"github.com/break/junhong_cmp_fiber/internal/infrastructure/systemconfig"
	"github.com/break/junhong_cmp_fiber/pkg/constants"
)

func TestRegistryRejectsDuplicateTypeConflictAndInvalidDefault(t *testing.T) {
	t.Parallel()

	registry := systemconfig.NewRegistry()
	definition := systemconfig.Definition{
		Key: "foundation.example.limit", Module: "foundation", ValueType: constants.SystemConfigTypeInt,
		DefaultValue: "10", Description: "示例限制",
	}
	if err := registry.Register(definition); err != nil {
		t.Fatalf("注册合法配置失败：%v", err)
	}
	if err := registry.Register(definition); err == nil {
		t.Fatal("重复 Key 必须被拒绝")
	}
	conflict := definition
	conflict.ValueType = constants.SystemConfigTypeString
	if err := registry.Register(conflict); err == nil {
		t.Fatal("同 Key 类型冲突必须被拒绝")
	}
	invalid := definition
	invalid.Key = "foundation.example.invalid"
	invalid.DefaultValue = "not-int"
	if err := registry.Register(invalid); err == nil {
		t.Fatal("非法默认值必须在注册阶段失败")
	}
}

func TestValidateValueSupportsFourControlledTypesAndBounds(t *testing.T) {
	t.Parallel()

	minimum, maximum := int64(1), int64(10)
	cases := []systemconfig.Definition{
		{Key: "a.b.string", Module: "a", ValueType: constants.SystemConfigTypeString, DefaultValue: "x", Description: "字符串"},
		{Key: "a.b.int", Module: "a", ValueType: constants.SystemConfigTypeInt, DefaultValue: "5", Description: "整数", Min: &minimum, Max: &maximum},
		{Key: "a.b.bool", Module: "a", ValueType: constants.SystemConfigTypeBool, DefaultValue: "true", Description: "布尔"},
		{Key: "a.b.json", Module: "a", ValueType: constants.SystemConfigTypeJSON, DefaultValue: `{"enabled":true}`, Description: "JSON"},
	}
	for _, definition := range cases {
		if err := systemconfig.ValidateValue(definition, definition.DefaultValue); err != nil {
			t.Fatalf("合法 %s 值未通过：%v", definition.ValueType, err)
		}
	}
	if err := systemconfig.ValidateValue(cases[1], "11"); err == nil {
		t.Fatal("越界整数必须被拒绝")
	}
	if err := systemconfig.ValidateValue(cases[2], "yes"); err == nil {
		t.Fatal("非法布尔值必须被拒绝")
	}
	if err := systemconfig.ValidateValue(cases[3], "{"); err == nil {
		t.Fatal("非法 JSON 必须被拒绝")
	}
}
