package dialectsfcrm

import (
	"reflect"
	"testing"

	querycodec "github.com/pingcap-inc/nexuscrm-app-packs/sfcrm/querycodec"
)

func TestRuntimeQueryRoutesAreOwnedOnceByTheDialect(t *testing.T) {
	partition := NewCompositeTreePartition()
	manifest := partition.Manifest()
	for _, route := range runtimeQueryRoutes() {
		matches := 0
		for _, declared := range manifest {
			if declared.Method == route.Method && declared.Path == route.Path &&
				reflect.ValueOf(declared.Handler).Pointer() == reflect.ValueOf(route.Handler).Pointer() {
				matches++
			}
		}
		if matches != 1 {
			t.Fatalf("query route %s %s occurs %d times in dialect manifest, want exactly one", route.Method, route.Path, matches)
		}
	}

	for _, version := range partition.Versions() {
		for _, test := range []struct {
			path    string
			locator string
		}{
			{path: "/query"},
			{path: "/queryAll"},
			{path: "/query/cursor-1", locator: "cursor-1"},
		} {
			match, ok := querycodec.Match(partition.BasePath() + "/" + version + test.path)
			if !ok || match.Version != version || match.Locator != test.locator {
				t.Fatalf("querycodec.Match(%s%s) = %#v, %t", version, test.path, match, ok)
			}
		}
	}
}

func TestRuntimeQueryRouteMatcherRejectsUndeclaredCRMGrammar(t *testing.T) {
	for _, path := range []string{
		"/services/data/v58.0/query",
		"/services/data/v63.0/query/",
		"/services/data/v63.0/search",
		"/services/data/v63.0/query/cursor/extra",
	} {
		if match, ok := querycodec.Match(path); ok {
			t.Fatalf("querycodec.Match(%q) = %#v, true; want rejected", path, match)
		}
	}
}
