package runner_test

import (
	"testing"

	"github.com/stretchr/testify/require"

	"github.com/tidbcloud/AgentTeam/internal/extension/runner"
)

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

	valid := runner.ConnectionConfig{"topology": "aggregate"}
	require.NoError(t, valid.Validate())
	cloned := valid.Clone()
	cloned["topology"] = "fallback"
	require.Equal(t, "aggregate", valid["topology"])

	for _, invalid := range []runner.ConnectionConfig{
		{"": "aggregate"},
		{"Topology": "aggregate"},
		{"topology-name": "aggregate"},
		{"topology": ""},
		{"topology": " fallback"},
		{"topology": "fall\nback"},
		{"topology": "回退"},
		{"topology": string([]byte{0xff})},
	} {
		require.Error(t, invalid.Validate())
	}
}

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

	contract := runner.ConnectionConfigContract{
		Fields: []runner.ConnectionConfigField{
			{
				Name:     "topology",
				Required: true,
				Values:   []string{"aggregate", "fallback"},
			},
		},
	}
	require.NoError(t, contract.ValidateSpec())
	require.NoError(t, contract.Validate(
		runner.ConnectionConfig{"topology": "aggregate"},
	))

	for _, invalid := range []runner.ConnectionConfig{
		nil,
		{"region": "cn"},
		{"topology": "secret"},
		{"topology": "deadbeef"},
		{"topology": "endpoint"},
		{"topology": "tool"},
		{"topology": "session"},
		{"topology": "aggregate", "session_id": "opaque"},
	} {
		require.Error(t, contract.Validate(invalid))
	}
	require.Error(t, (runner.ConnectionConfigContract{}).Validate(
		runner.ConnectionConfig{"topology": "aggregate"},
	))

	for _, invalid := range []runner.ConnectionConfigContract{
		{
			Fields: []runner.ConnectionConfigField{
				{Name: "Topology", Values: []string{"aggregate"}},
			},
		},
		{
			Fields: []runner.ConnectionConfigField{
				{Name: "topology"},
			},
		},
		{
			Fields: []runner.ConnectionConfigField{
				{Name: "topology", Values: []string{"aggregate", "aggregate"}},
			},
		},
		{
			Fields: []runner.ConnectionConfigField{
				{Name: "topology", Values: []string{"aggregate"}},
				{Name: "topology", Values: []string{"fallback"}},
			},
		},
		{
			Fields: []runner.ConnectionConfigField{
				{Name: "topology", Values: []string{"https://mcp.example.com"}},
			},
		},
	} {
		require.Error(t, invalid.ValidateSpec())
	}
}
