package sfcrmappservice

import (
	"context"
	"encoding/json"
	"net/http"
	"net/http/httptest"
	"reflect"
	"strings"
	"testing"
	"time"

	"github.com/pingcap-inc/nexuscrm-api-host/runtimegrpc"
	querycodec "github.com/pingcap-inc/nexuscrm-app-packs/sfcrm/querycodec"
	catalogsemantic "github.com/pingcap-inc/nexuscrm-contract/pkg/catalog/consumerv1"
	permissionsemantic "github.com/pingcap-inc/nexuscrm-contract/pkg/runtime/effectivepermissionsv1"
	querysemantic "github.com/pingcap-inc/nexuscrm-contract/pkg/runtime/queryv1"
	recordsemantic "github.com/pingcap-inc/nexuscrm-contract/pkg/runtime/recordaccessv1"
)

func TestQueryRouteUsesOneCoarseRuntimeCallAndPreservesCRMProjection(t *testing.T) {
	var gotBearer string
	var gotRequest querysemantic.Request
	id, name, empty, reference := "00Qlead", "Ada", "", "001parent"
	parentName := "Parent account"
	active := false
	count := int64(0)
	runtime := &fakeRuntime{response: recordsemantic.Response{Receipts: validReceipts()}}
	runtime.ready.Store(true)
	service, err := NewService(ServiceConfig{
		RuntimeEvaluate: runtime.Evaluate,
		RuntimeQuery: func(_ context.Context, bearer string, request querysemantic.Request) (querysemantic.Response, error) {
			gotBearer, gotRequest = bearer, request
			return querysemantic.Response{
				TotalSize: 1,
				Done:      true,
				Records: []querysemantic.Record{{ObjectID: "Lead", Fields: []querysemantic.Field{
					{Name: "Active", Value: querysemantic.Value{Kind: querysemantic.ValueBoolean, Boolean: &active}},
					{Name: "Amount", Value: querysemantic.Value{Kind: querysemantic.ValueDecimal, Decimal: &querysemantic.Decimal{Coefficient: "-1200", Scale: 2}}},
					{Name: "Count", Value: querysemantic.Value{Kind: querysemantic.ValueInteger, Integer: &count}},
					{Name: "Description", Value: querysemantic.Value{Kind: querysemantic.ValueString, Null: true}},
					{Name: "Empty", Value: querysemantic.Value{Kind: querysemantic.ValueString, String: &empty}},
					{Name: "Id", Value: querysemantic.Value{Kind: querysemantic.ValueReference, Reference: &id}},
					{Name: "Name", Value: querysemantic.Value{Kind: querysemantic.ValueString, String: &name}},
					{Name: "Parent", Value: querysemantic.Value{Kind: querysemantic.ValueObject, Object: &querysemantic.Record{ObjectID: "Account", Fields: []querysemantic.Field{
						{Name: "Id", Value: querysemantic.Value{Kind: querysemantic.ValueReference, Reference: &reference}},
						{Name: "Name", Value: querysemantic.Value{Kind: querysemantic.ValueString, String: &parentName}},
					}}}},
					{Name: "ParentId", Value: querysemantic.Value{Kind: querysemantic.ValueReference, Reference: &reference}},
				}}},
				Receipts: querysemantic.Receipts{ProtocolVersion: "1.0", CapabilityVersion: querysemantic.CapabilityName, CatalogRevision: 7, SchemaGeneration: 8, EngineGeneration: 9, SecurityEpoch: 5},
			}, nil
		},
		RuntimeHistoryQuery: func(context.Context, string, querysemantic.HistoryRequest) (querysemantic.HistoryResponse, error) {
			t.Fatal("normal query called history Runtime operation")
			return querysemantic.HistoryResponse{}, nil
		},
		RuntimeReadEffectivePermissions: func(context.Context, string, permissionsemantic.Request) (permissionsemantic.Response, error) {
			return validPermissionResponse(7, 5), nil
		},
		RuntimeGetAppMetadataViewV3: func(context.Context, catalogsemantic.GetRequest) (catalogsemantic.AppMetadataViewV3, error) {
			return permissionFixtureV3(validSearchScopeView(t, 7, 5))
		},
		RuntimeReady: runtime.Ready, RuntimeMetrics: runtime.Metrics,
		RequestTimeout: time.Second, MaxRequestBytes: 64 * 1024,
	})
	if err != nil {
		t.Fatal(err)
	}
	request := httptest.NewRequest(http.MethodGet, "/services/data/v63.0/query?q=SELECT+Name%2CAmount+FROM+Lead+WHERE+Active+%3D+false+LIMIT+2", nil)
	request.Header.Set("Authorization", "Bearer user-secret")
	recorder := httptest.NewRecorder()
	service.ServeHTTP(recorder, request)

	if recorder.Code != http.StatusOK {
		t.Fatalf("status=%d body=%s", recorder.Code, recorder.Body.String())
	}
	wantSelections := []querysemantic.Selection{{Kind: querysemantic.SelectionField, Field: "Name"}, {Kind: querysemantic.SelectionField, Field: "Amount"}}
	if gotBearer != "user-secret" || gotRequest.ObjectID != "Lead" || !reflect.DeepEqual(gotRequest.Selections, wantSelections) || gotRequest.Limit != 2 {
		t.Fatalf("bearer=%q request=%#v", gotBearer, gotRequest)
	}
	if strings.Count(recorder.Body.String(), `"Amount":-12.00`) != 1 {
		t.Fatalf("exact decimal projection lost: %s", recorder.Body.String())
	}
	var body map[string]any
	if err := json.Unmarshal(recorder.Body.Bytes(), &body); err != nil {
		t.Fatal(err)
	}
	records := body["records"].([]any)
	record := records[0].(map[string]any)
	if record["Active"] != false || record["Count"] != float64(0) || record["Empty"] != "" || record["Description"] != nil || record["ParentId"] != reference {
		t.Fatalf("typed projection=%#v", record)
	}
	parent, ok := record["Parent"].(map[string]any)
	if !ok || parent["Id"] != reference || parent["Name"] != parentName || parent["attributes"].(map[string]any)["type"] != "Account" {
		t.Fatalf("neutral relationship projection=%#v", record["Parent"])
	}
	if _, exists := record["FLSHidden"]; exists {
		t.Fatalf("omitted FLS field became observable: %#v", record)
	}
}

func TestToolingQueryRouteLowersToSameNeutralRuntimePort(t *testing.T) {
	var gotBearer string
	var gotRequest querysemantic.Request
	var gotPermissionRequest permissionsemantic.Request
	id, name := "0VR000000000001AAA", "BlockLead"
	runtime := &fakeRuntime{response: recordsemantic.Response{Receipts: validReceipts()}}
	runtime.ready.Store(true)
	service, err := NewService(ServiceConfig{
		RuntimeEvaluate: runtime.Evaluate,
		RuntimeQuery: func(_ context.Context, bearer string, request querysemantic.Request) (querysemantic.Response, error) {
			gotBearer, gotRequest = bearer, request
			return querysemantic.Response{
				TotalSize: 1,
				Done:      true,
				Records: []querysemantic.Record{{ObjectID: "_System_ValidationRule", Fields: []querysemantic.Field{
					{Name: "Id", Value: querysemantic.Value{Kind: querysemantic.ValueReference, Reference: &id}},
					{Name: "Name", Value: querysemantic.Value{Kind: querysemantic.ValueString, String: &name}},
				}}},
				Receipts: querysemantic.Receipts{ProtocolVersion: "1.0", CapabilityVersion: querysemantic.CapabilityName, CatalogRevision: 7, SchemaGeneration: 8, EngineGeneration: 9, SecurityEpoch: 5},
			}, nil
		},
		RuntimeHistoryQuery: func(context.Context, string, querysemantic.HistoryRequest) (querysemantic.HistoryResponse, error) {
			t.Fatal("Tooling query called history Runtime operation")
			return querysemantic.HistoryResponse{}, nil
		},
		RuntimeReadEffectivePermissions: func(_ context.Context, _ string, request permissionsemantic.Request) (permissionsemantic.Response, error) {
			gotPermissionRequest = request
			return validPermissionResponse(7, 5), nil
		},
		RuntimeGetAppMetadataViewV3: func(context.Context, catalogsemantic.GetRequest) (catalogsemantic.AppMetadataViewV3, error) {
			return permissionFixtureV3(validSearchScopeView(t, 7, 5))
		},
		RuntimeReady: runtime.Ready, RuntimeMetrics: runtime.Metrics,
		RequestTimeout: time.Second, MaxRequestBytes: 64 * 1024,
	})
	if err != nil {
		t.Fatal(err)
	}
	request := httptest.NewRequest(http.MethodGet, "/services/data/v63.0/tooling/query?q=SELECT+Id%2CValidationName+FROM+ValidationRule", nil)
	request.Header.Set("Authorization", "Bearer user-secret")
	recorder := httptest.NewRecorder()
	service.ServeHTTP(recorder, request)

	if recorder.Code != http.StatusOK {
		t.Fatalf("status=%d body=%s", recorder.Code, recorder.Body.String())
	}
	wantSelections := []querysemantic.Selection{{Kind: querysemantic.SelectionField, Field: "Id"}, {Kind: querysemantic.SelectionField, Field: "Name"}}
	if gotBearer != "user-secret" || gotRequest.ObjectID != "_System_ValidationRule" || !reflect.DeepEqual(gotRequest.Selections, wantSelections) {
		t.Fatalf("bearer=%q request=%#v", gotBearer, gotRequest)
	}
	if gotPermissionRequest.Selection == nil ||
		!reflect.DeepEqual(gotPermissionRequest.Selection.Sections, []permissionsemantic.Section{
			permissionsemantic.SectionSystemPermissions,
		}) || len(gotPermissionRequest.Selection.ResourceTypes) != 0 {
		t.Fatalf("tooling permission request=%#v", gotPermissionRequest)
	}
	want := `{"done":true,"records":[{"Id":"0VR000000000001AAA","Name":"BlockLead","attributes":{"type":"ValidationRule","url":"/services/data/v63.0/tooling/sobjects/ValidationRule/0VR000000000001AAA"}}],"totalSize":1}` + "\n"
	if recorder.Body.String() != want {
		t.Fatalf("body=%s\nwant=%s", recorder.Body.String(), want)
	}
}

func TestToolingQueryFailsClosedOnMissingPermissionOrMixedAuthority(t *testing.T) {
	for _, test := range []struct {
		name          string
		permission    permissionsemantic.Response
		queryRevision uint64
		wantStatus    int
		wantCalls     int
	}{
		{
			name: "missing setup permission",
			permission: func() permissionsemantic.Response {
				response := validPermissionResponse(7, 5)
				response.SystemPermissions = []permissionsemantic.PermissionGrant{
					{PermissionID: "CustomizeApplication", Granted: false},
					{PermissionID: "ViewSetup", Granted: false},
				}
				return response
			}(),
			queryRevision: 7,
			wantStatus:    http.StatusForbidden,
			wantCalls:     0,
		},
		{
			name:          "query authority changed after permission decision",
			permission:    validPermissionResponse(7, 5),
			queryRevision: 8,
			wantStatus:    http.StatusInternalServerError,
			wantCalls:     1,
		},
	} {
		t.Run(test.name, func(t *testing.T) {
			var queryCalls int
			id := "0VR000000000001AAA"
			runtime := &fakeRuntime{response: recordsemantic.Response{Receipts: validReceipts()}}
			runtime.ready.Store(true)
			service, err := NewService(ServiceConfig{
				RuntimeEvaluate: runtime.Evaluate,
				RuntimeQuery: func(context.Context, string, querysemantic.Request) (querysemantic.Response, error) {
					queryCalls++
					return querysemantic.Response{
						TotalSize: 1, Done: true,
						Records:  []querysemantic.Record{{ObjectID: "_System_ValidationRule", Fields: []querysemantic.Field{{Name: "Id", Value: querysemantic.Value{Kind: querysemantic.ValueReference, Reference: &id}}}}},
						Receipts: querysemantic.Receipts{ProtocolVersion: "1.0", CapabilityVersion: querysemantic.CapabilityName, CatalogRevision: test.queryRevision, SchemaGeneration: 8, EngineGeneration: 9, SecurityEpoch: 5},
					}, nil
				},
				RuntimeHistoryQuery: func(context.Context, string, querysemantic.HistoryRequest) (querysemantic.HistoryResponse, error) {
					return querysemantic.HistoryResponse{}, nil
				},
				RuntimeReadEffectivePermissions: func(context.Context, string, permissionsemantic.Request) (permissionsemantic.Response, error) {
					return test.permission, nil
				},
				RuntimeGetAppMetadataViewV3: func(context.Context, catalogsemantic.GetRequest) (catalogsemantic.AppMetadataViewV3, error) {
					return permissionFixtureV3(validSearchScopeView(t, 7, 5))
				},
				RuntimeReady: runtime.Ready, RuntimeMetrics: runtime.Metrics,
				RequestTimeout: time.Second, MaxRequestBytes: 64 * 1024,
			})
			if err != nil {
				t.Fatal(err)
			}
			request := httptest.NewRequest(http.MethodGet, "/services/data/v63.0/tooling/query?q=SELECT+Id+FROM+ValidationRule", nil)
			request.Header.Set("Authorization", "Bearer user-secret")
			recorder := httptest.NewRecorder()
			service.ServeHTTP(recorder, request)
			if recorder.Code != test.wantStatus || queryCalls != test.wantCalls {
				t.Fatalf("status=%d queryCalls=%d body=%s", recorder.Code, queryCalls, recorder.Body.String())
			}
		})
	}
}

func TestQueryValuePreservesAnonymousObjectAsOrdinaryJSON(t *testing.T) {
	falseValue := false
	zero := int64(0)
	empty := ""
	typeValue := "ordinary-value"
	value, err := queryValueFromSemantic(querysemantic.Value{
		Kind: querysemantic.ValueObject,
		Object: &querysemantic.Record{Fields: []querysemantic.Field{
			{Name: "", Value: querysemantic.Value{Kind: querysemantic.ValueString, Null: true}},
			{Name: "a-b", Value: querysemantic.Value{Kind: querysemantic.ValueBoolean, Boolean: &falseValue}},
			{Name: "attributes", Value: querysemantic.Value{Kind: querysemantic.ValueObject, Object: &querysemantic.Record{Fields: []querysemantic.Field{
				{Name: "type", Value: querysemantic.Value{Kind: querysemantic.ValueString, String: &typeValue}},
			}}}},
			{Name: "items", Value: querysemantic.Value{Kind: querysemantic.ValueList, List: &[]querysemantic.Value{
				{Kind: querysemantic.ValueInteger, Integer: &zero},
				{Kind: querysemantic.ValueString, String: &empty},
				{Kind: querysemantic.ValueString, Null: true},
			}}},
		}},
	})
	if err != nil {
		t.Fatal(err)
	}
	object, ok := value.(map[string]interface{})
	if !ok {
		t.Fatalf("anonymous object type = %T, want ordinary map", value)
	}
	if object[""] != nil || object["a-b"] != false {
		t.Fatalf("anonymous scalar projection = %#v", object)
	}
	attributes, ok := object["attributes"].(map[string]interface{})
	if !ok || attributes["type"] != typeValue {
		t.Fatalf("ordinary attributes key was interpreted as record metadata: %#v", object["attributes"])
	}
	items, ok := object["items"].([]any)
	if !ok || len(items) != 3 || items[0] != int64(0) || items[1] != "" || items[2] != nil {
		t.Fatalf("anonymous list projection = %#v", object["items"])
	}
}

func TestQueryAdapterRejectsInvalidSemanticBoundaryValues(t *testing.T) {
	t.Run("records request before Runtime", func(t *testing.T) {
		adapter := &RuntimeQueryAdapter{query: func(context.Context, string, querysemantic.Request) (querysemantic.Response, error) {
			t.Fatal("invalid records request reached Runtime")
			return querysemantic.Response{}, nil
		}}
		ctx, cancel := context.WithTimeout(withQueryBearer(context.Background(), "user-secret"), time.Second)
		defer cancel()
		_, err := adapter.queryRecords(ctx, querycodec.QueryRequest{ObjectAPIName: "bad-name", SelectFields: []string{"Id"}}, 0)
		if err == nil {
			t.Fatal("invalid records request was accepted")
		}
	})

	t.Run("records response before projection", func(t *testing.T) {
		adapter := &RuntimeQueryAdapter{query: func(context.Context, string, querysemantic.Request) (querysemantic.Response, error) {
			return querysemantic.Response{
				Done: true,
				Records: []querysemantic.Record{{ObjectID: "Lead", Fields: []querysemantic.Field{{
					Name: "Amount", Value: querysemantic.Value{Kind: querysemantic.ValueDecimal, Decimal: &querysemantic.Decimal{Coefficient: "1", Scale: querysemantic.MaxSemanticResponseBytes}},
				}}}},
				Receipts: querysemantic.Receipts{ProtocolVersion: "1.0", CapabilityVersion: querysemantic.CapabilityName},
			}, nil
		}}
		ctx, cancel := context.WithTimeout(withQueryBearer(context.Background(), "user-secret"), time.Second)
		defer cancel()
		_, err := adapter.queryRecords(ctx, querycodec.QueryRequest{ObjectAPIName: "Lead", SelectFields: []string{"Amount"}}, 0)
		if err == nil {
			t.Fatal("oversized decimal response reached CRM projection")
		}
	})

	t.Run("history request before Runtime", func(t *testing.T) {
		adapter := &RuntimeQueryAdapter{history: func(context.Context, string, querysemantic.HistoryRequest) (querysemantic.HistoryResponse, error) {
			t.Fatal("invalid history request reached Runtime")
			return querysemantic.HistoryResponse{}, nil
		}}
		ctx, cancel := context.WithTimeout(withQueryBearer(context.Background(), "user-secret"), time.Second)
		defer cancel()
		_, err := adapter.queryHistory(ctx, querycodec.HistoryRequest{ParentObjectAPIName: "bad-name", SelectFields: []string{"Id"}})
		if err == nil {
			t.Fatal("invalid history request was accepted")
		}
	})

	t.Run("history response before projection", func(t *testing.T) {
		adapter := &RuntimeQueryAdapter{history: func(context.Context, string, querysemantic.HistoryRequest) (querysemantic.HistoryResponse, error) {
			return querysemantic.HistoryResponse{
				Done:     true,
				Rows:     []querysemantic.HistoryRow{{ID: "history\n1", ParentID: "001parent", Field: "Name", DataType: "string", CreatedDate: "2026-06-24T10:00:00Z", CreatedByID: "005user"}},
				Receipts: querysemantic.Receipts{ProtocolVersion: "1.0", CapabilityVersion: querysemantic.CapabilityName},
			}, nil
		}}
		ctx, cancel := context.WithTimeout(withQueryBearer(context.Background(), "user-secret"), time.Second)
		defer cancel()
		_, err := adapter.queryHistory(ctx, querycodec.HistoryRequest{ParentObjectAPIName: "Account", ParentID: "001parent", SelectFields: []string{"Id"}})
		if err == nil {
			t.Fatal("invalid history response reached CRM projection")
		}
	})
}

func TestQueryAllAndQueryMorePreserveDeletedVisibilityWithOneRuntimeCallPerPage(t *testing.T) {
	var requests []querysemantic.Request
	runtime := &fakeRuntime{response: recordsemantic.Response{Receipts: validReceipts()}}
	runtime.ready.Store(true)
	service, err := NewService(ServiceConfig{
		RuntimeEvaluate: runtime.Evaluate,
		RuntimeQuery: func(_ context.Context, bearer string, request querysemantic.Request) (querysemantic.Response, error) {
			if bearer != "user-secret" {
				t.Fatalf("bearer=%q", bearer)
			}
			requests = append(requests, request)
			id := "I-" + string(rune('0'+len(requests)))
			return querysemantic.Response{
				TotalSize: 2,
				Done:      len(requests) == 2,
				Records: []querysemantic.Record{{ObjectID: "Issue", Fields: []querysemantic.Field{
					{Name: "Id", Value: querysemantic.Value{Kind: querysemantic.ValueReference, Reference: &id}},
				}}},
				Receipts: querysemantic.Receipts{ProtocolVersion: "1.0", CapabilityVersion: querysemantic.CapabilityName, CatalogRevision: 7},
			}, nil
		},
		RuntimeHistoryQuery: func(context.Context, string, querysemantic.HistoryRequest) (querysemantic.HistoryResponse, error) {
			t.Fatal("queryAll called history Runtime operation")
			return querysemantic.HistoryResponse{}, nil
		},
		RuntimeReady: runtime.Ready, RuntimeMetrics: runtime.Metrics,
		RequestTimeout: time.Second, MaxRequestBytes: 64 * 1024,
	})
	if err != nil {
		t.Fatal(err)
	}

	request := httptest.NewRequest(http.MethodGet, "/services/data/v63.0/queryAll?q=SELECT+Id+FROM+Issue", nil)
	request.Header.Set("Authorization", "Bearer user-secret")
	recorder := httptest.NewRecorder()
	service.ServeHTTP(recorder, request)
	if recorder.Code != http.StatusOK || len(requests) != 1 || !requests[0].IncludeDeleted {
		t.Fatalf("first page status=%d requests=%#v body=%s", recorder.Code, requests, recorder.Body.String())
	}
	var firstPage struct {
		NextRecordsURL string `json:"nextRecordsUrl"`
	}
	if err := json.Unmarshal(recorder.Body.Bytes(), &firstPage); err != nil || firstPage.NextRecordsURL == "" {
		t.Fatalf("first page locator=%q err=%v body=%s", firstPage.NextRecordsURL, err, recorder.Body.String())
	}

	request = httptest.NewRequest(http.MethodGet, firstPage.NextRecordsURL, nil)
	request.Header.Set("Authorization", "Bearer user-secret")
	recorder = httptest.NewRecorder()
	service.ServeHTTP(recorder, request)
	if recorder.Code != http.StatusOK || len(requests) != 2 || !requests[1].IncludeDeleted {
		t.Fatalf("second page status=%d requests=%#v body=%s", recorder.Code, requests, recorder.Body.String())
	}
}

func TestHistoryBranchUsesSameQueryCapabilityWithoutFallback(t *testing.T) {
	var normalCalls, historyCalls int
	var got querysemantic.HistoryRequest
	runtime := &fakeRuntime{response: recordsemantic.Response{Receipts: validReceipts()}}
	runtime.ready.Store(true)
	service, err := NewService(ServiceConfig{
		RuntimeEvaluate: runtime.Evaluate,
		RuntimeQuery: func(context.Context, string, querysemantic.Request) (querysemantic.Response, error) {
			normalCalls++
			return querysemantic.Response{}, nil
		},
		RuntimeHistoryQuery: func(_ context.Context, bearer string, request querysemantic.HistoryRequest) (querysemantic.HistoryResponse, error) {
			historyCalls++
			got = request
			if bearer != "user-secret" {
				t.Fatalf("bearer=%q", bearer)
			}
			return querysemantic.HistoryResponse{TotalSize: 1, Done: true, Rows: []querysemantic.HistoryRow{{
				ID: "017hist", ParentID: "001parent", Field: "Name", DataType: "string",
				CreatedDate: "2026-06-24T10:00:00.000Z", CreatedByID: "005user",
			}}, Receipts: querysemantic.Receipts{ProtocolVersion: "1.0", CapabilityVersion: querysemantic.CapabilityName, CatalogRevision: 7}}, nil
		},
		RuntimeReady: runtime.Ready, RuntimeMetrics: func() runtimegrpc.RuntimeClientMetrics { return runtime.Metrics() },
		RequestTimeout: time.Second, MaxRequestBytes: 64 * 1024,
	})
	if err != nil {
		t.Fatal(err)
	}
	request := httptest.NewRequest(http.MethodGet, "/services/data/v63.0/query?q=SELECT+Id%2CField%2CCreatedDate%2CCreatedById+FROM+AccountHistory+WHERE+AccountId+%3D+%27001parent%27+LIMIT+5", nil)
	request.Header.Set("Authorization", "Bearer user-secret")
	recorder := httptest.NewRecorder()
	service.ServeHTTP(recorder, request)

	if recorder.Code != http.StatusOK || normalCalls != 0 || historyCalls != 1 {
		t.Fatalf("status=%d normal=%d history=%d body=%s", recorder.Code, normalCalls, historyCalls, recorder.Body.String())
	}
	if got.ParentObjectID != "Account" || got.ParentRecordID != "001parent" || got.Limit != 5 {
		t.Fatalf("history request=%#v", got)
	}
}

func TestQueryLoweringProducesClosedTypedPlan(t *testing.T) {
	request := querycodec.QueryRequest{
		ObjectAPIName: "Opportunity",
		SelectFields:  []string{"Owner.Name", "SUM(Amount) total"},
		Filter: querycodec.ComparisonPredicate(
			querycodec.FieldOperand("Amount"),
			">",
			querycodec.RawOperand("12345678901234567890.1200"),
		),
		OrderBy: []querycodec.SortCriterion{{Field: "Owner.Name", Direction: "DESC"}},
		GroupBy: "Owner.Name",
		Limit:   50,
	}
	got, err := queryRequestToSemantic(request, 0)
	if err != nil {
		t.Fatal(err)
	}
	if len(got.Selections) != 2 || got.Selections[1] != (querysemantic.Selection{Kind: querysemantic.SelectionAggregate, Aggregate: querysemantic.AggregateSum, Field: "Amount", Alias: "total"}) {
		t.Fatalf("selections=%#v", got.Selections)
	}
	if got.Filter.Operator != querysemantic.ComparisonGreaterThan || got.Filter.Right.Literal == nil || got.Filter.Right.Literal.Decimal == nil ||
		got.Filter.Right.Literal.Decimal.Coefficient != "123456789012345678901200" || got.Filter.Right.Literal.Decimal.Scale != 4 {
		t.Fatalf("exact predicate=%#v", got.Filter)
	}
	if len(got.OrderBy) != 1 || got.OrderBy[0].Direction != querysemantic.SortDescending {
		t.Fatalf("order=%#v", got.OrderBy)
	}

	request.Filter = querycodec.ExpressionPredicate(querycodec.RawOperand("Amount > 0"))
	if _, err := queryRequestToSemantic(request, 0); err == nil {
		t.Fatal("opaque formula predicate crossed the Runtime boundary")
	}
	request.Filter = querycodec.ComparisonPredicate(querycodec.FieldOperand("Amount"), ">", querycodec.RawOperand("1 OR true"))
	if _, err := queryRequestToSemantic(request, 0); err == nil {
		t.Fatal("non-numeric raw operand crossed the Runtime boundary")
	}
}

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

	tests := []struct {
		name     string
		query    string
		wantDate string
		wantTime string
		wantText string
	}{
		{name: "date", query: "SELECT Id FROM Opportunity WHERE CloseDate = 2026-07-20", wantDate: "2026-07-20"},
		{name: "datetime", query: "SELECT Id FROM Opportunity WHERE CreatedDate >= 2026-07-20T14:34:56.789+02:00", wantTime: "2026-07-20T12:34:56.789Z"},
		{name: "quoted date-shaped string", query: "SELECT Id FROM Opportunity WHERE Name = '2026-07-20'", wantText: "2026-07-20"},
	}
	for _, test := range tests {
		test := test
		t.Run(test.name, func(t *testing.T) {
			t.Parallel()
			parsed, err := querycodec.ParseSOQL(test.query)
			if err != nil {
				t.Fatalf("ParseSOQL() error = %v", err)
			}
			request, err := queryRequestToSemantic(*parsed, 0)
			if err != nil {
				t.Fatalf("queryRequestToSemantic() error = %v", err)
			}
			validationContext, cancel := context.WithTimeout(context.Background(), time.Second)
			defer cancel()
			if err := querysemantic.ValidateRequest(validationContext, request); err != nil {
				t.Fatalf("ValidateRequest() error = %v", err)
			}
			if request.Filter.Right.Literal == nil {
				t.Fatalf("filter = %#v, want typed literal", request.Filter)
			}
			literal := request.Filter.Right.Literal
			switch {
			case test.wantDate != "":
				if literal.Date == nil || *literal.Date != test.wantDate || literal.DateTime != nil || literal.String != nil {
					t.Fatalf("literal = %#v, want date %q only", literal, test.wantDate)
				}
			case test.wantTime != "":
				if literal.DateTime == nil || *literal.DateTime != test.wantTime || literal.Date != nil || literal.String != nil {
					t.Fatalf("literal = %#v, want datetime %q only", literal, test.wantTime)
				}
			case test.wantText != "":
				if literal.String == nil || *literal.String != test.wantText || literal.Date != nil || literal.DateTime != nil {
					t.Fatalf("literal = %#v, want string %q only", literal, test.wantText)
				}
			}
		})
	}
}

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

	adapter := &RuntimeQueryAdapter{history: func(context.Context, string, querysemantic.HistoryRequest) (querysemantic.HistoryResponse, error) {
		t.Fatal("invalid history window reached Runtime")
		return querysemantic.HistoryResponse{}, nil
	}}
	ctx := withQueryBearer(context.Background(), "bearer")
	tests := []struct {
		name    string
		request querycodec.HistoryRequest
	}{
		{name: "negative limit", request: querycodec.HistoryRequest{Limit: -1}},
		{name: "oversized limit", request: querycodec.HistoryRequest{Limit: querysemantic.MaxHistoryRows + 1}},
		{name: "negative offset", request: querycodec.HistoryRequest{Offset: -1}},
		{name: "oversized offset", request: querycodec.HistoryRequest{Offset: querysemantic.MaxOffset + 1}},
		{name: "negative page size", request: querycodec.HistoryRequest{PageSize: -1}},
		{name: "oversized page size", request: querycodec.HistoryRequest{PageSize: querysemantic.MaxHistoryRows + 1}},
		{name: "negative cursor offset", request: querycodec.HistoryRequest{CursorOffset: -1}},
		{name: "oversized cursor offset", request: querycodec.HistoryRequest{CursorOffset: querysemantic.MaxOffset + 1}},
	}
	for _, test := range tests {
		test := test
		t.Run(test.name, func(t *testing.T) {
			t.Parallel()
			if _, err := adapter.queryHistory(ctx, test.request); err == nil {
				t.Fatal("queryHistory() error = nil, want invalid query")
			}
		})
	}
}
