package persistence

import "testing"

// The physical index is the oracle. These are deliberately arbitrary fixture
// indexes, not copies of any system catalog definition.
func TestVerifyExactTableIndexTiDBRejectsIncompatibleIndexes(t *testing.T) {
	db, cleanup := openSessionRepositoryTiDB(t)
	defer cleanup()
	_, err := db.Exec(`CREATE TABLE IndexProbe (
  Id BIGINT PRIMARY KEY,
  FirstValue VARCHAR(128),
  SecondValue VARCHAR(128),
  UNIQUE KEY exact_unique (FirstValue, SecondValue),
  KEY exact_nonunique (FirstValue, SecondValue),
  KEY prefix_first (FirstValue(8), SecondValue),
  KEY prefix_second (FirstValue, SecondValue(8))
)`)
	if err != nil {
		t.Fatal(err)
	}
	for _, tc := range []struct {
		name    string
		index   string
		unique  bool
		columns []string
		valid   bool
	}{
		{"primary", "PRIMARY", true, []string{"Id"}, true},
		{"unique", "exact_unique", true, []string{"FirstValue", "SecondValue"}, true},
		{"nonunique", "exact_nonunique", false, []string{"FirstValue", "SecondValue"}, true},
		{"case insensitive", "exact_unique", true, []string{"firstvalue", "SECONDVALUE"}, true},
		{"missing", "missing_index", false, []string{"FirstValue"}, false},
		{"wrong uniqueness", "exact_nonunique", true, []string{"FirstValue", "SecondValue"}, false},
		{"wrong order", "exact_unique", true, []string{"SecondValue", "FirstValue"}, false},
		{"extra column", "exact_unique", true, []string{"FirstValue"}, false},
		{"missing column", "exact_unique", true, []string{"FirstValue", "SecondValue", "Id"}, false},
		{"prefix first", "prefix_first", false, []string{"FirstValue", "SecondValue"}, false},
		{"prefix second", "prefix_second", false, []string{"FirstValue", "SecondValue"}, false},
	} {
		t.Run(tc.name, func(t *testing.T) {
			err := VerifyExactTableIndex(t.Context(), db, "IndexProbe", tc.index, tc.unique, tc.columns)
			if (err == nil) != tc.valid {
				t.Fatalf("VerifyExactTableIndex = %v, want valid=%v", err, tc.valid)
			}
		})
	}
}
