// Copyright 2026 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package executor

import (
	"fmt"
	"testing"

	"github.com/pingcap/tidb/pkg/ddl/label"
	"github.com/stretchr/testify/require"
	pd "github.com/tikv/pd/client/http"
)

func TestCheckRuleWithKeyspaceID(t *testing.T) {
	newRule := func(id string) *label.Rule {
		return &label.Rule{
			ID:       id,
			RuleType: "key-range",
			Labels:   []pd.RegionLabel{{Key: "region_policy", Value: "exclusive"}},
			Data: []any{
				map[string]any{
					"start_key": "aa",
					"end_key":   "bb",
				},
			},
		}
	}

	tests := []struct {
		name          string
		ruleID        string
		wantDB        string
		wantTable     string
		wantPartition string
	}{
		{
			name:      "non-keyspace table",
			ruleID:    fmt.Sprintf("%s/test/t1", label.IDPrefix),
			wantDB:    "test",
			wantTable: "t1",
		},
		{
			name:          "keyspace table",
			ruleID:        fmt.Sprintf("%s/42/%s/test/t2", label.KeyspacePrefix, label.IDPrefix),
			wantDB:        "test",
			wantTable:     "t2",
			wantPartition: "",
		},
		{
			name:          "keyspace partition",
			ruleID:        fmt.Sprintf("%s/42/%s/test/t3/p0", label.KeyspacePrefix, label.IDPrefix),
			wantDB:        "test",
			wantTable:     "t3",
			wantPartition: "p0",
		},
	}

	for _, tc := range tests {
		t.Run(tc.name, func(t *testing.T) {
			dbName, tableName, partitionName, err := checkRule(newRule(tc.ruleID))
			require.NoError(t, err)
			require.Equal(t, tc.wantDB, dbName)
			require.Equal(t, tc.wantTable, tableName)
			require.Equal(t, tc.wantPartition, partitionName)
		})
	}
}
