package persistence

import (
	"testing"

	"github.com/nexuscrm/kernel/pkg/schemacatalog"
)

const managedRowMutationColumnInspectionPattern = `SELECT COLUMN_NAME, LOWER\(COLUMN_TYPE\), IS_NULLABLE, COLUMN_DEFAULT, EXTRA[\s\S]*FROM INFORMATION_SCHEMA\.COLUMNS`
const managedRowMutationTableGenerationInspectionPattern = `SELECT COALESCE\(t\.TIDB_ROW_ID_SHARDING_INFO, ''\),[\s\S]*FROM INFORMATION_SCHEMA\.TABLES t`

func TestManagedRowMutationClassifierRejectsHalfKeys(t *testing.T) {
	policy := managedRowMutationProtection{
		fields: []schemacatalog.SystemTableRowMutationProtectionField{
			{FieldName: "CatalogNamespaceId", PhysicalName: "CatalogNamespaceId"},
			{FieldName: "CatalogLocalKey", PhysicalName: "CatalogLocalKey"},
		},
	}
	for _, tc := range []struct {
		name  string
		row   map[string]any
		state managedRowMutationState
	}{
		{
			name: "both null",
			row: map[string]any{
				"CatalogNamespaceId": nil,
				"CatalogLocalKey":    nil,
			},
			state: managedRowMutationMutable,
		},
		{
			name: "both non-null",
			row: map[string]any{
				"CatalogNamespaceId": []byte("namespace"),
				"CatalogLocalKey":    []byte("local"),
			},
			state: managedRowMutationAuthorityOwned,
		},
		{
			name: "empty bytes remain non-null",
			row: map[string]any{
				"CatalogNamespaceId": []byte{},
				"CatalogLocalKey":    []byte{},
			},
			state: managedRowMutationAuthorityOwned,
		},
		{
			name: "half key",
			row: map[string]any{
				"CatalogNamespaceId": []byte("namespace"),
				"CatalogLocalKey":    nil,
			},
			state: managedRowMutationCorrupt,
		},
	} {
		t.Run(tc.name, func(t *testing.T) {
			if got := policy.classify(tc.row); got != tc.state {
				t.Fatalf("classify() = %v, want %v", got, tc.state)
			}
		})
	}
}
