package runtimeapi

import (
	"context"
	"errors"
	"testing"
	"time"

	"github.com/nexuscrm/analytics"
	appErrors "github.com/nexuscrm/kernel/pkg/errors"
	"github.com/nexuscrm/kernel/pkg/formula"
	"github.com/nexuscrm/metadata/catalogsnapshot"
	"github.com/nexuscrm/permissions"
	"github.com/nexuscrm/shared/pkg/constants"
	"github.com/nexuscrm/shared/pkg/contract"
	"github.com/nexuscrm/shared/pkg/models"
	"github.com/nexuscrm/shared/pkg/queryspec"
	"github.com/nexuscrm/shared/pkg/referenceidentity"
	delegation "github.com/pingcap-inc/nexuscrm-contract/pkg/runtime/delegationv1"
	semantic "github.com/pingcap-inc/nexuscrm-contract/pkg/runtime/queryv1"
	"github.com/pingcap-inc/nexuscrm-contract/wire-go/mapping"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
)

func TestQueryPredicateMappingPreservesClosedEngineKinds(t *testing.T) {
	value := "open"
	request := semantic.Request{
		ObjectID: "WorkItem",
		Selections: []semantic.Selection{
			{Kind: semantic.SelectionField, Field: "Id"},
			{Kind: semantic.SelectionAggregate, Aggregate: semantic.AggregateCount, Field: "Id", Alias: "total"},
		},
		OrderBy: []semantic.Sort{{Field: "Status", Direction: semantic.SortDescending}},
		Filter:  semantic.Predicate{Kind: semantic.PredicateFieldComparison, Field: "Status", Operator: semantic.ComparisonEqual, Value: &semantic.Scalar{String: &value}},
	}

	spec, err := querySpecFromSemantic(request)
	if err != nil {
		t.Fatal(err)
	}
	if spec.Filter.Kind != queryspec.PredicateFieldComparison || spec.Filter.Field != "Status" || spec.Filter.Op != "==" {
		t.Fatalf("mapped predicate = %#v", spec.Filter)
	}
	if len(spec.SelectFields) != 2 || spec.SelectFields[1] != "COUNT(Id) total" {
		t.Fatalf("mapped selections = %#v", spec.SelectFields)
	}
	if spec.SortField != "Status" || spec.SortDirection != "DESC" || len(spec.OrderBy) != 1 {
		t.Fatalf("mapped sort = %#v / %q %q", spec.OrderBy, spec.SortField, spec.SortDirection)
	}
}

func TestQueryLikePredicatesInsideOrCompileThroughResidualExecution(t *testing.T) {
	active := true
	pattern := "%Record.Link%"
	comparison := func(field string) semantic.Predicate {
		return semantic.Predicate{
			Kind:     semantic.PredicateComparison,
			Operator: semantic.ComparisonLike,
			Left:     semantic.Operand{Kind: semantic.OperandField, Field: field},
			Right: semantic.Operand{
				Kind:    semantic.OperandLiteral,
				Literal: &semantic.Scalar{String: &pattern},
			},
		}
	}
	request := semantic.Request{
		ObjectID:   "_System_EmailTemplate",
		Selections: []semantic.Selection{{Kind: semantic.SelectionField, Field: "Id"}},
		Filter: semantic.Predicate{Kind: semantic.PredicateAnd, Children: []semantic.Predicate{
			{
				Kind:     semantic.PredicateComparison,
				Operator: semantic.ComparisonEqual,
				Left:     semantic.Operand{Kind: semantic.OperandField, Field: "IsActive"},
				Right: semantic.Operand{
					Kind:    semantic.OperandLiteral,
					Literal: &semantic.Scalar{Boolean: &active},
				},
			},
			{Kind: semantic.PredicateOr, Children: []semantic.Predicate{
				comparison("Body"),
				comparison("HtmlValue"),
			}},
		}},
	}

	spec, err := querySpecFromSemantic(request)
	if err != nil {
		t.Fatalf("querySpecFromSemantic() error = %v", err)
	}
	lowering, err := queryspec.LowerPredicate(spec.Filter, queryspec.PredicateLoweringPreferCriteria)
	if err != nil {
		t.Fatalf("LowerPredicate() error = %v", err)
	}
	if len(lowering.Criteria) != 1 || lowering.Criteria[0] != (queryspec.QueryCriterion{Field: "IsActive", Op: "=", Val: true}) {
		t.Fatalf("LowerPredicate().Criteria = %#v", lowering.Criteria)
	}
	sql, args, err := formula.ToSQLWithMapper(lowering.Expression, func(identifier string) string {
		return "`" + identifier + "`"
	})
	if err != nil {
		t.Fatalf("residual LIKE expression did not compile: %v", err)
	}
	if want := "((`Body` LIKE ?) OR (`HtmlValue` LIKE ?))"; sql != want {
		t.Fatalf("residual LIKE SQL = %q, want %q", sql, want)
	}
	if len(args) != 2 || args[0] != pattern || args[1] != pattern {
		t.Fatalf("residual LIKE args = %#v", args)
	}
}

func TestQueryPlanOnlyMapsProvenExecutableFunctions(t *testing.T) {
	field := func(name string) semantic.Operand {
		return semantic.Operand{Kind: semantic.OperandField, Field: name}
	}
	literal := func(value string) semantic.Operand {
		return semantic.Operand{Kind: semantic.OperandLiteral, Literal: &semantic.Scalar{String: &value}}
	}
	functions := []struct {
		name          string
		operand       semantic.Operand
		havingAllowed bool
	}{
		{name: "count", operand: semantic.Operand{Kind: semantic.OperandFunction, Function: semantic.FunctionCount, Args: []semantic.Operand{field("Id")}}, havingAllowed: true},
		{name: "count distinct", operand: semantic.Operand{Kind: semantic.OperandFunction, Function: semantic.FunctionCountDistinct, Args: []semantic.Operand{field("Id")}}},
		{name: "sum", operand: semantic.Operand{Kind: semantic.OperandFunction, Function: semantic.FunctionSum, Args: []semantic.Operand{field("Amount")}}, havingAllowed: true},
		{name: "average", operand: semantic.Operand{Kind: semantic.OperandFunction, Function: semantic.FunctionAverage, Args: []semantic.Operand{field("Amount")}}, havingAllowed: true},
		{name: "minimum", operand: semantic.Operand{Kind: semantic.OperandFunction, Function: semantic.FunctionMinimum, Args: []semantic.Operand{field("Amount")}}, havingAllowed: true},
		{name: "maximum", operand: semantic.Operand{Kind: semantic.OperandFunction, Function: semantic.FunctionMaximum, Args: []semantic.Operand{field("Amount")}}, havingAllowed: true},
		{name: "string", operand: semantic.Operand{Kind: semantic.OperandFunction, Function: semantic.FunctionString, Args: []semantic.Operand{field("Amount")}}},
		{name: "format", operand: semantic.Operand{Kind: semantic.OperandFunction, Function: semantic.FunctionFormat, Args: []semantic.Operand{field("Amount")}}},
		{name: "display value", operand: semantic.Operand{Kind: semantic.OperandFunction, Function: semantic.FunctionDisplayValue, Args: []semantic.Operand{field("Status")}}},
		{name: "normalize currency", operand: semantic.Operand{Kind: semantic.OperandFunction, Function: semantic.FunctionNormalizeCurrency, Args: []semantic.Operand{field("Amount")}}},
		{name: "grouping", operand: semantic.Operand{Kind: semantic.OperandFunction, Function: semantic.FunctionGrouping, Args: []semantic.Operand{field("Status")}}},
		{name: "temporal", operand: semantic.Operand{Kind: semantic.OperandFunction, Function: semantic.FunctionTemporalPart, TemporalBasis: semantic.TemporalBasisCivil, TemporalPart: semantic.TemporalPartDate, Args: []semantic.Operand{field("CreatedDate")}}},
		{name: "geo distance", operand: semantic.Operand{Kind: semantic.OperandFunction, Function: semantic.FunctionGeoDistance, DistanceUnit: semantic.DistanceUnitMiles, Args: []semantic.Operand{field("Location"), field("Target")}}},
		{name: "geo point", operand: semantic.Operand{Kind: semantic.OperandFunction, Function: semantic.FunctionGeoPoint, Args: []semantic.Operand{literal("1"), literal("2")}}},
	}
	one := int64(1)
	for _, tt := range functions {
		t.Run(tt.name, func(t *testing.T) {
			predicate := semantic.Predicate{
				Kind: semantic.PredicateComparison, Operator: semantic.ComparisonGreaterThan,
				Left: tt.operand, Right: semantic.Operand{Kind: semantic.OperandLiteral, Literal: &semantic.Scalar{Integer: &one}},
			}
			request := semantic.Request{ObjectID: "WorkItem", Selections: []semantic.Selection{{Kind: semantic.SelectionField, Field: "Id"}}, Filter: predicate}
			if _, err := querySpecFromSemantic(request); !isInvalidQueryPlan(err) {
				t.Fatalf("filter error = %#v, want typed invalid query plan", err)
			}

			request.Filter = semantic.Predicate{}
			request.Having = predicate
			spec, err := querySpecFromSemantic(request)
			if !tt.havingAllowed {
				if !isInvalidQueryPlan(err) {
					t.Fatalf("having error = %#v, want typed invalid query plan", err)
				}
				return
			}
			if err != nil {
				t.Fatalf("executable aggregate HAVING rejected: %v", err)
			}
			lowered, err := queryspec.LowerPredicate(spec.Having, queryspec.PredicateLoweringExpressionOnly)
			if err != nil || lowered.Expression == "" {
				t.Fatalf("mapped HAVING = %#v, error = %v", spec.Having, err)
			}
		})
	}
}

func TestQueryPlanRejectsUnexecutableAggregateShapes(t *testing.T) {
	one := int64(1)
	invalidFunctions := []semantic.Operand{
		{Kind: semantic.OperandFunction, Function: semantic.FunctionCount},
		{Kind: semantic.OperandFunction, Function: semantic.FunctionCount, Args: []semantic.Operand{{Kind: semantic.OperandLiteral, Literal: &semantic.Scalar{Integer: &one}}}},
		{Kind: semantic.OperandFunction, Function: semantic.FunctionCount, Args: []semantic.Operand{{Kind: semantic.OperandField, Field: "Id"}, {Kind: semantic.OperandField, Field: "OwnerId"}}},
	}
	for _, function := range invalidFunctions {
		request := semantic.Request{
			ObjectID: "WorkItem", Selections: []semantic.Selection{{Kind: semantic.SelectionField, Field: "Id"}},
			Having: semantic.Predicate{Kind: semantic.PredicateComparison, Operator: semantic.ComparisonGreaterThan, Left: function, Right: semantic.Operand{Kind: semantic.OperandLiteral, Literal: &semantic.Scalar{Integer: &one}}},
		}
		if _, err := querySpecFromSemantic(request); !isInvalidQueryPlan(err) {
			t.Fatalf("invalid aggregate shape %#v error = %#v, want typed invalid query plan", function, err)
		}
	}
}

func isInvalidQueryPlan(err error) bool {
	var failure *semantic.Failure
	return errors.As(err, &failure) && failure.Category == semantic.FailureInvalidRequest &&
		failure.InvalidComponent == semantic.InvalidComponentQueryPlan
}

func TestQueryPredicateMappingRejectsUnknownKinds(t *testing.T) {
	if _, err := queryPredicateFromSemantic(semantic.Predicate{Kind: "FUTURE"}); err == nil {
		t.Fatal("unknown predicate kind was admitted")
	}
	if _, err := queryOperandFromSemantic(semantic.Operand{Kind: "FUTURE"}); err == nil {
		t.Fatal("unknown operand kind was admitted")
	}
}

func TestQueryRecordsResolvesTrustedPrincipalBeforeEngineAccess(t *testing.T) {
	engine := &queryServerTestEngine{queryResult: &models.QueryResult{Done: true}}
	server, err := NewQueryServer(engine, nil, nil)
	if err != nil {
		t.Fatal(err)
	}
	ctx, cancel := context.WithTimeout(context.Background(), time.Second)
	defer cancel()
	trusted := newTrustedCall(delegation.Claims{
		DelegationID: "delegation-query-test", OrgID: "org-query-test", PrincipalID: "trusted-user",
		SessionID: "session-query-test", CallerWorkloadID: "appservice-query-test",
		AppInstallationID: "installation-query-test", RuntimeAudience: "runtime-query-test",
		Capabilities: []string{semantic.CapabilityName}, AuthEpoch: 1, SecurityEpoch: 1,
	}, models.UserSession{ID: "trusted-user"})
	ctx = context.WithValue(ctx, trustedCallContextKey{}, trusted)
	ctx = context.WithValue(ctx, runtimeExecutionScopeContextKey{}, RuntimeExecutionScope{
		view: queryResponseTestView(t), receipts: semantic.Receipts{
			ProtocolVersion: "1.0", CapabilityVersion: semantic.CapabilityName,
			CatalogRevision: 1, SecurityEpoch: 1,
		},
	})
	wireRequest, err := mapping.ToWireQueryRecordsRequest(ctx, semantic.Request{
		ObjectID: "WorkItem", Selections: []semantic.Selection{{Kind: semantic.SelectionField, Field: constants.FieldID}},
		Filter: semantic.Predicate{
			Kind: semantic.PredicateComparison, Operator: semantic.ComparisonEqual,
			Left:  semantic.Operand{Kind: semantic.OperandField, Field: "OwnerId"},
			Right: semantic.Operand{Kind: semantic.OperandTrustedContext, TrustedContext: semantic.TrustedContextPrincipalID},
		},
	})
	if err != nil {
		t.Fatal(err)
	}
	if _, err := server.QueryRecords(ctx, wireRequest); err != nil {
		t.Fatal(err)
	}
	if engine.queryCalls != 1 || engine.lastUserID != "trusted-user" {
		t.Fatalf("engine calls=%d user=%q, want one trusted-user call", engine.queryCalls, engine.lastUserID)
	}
	if got := engine.lastSpec.Filter.Right; got.Kind != queryspec.OperandLiteral || got.Value != "trusted-user" {
		t.Fatalf("resolved trusted principal = %#v, want trusted-user literal", got)
	}

	if _, err := querySpecFromSemantic(semantic.Request{
		ObjectID: "WorkItem", Selections: []semantic.Selection{{Kind: semantic.SelectionField, Field: constants.FieldID}},
		Filter: semantic.Predicate{
			Kind: semantic.PredicateComparison, Operator: semantic.ComparisonEqual,
			Left:  semantic.Operand{Kind: semantic.OperandField, Field: "OwnerId"},
			Right: semantic.Operand{Kind: semantic.OperandTrustedContext, TrustedContext: semantic.TrustedContextPrincipalID},
		},
	}); err == nil {
		t.Fatal("trusted principal query was lowered without TrustedCall authority")
	}
}

func TestQueryRecordsBindsRecordQueryReferenceIdentityAuthority(t *testing.T) {
	view := approvalAuthorityTestView(t, semantic.CapabilityName)
	engine := &queryServerTestEngine{
		queryResult:   &models.QueryResult{TotalSize: 1, Done: true, Records: []models.SObject{{constants.FieldID: "work-1"}}},
		resolveObject: constants.TableProcessDefinition,
		resolveID:     approvalTestDefinitionID,
	}
	server, err := NewQueryServer(engine, nil, nil)
	if err != nil {
		t.Fatal(err)
	}
	trusted := newTrustedCall(delegation.Claims{
		DelegationID: "delegation-query-identity", OrgID: "org-approval-test", PrincipalID: "trusted-user",
		SessionID: "session-query-identity", CallerWorkloadID: "appservice-query-test",
		AppInstallationID: approvalTestInstallation, RuntimeAudience: "runtime-query-test",
		Capabilities: []string{semantic.CapabilityName}, AuthEpoch: 1, SecurityEpoch: 1,
	}, models.UserSession{ID: "trusted-user"})
	ctx, cancel := context.WithTimeout(context.Background(), time.Second)
	defer cancel()
	ctx = context.WithValue(ctx, trustedCallContextKey{}, trusted)
	ctx = context.WithValue(ctx, runtimeExecutionScopeContextKey{}, RuntimeExecutionScope{
		view: view, receipts: semantic.Receipts{
			ProtocolVersion: "1.0", CapabilityVersion: semantic.CapabilityName,
			CatalogRevision: 71, SecurityEpoch: 1,
		},
	})
	wireRequest, err := mapping.ToWireQueryRecordsRequest(ctx, semantic.Request{
		ObjectID: "WorkItem", Selections: []semantic.Selection{{Kind: semantic.SelectionField, Field: constants.FieldID}},
		Filter: semantic.Predicate{
			Kind: semantic.PredicateComparison, Operator: semantic.ComparisonEqual,
			Left:  semantic.Operand{Kind: semantic.OperandField, Field: "OwnerId"},
			Right: semantic.Operand{Kind: semantic.OperandTrustedContext, TrustedContext: semantic.TrustedContextPrincipalID},
		},
	})
	if err != nil {
		t.Fatal(err)
	}
	if _, err := server.QueryRecords(ctx, wireRequest); err != nil {
		t.Fatal(err)
	}
	if engine.resolvedDisposition != referenceidentity.Immutable || engine.resolvedName != "Catalog label" {
		t.Fatalf("bound query identity = disposition %v name %q", engine.resolvedDisposition, engine.resolvedName)
	}
}

func TestQueryExactDecimalPredicateRemainsNumeric(t *testing.T) {
	value, err := queryScalarValue(semantic.Scalar{Decimal: &semantic.Decimal{Coefficient: "123456789012345678901200", Scale: 4}})
	if err != nil {
		t.Fatal(err)
	}
	exact, ok := value.(queryspec.NumericLiteral)
	if !ok || exact != "12345678901234567890.1200" {
		t.Fatalf("exact predicate = %#v (%T)", value, value)
	}
	predicate := queryspec.ComparisonPredicate(queryspec.FieldOperand("Amount"), ">", queryspec.LiteralOperand(exact))
	lowered, err := queryspec.LowerPredicate(predicate, queryspec.PredicateLoweringExpressionOnly)
	if err != nil {
		t.Fatal(err)
	}
	if lowered.Expression != "Amount > 12345678901234567890.1200" {
		t.Fatalf("lowered exact predicate = %q", lowered.Expression)
	}
}

func TestQueryResponseNormalizesEngineLookupCarrierThroughBoundMetadata(t *testing.T) {
	view := queryResponseTestView(t)
	row := models.SObject{
		constants.FieldID:   "work-1",
		"WorkspaceId":       "workspace-1",
		"WorkspaceId_Name":  "Main workspace",
		"UndeclaredId_Name": "must not create an edge",
	}
	result, err := semanticQueryResponse(&models.QueryResult{TotalSize: 1, Done: true, Records: []models.SObject{row}}, semantic.Receipts{}, view, "WorkItem")
	if err != nil {
		t.Fatal(err)
	}
	if len(result.Records) != 1 {
		t.Fatalf("records = %d, want 1", len(result.Records))
	}
	fields := semanticFieldsByName(result.Records[0].Fields)
	workspace := fields["Workspace"].Object
	if workspace == nil || workspace.ObjectID != "Workspace" {
		t.Fatalf("Workspace = %#v, want neutral Workspace object", fields["Workspace"])
	}
	nested := semanticFieldsByName(workspace.Fields)
	if nested[constants.FieldID].String == nil || *nested[constants.FieldID].String != "workspace-1" ||
		nested[constants.FieldName].String == nil || *nested[constants.FieldName].String != "Main workspace" {
		t.Fatalf("nested Workspace fields = %#v", nested)
	}
	if _, invented := fields["Undeclared"]; invented {
		t.Fatalf("suffix-only field invented a relationship: %#v", fields["Undeclared"])
	}
	if _, mutated := row["Workspace"]; mutated {
		t.Fatal("Runtime response normalization mutated the engine-owned row")
	}
	if fields["WorkspaceId_Name"].String == nil {
		t.Fatal("existing compatibility field was silently removed before L1 projection")
	}
}

func TestQueryResponseRejectsNonObjectRelationshipCollision(t *testing.T) {
	view := queryResponseTestView(t)
	_, err := semanticQueryResponse(&models.QueryResult{Records: []models.SObject{{
		constants.FieldID: "work-1", "WorkspaceId": "workspace-1", "WorkspaceId_Name": "Main", "Workspace": "collision",
	}}}, semantic.Receipts{}, view, "WorkItem")
	if err == nil {
		t.Fatal("non-object relationship collision was accepted")
	}
}

func TestQueryResponseUsesChildObjectIdentityForTypedSubqueryProjection(t *testing.T) {
	view := queryResponseTestView(t)
	child := models.SObject{
		constants.FieldID: "work-1",
		"WorkspaceId":     "workspace-1",
		"DueDate":         "2026-07-19",
	}
	models.StampObjectType(child, "WorkItem")

	result, err := semanticQueryResponse(&models.QueryResult{Records: []models.SObject{{
		constants.FieldID: "workspace-1",
		"WorkItems":       []models.SObject{child},
	}}}, semantic.Receipts{}, view, "Workspace")
	if err != nil {
		t.Fatal(err)
	}
	rootFields := semanticFieldsByName(result.Records[0].Fields)
	if rootFields["WorkItems"].List == nil || len(*rootFields["WorkItems"].List) != 1 {
		t.Fatalf("WorkItems = %#v, want one child record", rootFields["WorkItems"])
	}
	childValue := (*rootFields["WorkItems"].List)[0]
	if childValue.Object == nil || childValue.Object.ObjectID != "WorkItem" {
		t.Fatalf("child = %#v, want typed WorkItem record", childValue)
	}
	childFields := semanticFieldsByName(childValue.Object.Fields)
	if childFields["WorkspaceId"].Kind != semantic.ValueReference || childFields["WorkspaceId"].Reference == nil ||
		*childFields["WorkspaceId"].Reference != "workspace-1" {
		t.Fatalf("WorkspaceId = %#v, want reference value", childFields["WorkspaceId"])
	}
	if childFields["DueDate"].Kind != semantic.ValueDate || childFields["DueDate"].Date == nil ||
		*childFields["DueDate"].Date != "2026-07-19" {
		t.Fatalf("DueDate = %#v, want date value", childFields["DueDate"])
	}
}

func TestQueryResponsePreservesMetadataDeclaredJSONAsAnonymousStructuredValue(t *testing.T) {
	view := queryResponseTestView(t)
	result, err := semanticQueryResponse(&models.QueryResult{TotalSize: 1, Done: true, Records: []models.SObject{{
		constants.FieldID: "work-1",
		"Payload": map[string]interface{}{
			"":           nil,
			"a-b":        false,
			"attributes": map[string]interface{}{"source": "json", "type": "ordinary-value"},
			"items":      []interface{}{float64(0), "", nil, map[string]interface{}{"space key": true}},
		},
	}}}, semantic.Receipts{ProtocolVersion: "1.0", CapabilityVersion: semantic.CapabilityName}, view, "WorkItem")
	if err != nil {
		t.Fatal(err)
	}
	fields := semanticFieldsByName(result.Records[0].Fields)
	payload := fields["Payload"]
	if payload.Kind != semantic.ValueObject || payload.Object == nil || payload.Object.ObjectID != "" {
		t.Fatalf("Payload = %#v, want anonymous value object", payload)
	}
	jsonFields := semanticFieldsByName(payload.Object.Fields)
	if !jsonFields[""].Null || jsonFields["a-b"].Boolean == nil || *jsonFields["a-b"].Boolean {
		t.Fatalf("JSON scalar fields = %#v", jsonFields)
	}
	attributes := jsonFields["attributes"]
	if attributes.Object == nil || attributes.Object.ObjectID != "" || semanticFieldsByName(attributes.Object.Fields)["type"].String == nil {
		t.Fatalf("JSON attributes object was interpreted as record metadata: %#v", attributes)
	}
	items := jsonFields["items"]
	if items.List == nil || len(*items.List) != 4 || (*items.List)[2].Null == false || (*items.List)[3].Object == nil {
		t.Fatalf("JSON list = %#v", items)
	}

	wireResponse, err := mapping.ToWireQueryRecordsResponse(result)
	if err != nil {
		t.Fatalf("encode existing query wire: %v", err)
	}
	roundTrip, err := mapping.FromWireQueryRecordsResponse(wireResponse)
	if err != nil {
		t.Fatalf("decode existing query wire: %v", err)
	}
	if got := semanticFieldsByName(roundTrip.Records[0].Fields)["Payload"]; got.Object == nil || got.Object.ObjectID != "" {
		t.Fatalf("wire round trip lost anonymous object identity: %#v", got)
	}
}

func TestQueryResponseRejectsUnstampedChildRecordCarrier(t *testing.T) {
	_, err := semanticQueryResponse(&models.QueryResult{Records: []models.SObject{{
		constants.FieldID: "workspace-1",
		"WorkItems":       []models.SObject{{constants.FieldID: "work-1"}},
	}}}, semantic.Receipts{}, queryResponseTestView(t), "Workspace")
	var failure *semantic.Failure
	if !errors.As(err, &failure) || failure.Category != semantic.FailureInternal {
		t.Fatalf("unstamped child error = %#v, want internal failure", err)
	}
}

func TestQueryResponseRejectsChildOutsideBoundMetadataClosure(t *testing.T) {
	child := models.SObject{constants.FieldID: "foreign-1", "CreatedDate": "2026-07-19T08:00:00Z"}
	models.StampObjectType(child, "ForeignObject")
	_, err := semanticQueryResponse(&models.QueryResult{Records: []models.SObject{{
		constants.FieldID: "workspace-1",
		"ForeignRows":     []models.SObject{child},
	}}}, semantic.Receipts{}, queryResponseTestView(t), "Workspace")
	var failure *semantic.Failure
	if !errors.As(err, &failure) || failure.Category != semantic.FailureInternal {
		t.Fatalf("out-of-closure child error = %#v, want internal failure", err)
	}
}

func TestClassifyQueryEngineErrorPreservesPublicSemantics(t *testing.T) {
	tests := []struct {
		name       string
		err        error
		category   semantic.FailureCategory
		component  semantic.InvalidComponent
		retryAfter uint64
	}{
		{name: "unknown object", err: appErrors.NewNotFoundError("Object", "MissingObject"), category: semantic.FailureInvalidRequest, component: semantic.InvalidComponentObjectID},
		{name: "non-object metadata gap", err: appErrors.NewNotFoundError("formula view", "MissingObject"), category: semantic.FailureInternal},
		{name: "invalid selected field", err: appErrors.NewValidationError("SelectFields", "missing"), category: semantic.FailureInvalidRequest, component: semantic.InvalidComponentSelection},
		{name: "invalid subquery relationship", err: appErrors.NewValidationError("SubQuery.RelationshipName", "missing"), category: semantic.FailureInvalidRequest, component: semantic.InvalidComponentQueryPlan},
		{name: "child object read denied", err: appErrors.NewPermissionError("read", "Child"), category: semantic.FailureForbidden},
		{name: "child repository failed", err: errors.New("child repository failed"), category: semantic.FailureInternal},
		{name: "field projection admission full", err: permissions.ErrFieldPermissionProjectionOverloaded, category: semantic.FailureUnavailable, retryAfter: 1000},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			wireError := mapping.ToQueryStatusError(classifyQueryEngineError(tt.err))
			got := mapping.FromQueryStatusError(wireError)
			var failure *semantic.Failure
			if !errors.As(got, &failure) || failure.Category != tt.category || failure.InvalidComponent != tt.component ||
				failure.RetryAfterMillis != tt.retryAfter {
				t.Fatalf("public Runtime error = %#v, want category=%q component=%q retryAfter=%d", got, tt.category, tt.component, tt.retryAfter)
			}
		})
	}
}

func TestQueryRecordsReturnsSubqueryExecutionFailuresAsTypedStatus(t *testing.T) {
	tests := []struct {
		name      string
		engineErr error
		category  semantic.FailureCategory
		component semantic.InvalidComponent
	}{
		{
			name: "invalid relationship", engineErr: appErrors.NewValidationError("SubQuery.RelationshipName", "missing"),
			category: semantic.FailureInvalidRequest, component: semantic.InvalidComponentQueryPlan,
		},
		{
			name: "child read denied", engineErr: appErrors.NewPermissionError("read", "WorkItem"),
			category: semantic.FailureForbidden,
		},
		{
			name: "child repository failed", engineErr: errors.New("child repository unavailable"),
			category: semantic.FailureInternal,
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			engine := &queryServerTestEngine{queryErr: tt.engineErr}
			server, err := NewQueryServer(engine, nil, nil)
			if err != nil {
				t.Fatal(err)
			}
			ctx, cancel := context.WithTimeout(context.Background(), time.Second)
			defer cancel()
			trusted := newTrustedCall(delegation.Claims{
				DelegationID: "delegation-query-test", OrgID: "org-query-test", PrincipalID: "user-query-test",
				SessionID: "session-query-test", CallerWorkloadID: "appservice-query-test",
				AppInstallationID: "installation-query-test", RuntimeAudience: "runtime-query-test",
				Capabilities: []string{semantic.CapabilityName}, AuthEpoch: 1, SecurityEpoch: 1,
			}, models.UserSession{ID: "user-query-test"})
			ctx = context.WithValue(ctx, trustedCallContextKey{}, trusted)
			ctx = context.WithValue(ctx, runtimeExecutionScopeContextKey{}, RuntimeExecutionScope{
				view: queryResponseTestView(t), receipts: semantic.Receipts{CatalogRevision: 1, SecurityEpoch: 1},
			})
			wireRequest, err := mapping.ToWireQueryRecordsRequest(ctx, semantic.Request{
				ObjectID:   "Workspace",
				Selections: []semantic.Selection{{Kind: semantic.SelectionField, Field: constants.FieldID}},
				Subqueries: []semantic.Subquery{{
					RelationshipName: "WorkItems", SelectedFields: []string{constants.FieldID}, Limit: 1,
				}},
			})
			if err != nil {
				t.Fatal(err)
			}
			_, wireErr := server.QueryRecords(ctx, wireRequest)
			decoded := mapping.FromQueryStatusError(wireErr)
			var failure *semantic.Failure
			if !errors.As(decoded, &failure) || failure.Category != tt.category || failure.InvalidComponent != tt.component {
				t.Fatalf("QueryRecords error = %#v, want category=%q component=%q", decoded, tt.category, tt.component)
			}
			if engine.queryCalls != 1 {
				t.Fatalf("QueryRecords engine calls = %d, want 1", engine.queryCalls)
			}
		})
	}
}

func TestQueryRecordsReturnsUnknownEngineObjectAsPublicObjectIdentifierFailure(t *testing.T) {
	engine := &queryServerTestEngine{queryErr: appErrors.NewNotFoundError("Object", "MissingObject")}
	server, err := NewQueryServer(engine, nil, nil)
	if err != nil {
		t.Fatal(err)
	}
	ctx, cancel := context.WithTimeout(context.Background(), time.Second)
	defer cancel()
	trusted := newTrustedCall(delegation.Claims{
		DelegationID: "delegation-query-test", OrgID: "org-query-test", PrincipalID: "user-query-test",
		SessionID: "session-query-test", CallerWorkloadID: "appservice-query-test",
		AppInstallationID: "installation-query-test", RuntimeAudience: "runtime-query-test",
		Capabilities: []string{semantic.CapabilityName}, AuthEpoch: 1, SecurityEpoch: 1,
	}, models.UserSession{ID: "user-query-test"})
	ctx = context.WithValue(ctx, trustedCallContextKey{}, trusted)
	ctx = context.WithValue(ctx, runtimeExecutionScopeContextKey{}, RuntimeExecutionScope{
		view: queryResponseTestView(t), receipts: semantic.Receipts{CatalogRevision: 1, SecurityEpoch: 1},
	})
	wireRequest, err := mapping.ToWireQueryRecordsRequest(ctx, semantic.Request{
		ObjectID: "MissingObject", Selections: []semantic.Selection{{Kind: semantic.SelectionField, Field: constants.FieldID}},
	})
	if err != nil {
		t.Fatal(err)
	}
	_, wireErr := server.QueryRecords(ctx, wireRequest)
	decoded := mapping.FromQueryStatusError(wireErr)
	var failure *semantic.Failure
	if !errors.As(decoded, &failure) || failure.Category != semantic.FailureInvalidRequest ||
		failure.InvalidComponent != semantic.InvalidComponentObjectID {
		t.Fatalf("QueryRecords error = %#v, want invalid object identifier", decoded)
	}
}

func TestQueryRecordsRejectsUnexecutableFunctionBeforeEngineAccess(t *testing.T) {
	engine := &queryServerTestEngine{}
	server, err := NewQueryServer(engine, nil, nil)
	if err != nil {
		t.Fatal(err)
	}
	ctx, cancel := context.WithTimeout(context.Background(), time.Second)
	defer cancel()
	trusted := newTrustedCall(delegation.Claims{
		DelegationID: "delegation-query-test", OrgID: "org-query-test", PrincipalID: "user-query-test",
		SessionID: "session-query-test", CallerWorkloadID: "appservice-query-test",
		AppInstallationID: "installation-query-test", RuntimeAudience: "runtime-query-test",
		Capabilities: []string{semantic.CapabilityName}, AuthEpoch: 1, SecurityEpoch: 1,
	}, models.UserSession{ID: "user-query-test"})
	ctx = context.WithValue(ctx, trustedCallContextKey{}, trusted)
	ctx = context.WithValue(ctx, runtimeExecutionScopeContextKey{}, RuntimeExecutionScope{
		view: queryResponseTestView(t), receipts: semantic.Receipts{CatalogRevision: 1, SecurityEpoch: 1},
	})
	open := "open"
	wireRequest, err := mapping.ToWireQueryRecordsRequest(ctx, semantic.Request{
		ObjectID: "WorkItem",
		Selections: []semantic.Selection{
			{Kind: semantic.SelectionField, Field: "Status"},
			{Kind: semantic.SelectionAggregate, Aggregate: semantic.AggregateCount, Field: constants.FieldID, Alias: "total"},
		},
		GroupBy: "Status",
		Having: semantic.Predicate{
			Kind: semantic.PredicateComparison, Operator: semantic.ComparisonEqual,
			Left: semantic.Operand{
				Kind: semantic.OperandFunction, Function: semantic.FunctionString,
				Args: []semantic.Operand{{Kind: semantic.OperandField, Field: "Status"}},
			},
			Right: semantic.Operand{Kind: semantic.OperandLiteral, Literal: &semantic.Scalar{String: &open}},
		},
	})
	if err != nil {
		t.Fatal(err)
	}
	_, wireErr := server.QueryRecords(ctx, wireRequest)
	decoded := mapping.FromQueryStatusError(wireErr)
	if !isInvalidQueryPlan(decoded) {
		t.Fatalf("QueryRecords error = %#v, want typed invalid query plan", decoded)
	}
	if engine.queryCalls != 0 {
		t.Fatalf("QueryRecords reached engine %d times for an unexecutable plan", engine.queryCalls)
	}
}

func TestQueryProjectionCarriesAuthoritativeChildRelationshipName(t *testing.T) {
	view := queryResponseTestView(t)
	resolution := analytics.ResolveChildRelationshipAuthoritative(view.Objects(), "Workspace", "WorkItems")
	if resolution.Status != analytics.ChildRelStatusMatched || resolution.ChildObjectAPIName != "WorkItem" ||
		resolution.FKFieldAPIName != "WorkspaceId" {
		t.Fatalf("bound query metadata resolved child relationship as %#v", resolution)
	}
}

func TestQueryHistoryRequiresRequestBoundMetadataBeforeEngineAccess(t *testing.T) {
	engine := &queryServerTestEngine{}
	server, err := NewQueryServer(engine, ReceiptSourceFunc(func(context.Context) (semantic.Receipts, error) {
		return semantic.Receipts{ProtocolVersion: "1.0", CapabilityVersion: semantic.CapabilityName, CatalogRevision: 1, SecurityEpoch: 1}, nil
	}), nil)
	if err != nil {
		t.Fatal(err)
	}
	ctx, cancel := context.WithTimeout(context.Background(), time.Second)
	defer cancel()
	trusted := newTrustedCall(delegation.Claims{
		DelegationID: "delegation-query-test", OrgID: "org-query-test", PrincipalID: "user-query-test",
		SessionID: "session-query-test", CallerWorkloadID: "appservice-query-test",
		AppInstallationID: "installation-query-test", RuntimeAudience: "runtime-query-test",
		Capabilities: []string{semantic.CapabilityName}, AuthEpoch: 1, SecurityEpoch: 1,
	}, models.UserSession{ID: "user-query-test"})
	ctx = context.WithValue(ctx, trustedCallContextKey{}, trusted)
	wireRequest, err := mapping.ToWireQueryHistoryRequest(ctx, semantic.HistoryRequest{
		ParentObjectID: "WorkItem", SelectedFields: []string{"Field"}, Limit: 1,
	})
	if err != nil {
		t.Fatal(err)
	}
	_, err = server.QueryHistory(ctx, wireRequest)
	if status.Code(err) != codes.Unavailable {
		t.Fatalf("QueryHistory error = %v, want Unavailable", err)
	}
	if engine.historyCalls != 0 {
		t.Fatalf("QueryHistory reached engine %d times without a bound Catalog view", engine.historyCalls)
	}
}

func TestQueryResponseRejectsEngineValueBeyondSemanticDepth(t *testing.T) {
	nested := map[string]interface{}{"leaf": "value"}
	for range semantic.MaxNestingDepth {
		nested = map[string]interface{}{"child": nested}
	}
	_, err := semanticQueryResponse(&models.QueryResult{Records: []models.SObject{{"nested": nested}}}, semantic.Receipts{}, nil, "WorkItem")
	var failure *semantic.Failure
	if !errors.As(err, &failure) || failure.Category != semantic.FailureResourceExhausted ||
		failure.LimitKind != semantic.LimitQueryDepth || failure.Maximum != semantic.MaxNestingDepth {
		t.Fatalf("deep Runtime projection error = %#v, want query depth limit %d", err, semantic.MaxNestingDepth)
	}
}

type queryServerTestEngine struct {
	historyCalls        int
	queryCalls          int
	queryErr            error
	queryResult         *models.QueryResult
	lastSpec            queryspec.QuerySpec
	lastUserID          string
	resolveObject       string
	resolveID           string
	resolvedDisposition referenceidentity.Disposition
	resolvedName        string
}

func (e *queryServerTestEngine) QueryWithSpec(ctx context.Context, spec queryspec.QuerySpec, user *models.UserSession) (*models.QueryResult, error) {
	e.queryCalls++
	e.lastSpec = spec
	if user != nil {
		e.lastUserID = user.ID
	}
	if e.queryErr != nil {
		return nil, e.queryErr
	}
	if e.resolveObject != "" {
		authority, bound := referenceidentity.FromContext(ctx)
		if !bound {
			return nil, errors.New("query reference identity authority is not bound")
		}
		resolution, err := authority.ResolveReferenceIdentities(ctx, e.resolveObject, []string{e.resolveID}, []string{constants.FieldID, constants.FieldName})
		if err != nil {
			return nil, err
		}
		identity := resolution.Identities[e.resolveID]
		e.resolvedDisposition = identity.Disposition
		e.resolvedName, _ = identity.Record[constants.FieldName].(string)
	}
	if e.queryResult != nil {
		return e.queryResult, nil
	}
	return nil, errors.New("unexpected QueryWithSpec call")
}

func (e *queryServerTestEngine) QueryHistory(context.Context, contract.HistoryQueryRequest, *models.UserSession) (*contract.HistoryQueryResult, error) {
	e.historyCalls++
	return &contract.HistoryQueryResult{}, nil
}

func semanticFieldsByName(fields []semantic.Field) map[string]semantic.Value {
	result := make(map[string]semantic.Value, len(fields))
	for _, field := range fields {
		result[field.Name] = field.Value
	}
	return result
}

func queryResponseTestView(t *testing.T) *catalogsnapshot.RuntimeMetadataView {
	t.Helper()
	const revision catalogsnapshot.CatalogRevision = 1
	relationshipName := "Workspace"
	childRelationshipName := "WorkItems"
	workspace := &models.ObjectMetadata{
		ID: "object-workspace", APIName: "Workspace", Label: "Workspace", PluralLabel: "Workspaces",
		SharingModel: constants.SharingModelPublicReadWrite,
		Fields: []models.FieldMetadata{
			{ID: "workspace-id", APIName: constants.FieldID, Label: "ID", Type: constants.FieldTypeString, PhysicalName: "id", IsSystem: true},
			{ID: "workspace-name", APIName: constants.FieldName, Label: "Name", Type: constants.FieldTypeString, PhysicalName: "name", IsNameField: true},
		},
	}
	workItem := &models.ObjectMetadata{
		ID: "object-work-item", APIName: "WorkItem", Label: "Work Item", PluralLabel: "Work Items",
		SharingModel: constants.SharingModelPublicReadWrite,
		Fields: []models.FieldMetadata{
			{ID: "work-item-id", APIName: constants.FieldID, Label: "ID", Type: constants.FieldTypeString, PhysicalName: "id", IsSystem: true},
			{ID: "work-item-workspace", APIName: "WorkspaceId", Label: "Workspace", Type: constants.FieldTypeReference, PhysicalName: "workspace_id", ReferenceTo: []string{"Workspace"}, RelationshipName: &relationshipName, ChildRelationshipName: &childRelationshipName},
			{ID: "work-item-due-date", APIName: "DueDate", Label: "Due Date", Type: constants.FieldTypeDate, PhysicalName: "due_date"},
			{ID: "work-item-payload", APIName: "Payload", Label: "Payload", Type: constants.FieldTypeJson, PhysicalName: "payload"},
		},
	}
	input := catalogsnapshot.CompileInput{
		OrgID:   "org-query-test",
		Lineage: catalogsnapshot.Lineage{CatalogRevision: revision, SchemaGeneration: 1, EngineGeneration: 1},
		Objects: []catalogsnapshot.ObjectInput{
			{CatalogRevision: revision, Metadata: workItem},
			{CatalogRevision: revision, Metadata: workspace},
		},
		Relationships: []catalogsnapshot.RelationshipInput{{CatalogRevision: revision, Metadata: &models.Relationship{
			ID: "relationship-workspace", ChildObjectAPIName: "WorkItem", ParentObjectAPIName: "Workspace",
			FieldAPIName: "WorkspaceId", RelationshipName: relationshipName, RelationshipType: "lookup",
		}}},
		Projections: []catalogsnapshot.RuntimeProjectionInput{{
			CatalogRevision: revision, AppInstallationID: "installation-query-test", CapabilityID: semantic.CapabilityName,
			Profile: catalogsnapshot.ProjectionRecordQueryV1, ObjectAPINames: []string{"WorkItem", "Workspace"},
		}},
	}
	snapshotArtifact, err := catalogsnapshot.CompileCatalogSnapshot(input)
	if err != nil {
		t.Fatalf("compile Catalog snapshot: %v", err)
	}
	snapshot, err := catalogsnapshot.OpenCatalogSnapshot(snapshotArtifact)
	if err != nil {
		t.Fatalf("open Catalog snapshot: %v", err)
	}
	viewArtifact, err := catalogsnapshot.ProjectRuntimeMetadataView(snapshot, catalogsnapshot.ProjectionKey{
		AppInstallationID: "installation-query-test", CapabilityID: semantic.CapabilityName,
	})
	if err != nil {
		t.Fatalf("project Runtime query view: %v", err)
	}
	view, err := catalogsnapshot.OpenRuntimeMetadataView(viewArtifact)
	if err != nil {
		t.Fatalf("open Runtime query view: %v", err)
	}
	return view
}
