package mapping

import (
	"errors"
	"testing"

	analyticssemantic "github.com/pingcap-inc/nexuscrm-contract/pkg/runtime/analyticsauthoringv1"
	approvalsemantic "github.com/pingcap-inc/nexuscrm-contract/pkg/runtime/approvalv1"
	commonsemantic "github.com/pingcap-inc/nexuscrm-contract/pkg/runtime/commonv1"
	layoutauthoringv2 "github.com/pingcap-inc/nexuscrm-contract/pkg/runtime/layoutauthoringv2"
	permissionsemantic "github.com/pingcap-inc/nexuscrm-contract/pkg/runtime/permissionadminv1"
	permissionauthoringsemantic "github.com/pingcap-inc/nexuscrm-contract/pkg/runtime/permissionauthoringv1"
	historysemantic "github.com/pingcap-inc/nexuscrm-contract/pkg/runtime/queryv1"
	resourceaccesssemantic "github.com/pingcap-inc/nexuscrm-contract/pkg/runtime/resourceaccessv1"
	sessionsemantic "github.com/pingcap-inc/nexuscrm-contract/pkg/runtime/sessionv1"
	"github.com/pingcap-inc/nexuscrm-contract/wire-go/envelope"
	runtimev1 "github.com/pingcap-inc/nexuscrm-contract/wire-go/gen/runtime/v1"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
	"google.golang.org/protobuf/encoding/protowire"
	"google.golang.org/protobuf/proto"
	"google.golang.org/protobuf/reflect/protoreflect"
)

func TestPlatformWirePayloadPreflightReturnsInspectableLimitFailures(t *testing.T) {
	requestCases := []struct {
		name           string
		payload        []byte
		destination    proto.Message
		capabilityName string
		maximum        int
	}{
		{
			name: "session document routes", payload: appendWireBytesField(nil, 4, repeatedEmptyWireMessages(2, sessionsemantic.MaxDocumentLinkRoutes+1)),
			destination: &runtimev1.ReadSessionRequest{}, capabilityName: sessionsemantic.CapabilityName,
			maximum: sessionsemantic.MaxDocumentLinkRoutes,
		},
		{
			name: "resource request", payload: repeatedEmptyWireMessages(6, resourceaccesssemantic.MaxGrants+1),
			destination: &runtimev1.AccessResourceRequest{}, capabilityName: resourceaccesssemantic.CapabilityName,
			maximum: resourceaccesssemantic.MaxGrants,
		},
		{
			name: "permission mutation", payload: repeatedEmptyWireMessages(3, permissionsemantic.MaxGrants+1),
			destination: &runtimev1.MutatePermissionAdministrationRequest{}, capabilityName: permissionsemantic.CapabilityName,
			maximum: permissionsemantic.MaxGrants,
		},
		{
			name: "analytics components across merged wrappers",
			payload: appendWireBytesField(
				appendWireBytesField(nil, 6, analyticsDashboardWirePayload(analyticssemantic.MaxDashboardComponents)),
				6, analyticsDashboardWirePayload(1),
			),
			destination: &runtimev1.MutateAnalyticsDefinitionRequest{}, capabilityName: analyticssemantic.CapabilityName,
			maximum: analyticssemantic.MaxDashboardComponents,
		},
	}
	for _, test := range requestCases {
		t.Run(test.name, func(t *testing.T) {
			err := PreflightPlatformWirePayload(test.payload, test.destination)
			assertPlatformLimitFailure(t, err, commonsemantic.LimitOperationCount, test.maximum)
			statusErr := ToPlatformStatusError(err, test.capabilityName)
			if status.Code(statusErr) != codes.ResourceExhausted {
				t.Fatalf("status code = %s, want %s", status.Code(statusErr), codes.ResourceExhausted)
			}
			assertPlatformLimitFailure(
				t,
				FromPlatformStatusError(statusErr, test.capabilityName),
				commonsemantic.LimitOperationCount,
				test.maximum,
			)
		})
	}

	t.Run("resource response remains peer internal failure", func(t *testing.T) {
		err := PreflightPlatformWirePayload(
			repeatedEmptyWireMessages(2, resourceaccesssemantic.MaxGrants+1),
			&runtimev1.AccessResourceResponse{},
		)
		assertPlatformFailure(t, err, commonsemantic.FailureInternal, "")
	})
	t.Run("permission response across families remains peer internal failure", func(t *testing.T) {
		payload := repeatedEmptyWireMessages(1, permissionsemantic.MaxCatalogEntries)
		payload = append(payload, repeatedEmptyWireMessages(2, 1)...)
		err := PreflightPlatformWirePayload(payload, &runtimev1.ReadPermissionAdministrationResponse{})
		assertPlatformFailure(t, err, commonsemantic.FailureInternal, "")
	})
}

func TestApprovalValidationIssuesWirePayloadPreflight(t *testing.T) {
	validationIssues := func(count int) []byte {
		return appendWireBytesField(nil, 10, repeatedEmptyWireMessages(2, count))
	}

	if err := PreflightPlatformWirePayload(
		validationIssues(approvalsemantic.MaxValidationIssues),
		&runtimev1.ExecuteApprovalResponse{},
	); err != nil {
		t.Fatalf("maximum validation issues rejected: %v", err)
	}

	assertPlatformFailure(
		t,
		PreflightPlatformWirePayload(
			validationIssues(approvalsemantic.MaxValidationIssues+1),
			&runtimev1.ExecuteApprovalResponse{},
		),
		commonsemantic.FailureInternal,
		"",
	)

	mergedRejections := validationIssues(approvalsemantic.MaxValidationIssues)
	mergedRejections = append(
		mergedRejections,
		appendWireBytesField(nil, 10, repeatedEmptyWireMessages(2, 1))...,
	)
	assertPlatformFailure(
		t,
		PreflightPlatformWirePayload(mergedRejections, &runtimev1.ExecuteApprovalResponse{}),
		commonsemantic.FailureInternal,
		"",
	)
}

type permissionAuthoringRawPreflightCase struct {
	path        string
	maximum     int
	kind        commonsemantic.LimitKind
	destination proto.Message
	payload     func(int) []byte
	response    bool
}

func TestPermissionAuthoringWirePayloadPreflightCoversEveryRepeatedField(t *testing.T) {
	requestPayload := func(field protowire.Number) func(int) []byte {
		return func(count int) []byte {
			return appendWireBytesField(nil, 4, repeatedEmptyWireMessages(field, count))
		}
	}
	responsePayload := func(wrapper, field protowire.Number) func(int) []byte {
		return func(count int) []byte {
			return appendWireBytesField(nil, wrapper, repeatedEmptyWireMessages(field, count))
		}
	}
	tests := []permissionAuthoringRawPreflightCase{
		{path: "SavePermissionAuthoringRequest.changes.system", maximum: permissionauthoringsemantic.MaxSystemChanges, kind: commonsemantic.LimitOperationCount, destination: &runtimev1.SavePermissionAuthoringRequest{}, payload: requestPayload(1)},
		{path: "SavePermissionAuthoringRequest.changes.objects", maximum: permissionauthoringsemantic.MaxObjectChanges, kind: commonsemantic.LimitOperationCount, destination: &runtimev1.SavePermissionAuthoringRequest{}, payload: requestPayload(2)},
		{path: "SavePermissionAuthoringRequest.changes.fields", maximum: permissionauthoringsemantic.MaxFieldChanges, kind: commonsemantic.LimitFieldCount, destination: &runtimev1.SavePermissionAuthoringRequest{}, payload: requestPayload(3)},
		{path: "SavePermissionAuthoringRequest.changes.record_types", maximum: permissionauthoringsemantic.MaxRecordTypeChanges, kind: commonsemantic.LimitOperationCount, destination: &runtimev1.SavePermissionAuthoringRequest{}, payload: requestPayload(4)},
		{path: "SavePermissionAuthoringRequest.changes.custom", maximum: permissionauthoringsemantic.MaxCustomChanges, kind: commonsemantic.LimitOperationCount, destination: &runtimev1.SavePermissionAuthoringRequest{}, payload: requestPayload(5)},
		{path: "ReadPermissionAuthoringSnapshotResponse.catalog.system", maximum: permissionauthoringsemantic.MaxSystemChanges, destination: &runtimev1.ReadPermissionAuthoringSnapshotResponse{}, payload: responsePayload(3, 1), response: true},
		{path: "ReadPermissionAuthoringSnapshotResponse.catalog.record_types", maximum: permissionauthoringsemantic.MaxRecordTypeChanges, destination: &runtimev1.ReadPermissionAuthoringSnapshotResponse{}, payload: responsePayload(3, 2), response: true},
		{path: "ReadPermissionAuthoringSnapshotResponse.catalog.custom", maximum: permissionauthoringsemantic.MaxCustomChanges, destination: &runtimev1.ReadPermissionAuthoringSnapshotResponse{}, payload: responsePayload(3, 3), response: true},
		{path: "ReadPermissionAuthoringSnapshotResponse.grants.system", maximum: permissionauthoringsemantic.MaxSystemChanges, destination: &runtimev1.ReadPermissionAuthoringSnapshotResponse{}, payload: responsePayload(4, 1), response: true},
		{path: "ReadPermissionAuthoringSnapshotResponse.grants.objects", maximum: permissionauthoringsemantic.MaxObjectChanges, destination: &runtimev1.ReadPermissionAuthoringSnapshotResponse{}, payload: responsePayload(4, 2), response: true},
		{path: "ReadPermissionAuthoringSnapshotResponse.grants.fields", maximum: permissionauthoringsemantic.MaxFieldChanges, destination: &runtimev1.ReadPermissionAuthoringSnapshotResponse{}, payload: responsePayload(4, 3), response: true},
		{path: "ReadPermissionAuthoringSnapshotResponse.grants.record_types", maximum: permissionauthoringsemantic.MaxRecordTypeChanges, destination: &runtimev1.ReadPermissionAuthoringSnapshotResponse{}, payload: responsePayload(4, 4), response: true},
		{path: "ReadPermissionAuthoringSnapshotResponse.grants.custom", maximum: permissionauthoringsemantic.MaxCustomChanges, destination: &runtimev1.ReadPermissionAuthoringSnapshotResponse{}, payload: responsePayload(4, 5), response: true},
	}
	requireEveryRepeatedPermissionAuthoringFieldCovered(t, tests)
	for _, test := range tests {
		t.Run(test.path, func(t *testing.T) {
			if err := PreflightPlatformWirePayload(test.payload(test.maximum), test.destination); err != nil {
				t.Fatalf("maximum repeated field rejected: %v", err)
			}
			err := PreflightPlatformWirePayload(test.payload(test.maximum+1), test.destination)
			if test.response {
				assertPlatformFailure(t, err, commonsemantic.FailureInternal, "")
				return
			}
			assertPlatformLimitFailure(t, err, test.kind, test.maximum)
		})
	}
}

func TestPermissionAuthoringWirePayloadPreflightAggregatesMergedMessageOccurrences(t *testing.T) {
	request := appendWireBytesField(nil, 4, repeatedEmptyWireMessages(2, permissionauthoringsemantic.MaxObjectChanges))
	request = appendWireBytesField(request, 4, repeatedEmptyWireMessages(2, 1))
	assertPlatformLimitFailure(
		t,
		PreflightPlatformWirePayload(request, &runtimev1.SavePermissionAuthoringRequest{}),
		commonsemantic.LimitOperationCount,
		permissionauthoringsemantic.MaxObjectChanges,
	)

	response := appendWireBytesField(nil, 4, repeatedEmptyWireMessages(2, permissionauthoringsemantic.MaxObjectChanges))
	response = appendWireBytesField(response, 4, repeatedEmptyWireMessages(2, 1))
	assertPlatformFailure(
		t,
		PreflightPlatformWirePayload(response, &runtimev1.ReadPermissionAuthoringSnapshotResponse{}),
		commonsemantic.FailureInternal,
		"",
	)
}

func requireEveryRepeatedPermissionAuthoringFieldCovered(t *testing.T, tests []permissionAuthoringRawPreflightCase) {
	t.Helper()
	covered := make(map[string]struct{}, len(tests))
	for _, test := range tests {
		if _, duplicate := covered[test.path]; duplicate {
			t.Fatalf("duplicate raw preflight case %q", test.path)
		}
		covered[test.path] = struct{}{}
	}
	service := runtimev1.File_runtime_v1_permission_authoring_proto.Services().ByName("PermissionAuthoringService")
	wantRegistered := map[protoreflect.FullName]proto.Message{
		(&runtimev1.SavePermissionAuthoringRequest{}).ProtoReflect().Descriptor().FullName():          &runtimev1.SavePermissionAuthoringRequest{},
		(&runtimev1.ReadPermissionAuthoringSnapshotResponse{}).ProtoReflect().Descriptor().FullName(): &runtimev1.ReadPermissionAuthoringSnapshotResponse{},
	}
	discovered := map[string]struct{}{}
	methods := service.Methods()
	for methodIndex := 0; methodIndex < methods.Len(); methodIndex++ {
		method := methods.Get(methodIndex)
		for _, message := range []protoreflect.MessageDescriptor{method.Input(), method.Output()} {
			repeated := map[string]struct{}{}
			collectRepeatedFieldPaths(message, string(message.Name()), repeated)
			if len(repeated) == 0 {
				continue
			}
			for path := range repeated {
				discovered[path] = struct{}{}
			}
			destination, ok := wantRegistered[message.FullName()]
			if !ok {
				t.Fatalf("permission authoring message %s has nested repeated fields but no raw preflight registration", message.FullName())
			}
			if err := PreflightPlatformWirePayload([]byte{0xff}, destination); !errors.Is(err, ErrMalformedPlatformWire) {
				t.Fatalf("permission authoring message %s raw preflight registration not active: %v", message.FullName(), err)
			}
			delete(wantRegistered, message.FullName())
		}
	}
	for message := range wantRegistered {
		t.Fatalf("raw preflight registration %s is not a permission authoring service message with repeated fields", message)
	}
	for path := range discovered {
		if _, ok := covered[path]; !ok {
			t.Fatalf("repeated permission authoring field %s has no raw preflight case", path)
		}
		delete(covered, path)
	}
	for path := range covered {
		t.Fatalf("raw preflight case %s does not name a repeated permission authoring service field", path)
	}
}

func TestAnalyticsWirePayloadPreflightCoversEveryRepeatedDefinitionField(t *testing.T) {
	tests := []struct {
		path    string
		maximum int
		payload func(int) []byte
	}{
		{
			path: "AnalyticsDashboardDefinition.component_set.components", maximum: analyticssemantic.MaxDashboardComponents,
			payload: func(count int) []byte {
				return appendWireBytesField(nil, 6, analyticsDashboardWirePayload(count))
			},
		},
		{
			path: "AnalyticsReportDefinition.column_set.columns", maximum: analyticssemantic.MaxReportDefinitionEntries,
			payload: func(count int) []byte { return analyticsReportWirePayload(9, count) },
		},
		{
			path: "AnalyticsReportDefinition.filter_set.filters", maximum: analyticssemantic.MaxReportDefinitionEntries,
			payload: func(count int) []byte { return analyticsReportWirePayload(10, count) },
		},
		{
			path: "AnalyticsReportDefinition.grouping_set.grouping", maximum: analyticssemantic.MaxReportDefinitionEntries,
			payload: func(count int) []byte { return analyticsReportWirePayload(11, count) },
		},
	}
	requireEveryRepeatedAnalyticsDefinitionFieldCovered(t, tests)
	for _, test := range tests {
		t.Run(test.path, func(t *testing.T) {
			if err := PreflightPlatformWirePayload(test.payload(test.maximum), &runtimev1.MutateAnalyticsDefinitionRequest{}); err != nil {
				t.Fatalf("maximum repeated field rejected: %v", err)
			}
			assertPlatformLimitFailure(
				t,
				PreflightPlatformWirePayload(test.payload(test.maximum+1), &runtimev1.MutateAnalyticsDefinitionRequest{}),
				commonsemantic.LimitOperationCount,
				test.maximum,
			)
		})
	}

	mergedReports := analyticsReportWirePayload(9, analyticssemantic.MaxReportDefinitionEntries/2)
	mergedReports = append(mergedReports, analyticsReportWirePayload(10, analyticssemantic.MaxReportDefinitionEntries/2+1)...)
	assertPlatformLimitFailure(
		t,
		PreflightPlatformWirePayload(mergedReports, &runtimev1.MutateAnalyticsDefinitionRequest{}),
		commonsemantic.LimitOperationCount,
		analyticssemantic.MaxReportDefinitionEntries,
	)
}

func requireEveryRepeatedAnalyticsDefinitionFieldCovered(t *testing.T, tests []struct {
	path    string
	maximum int
	payload func(int) []byte
}) {
	t.Helper()
	covered := make(map[string]struct{}, len(tests))
	for _, test := range tests {
		if _, duplicate := covered[test.path]; duplicate {
			t.Fatalf("duplicate raw preflight case %q", test.path)
		}
		covered[test.path] = struct{}{}
	}
	discovered := map[string]struct{}{}
	for _, message := range []protoreflect.MessageDescriptor{
		(&runtimev1.AnalyticsDashboardDefinition{}).ProtoReflect().Descriptor(),
		(&runtimev1.AnalyticsReportDefinition{}).ProtoReflect().Descriptor(),
	} {
		collectRepeatedFieldPaths(message, string(message.Name()), discovered)
	}
	for path := range discovered {
		if _, ok := covered[path]; !ok {
			t.Fatalf("repeated analytics definition field %s has no raw preflight case", path)
		}
		delete(covered, path)
	}
	for path := range covered {
		t.Fatalf("raw preflight case %s does not name a repeated analytics definition field", path)
	}
}

func collectRepeatedFieldPaths(message protoreflect.MessageDescriptor, prefix string, paths map[string]struct{}) {
	fields := message.Fields()
	for index := 0; index < fields.Len(); index++ {
		field := fields.Get(index)
		path := prefix + "." + string(field.Name())
		if field.Cardinality() == protoreflect.Repeated {
			paths[path] = struct{}{}
		}
		if field.Kind() == protoreflect.MessageKind {
			collectRepeatedFieldPaths(field.Message(), path, paths)
		}
	}
}

func TestPlatformWirePayloadPreflightEnforcesFramesBeforeScanningFields(t *testing.T) {
	maximumRequest := unknownWireBytesPayload(t, envelope.MaxRequestWireBytes)
	if err := PreflightPlatformWirePayload(maximumRequest, &runtimev1.AccessResourceRequest{}); err != nil {
		t.Fatalf("maximum request frame rejected: %v", err)
	}
	assertPlatformLimitFailure(
		t,
		PreflightPlatformWirePayload(
			oversizedUnknownScalarPayload(envelope.MaxRequestWireBytes),
			&runtimev1.AccessResourceRequest{},
		),
		commonsemantic.LimitWireFrame,
		envelope.MaxRequestWireBytes,
	)

	maximumResponse := unknownWireBytesPayload(t, envelope.MaxResponseWireBytes)
	if err := PreflightPlatformWirePayload(maximumResponse, &runtimev1.AccessResourceResponse{}); err != nil {
		t.Fatalf("maximum response frame rejected: %v", err)
	}
	assertPlatformFailure(
		t,
		PreflightPlatformWirePayload(
			oversizedUnknownScalarPayload(envelope.MaxResponseWireBytes),
			&runtimev1.AccessResourceResponse{},
		),
		commonsemantic.FailureInternal,
		"",
	)
}

func TestPlatformWirePayloadPreflightDoesNotMaterializeNestedMessages(t *testing.T) {
	resourceDestination := &runtimev1.AccessResourceRequest{}
	analyticsDestination := &runtimev1.MutateAnalyticsDefinitionRequest{}
	permissionAuthoringDestination := &runtimev1.SavePermissionAuthoringRequest{}
	tests := []struct {
		name         string
		payload      []byte
		destination  proto.Message
		maximum      int
		materialized func() int
	}{
		{
			name: "resource grants", payload: repeatedEmptyWireMessages(6, 100_000), destination: resourceDestination,
			maximum:      resourceaccesssemantic.MaxGrants,
			materialized: func() int { return len(resourceDestination.GetGrants()) },
		},
		{
			name: "analytics report filters", payload: analyticsReportWirePayload(10, 100_000), destination: analyticsDestination,
			maximum:      analyticssemantic.MaxReportDefinitionEntries,
			materialized: func() int { return len(analyticsDestination.GetReport().GetFilterSet().GetFilters()) },
		},
		{
			name: "permission authoring object changes", payload: appendWireBytesField(nil, 4, repeatedEmptyWireMessages(2, 100_000)), destination: permissionAuthoringDestination,
			maximum:      permissionauthoringsemantic.MaxObjectChanges,
			materialized: func() int { return len(permissionAuthoringDestination.GetChanges().GetObjects()) },
		},
	}
	for _, test := range tests {
		t.Run(test.name, func(t *testing.T) {
			var preflightErr error
			allocations := testing.AllocsPerRun(20, func() {
				preflightErr = PreflightPlatformWirePayload(test.payload, test.destination)
			})
			assertPlatformLimitFailure(t, preflightErr, commonsemantic.LimitOperationCount, test.maximum)
			if count := test.materialized(); count != 0 {
				t.Fatalf("preflight materialized %d nested values", count)
			}
			// The typed failure is the only required heap object. Leave small compiler
			// headroom while preventing allocations from scaling with the wire count.
			if allocations > 4 {
				t.Fatalf("preflight allocations = %.0f/run, want at most 4 for 100,000 nested values", allocations)
			}
		})
	}

	t.Run("permission authoring snapshot object grants", func(t *testing.T) {
		destination := &runtimev1.ReadPermissionAuthoringSnapshotResponse{}
		payload := appendWireBytesField(nil, 4, repeatedEmptyWireMessages(2, 100_000))
		var preflightErr error
		allocations := testing.AllocsPerRun(20, func() {
			preflightErr = PreflightPlatformWirePayload(payload, destination)
		})
		assertPlatformFailure(t, preflightErr, commonsemantic.FailureInternal, "")
		if count := len(destination.GetGrants().GetObjects()); count != 0 {
			t.Fatalf("preflight materialized %d nested values", count)
		}
		if allocations > 4 {
			t.Fatalf("preflight allocations = %.0f/run, want at most 4 for 100,000 nested values", allocations)
		}
	})
}

func TestPlatformWirePayloadPreflightAcceptsBoundsAndRejectsMalformedWire(t *testing.T) {
	if err := PreflightPlatformWirePayload(
		repeatedEmptyWireMessages(6, resourceaccesssemantic.MaxGrants),
		&runtimev1.AccessResourceRequest{},
	); err != nil {
		t.Fatalf("maximum resource request rejected: %v", err)
	}
	if err := PreflightPlatformWirePayload(
		appendWireBytesField(nil, 6, analyticsDashboardWirePayload(analyticssemantic.MaxDashboardComponents)),
		&runtimev1.MutateAnalyticsDefinitionRequest{},
	); err != nil {
		t.Fatalf("maximum analytics request rejected: %v", err)
	}
	if err := PreflightPlatformWirePayload([]byte{0xff}, &runtimev1.AccessResourceRequest{}); !errors.Is(err, ErrMalformedPlatformWire) {
		t.Fatalf("malformed wire error = %v, want ErrMalformedPlatformWire", err)
	}
	group := protowire.AppendTag(nil, 100, protowire.StartGroupType)
	group = protowire.AppendTag(group, 100, protowire.EndGroupType)
	if err := PreflightPlatformWirePayload(group, &runtimev1.AccessResourceRequest{}); !errors.Is(err, ErrMalformedPlatformWire) {
		t.Fatalf("protobuf group error = %v, want ErrMalformedPlatformWire", err)
	}
	if err := PreflightPlatformWirePayload([]byte{0xff}, &runtimev1.MutateAnalyticsDefinitionResponse{}); err != nil {
		t.Fatalf("message without structural limits should defer malformed-wire handling to protobuf: %v", err)
	}
}

func assertPlatformLimitFailure(t *testing.T, err error, kind commonsemantic.LimitKind, maximum int) {
	t.Helper()
	var failure *commonsemantic.Failure
	if !errors.As(err, &failure) || failure.Category != commonsemantic.FailureResourceExhausted ||
		failure.LimitKind != kind || failure.Maximum != uint64(maximum) {
		t.Fatalf("failure = %#v, want RESOURCE_EXHAUSTED/%s/%d", err, kind, maximum)
	}
	if errors.Is(err, ErrMalformedPlatformWire) {
		t.Fatal("resource limit was also classified as malformed wire")
	}
}

func unknownWireBytesPayload(t *testing.T, size int) []byte {
	t.Helper()
	for valueSize := size; valueSize >= 0; valueSize-- {
		header := protowire.AppendTag(nil, 100, protowire.BytesType)
		header = protowire.AppendVarint(header, uint64(valueSize))
		if len(header)+valueSize == size {
			return append(header, make([]byte, valueSize)...)
		}
	}
	t.Fatalf("cannot construct a valid unknown wire field of size %d", size)
	return nil
}

func oversizedUnknownScalarPayload(maximum int) []byte {
	result := make([]byte, 0, maximum+8)
	for len(result) <= maximum {
		result = protowire.AppendTag(result, 100, protowire.VarintType)
		result = protowire.AppendVarint(result, 1)
	}
	return result
}

func repeatedEmptyWireMessages(field protowire.Number, count int) []byte {
	result := make([]byte, 0, count*2)
	for range count {
		result = protowire.AppendTag(result, field, protowire.BytesType)
		result = protowire.AppendVarint(result, 0)
	}
	return result
}

func analyticsDashboardWirePayload(components int) []byte {
	componentSet := repeatedEmptyWireMessages(1, components)
	return appendWireBytesField(nil, 7, componentSet)
}

func analyticsReportWirePayload(collectionField protowire.Number, entries int) []byte {
	collection := repeatedEmptyWireMessages(1, entries)
	report := appendWireBytesField(nil, collectionField, collection)
	return appendWireBytesField(nil, 8, report)
}

func appendWireBytesField(destination []byte, field protowire.Number, value []byte) []byte {
	destination = protowire.AppendTag(destination, field, protowire.BytesType)
	return protowire.AppendBytes(destination, value)
}

func TestSessionDocumentPolicyPreflightBoundsMergedMessages(t *testing.T) {
	for _, test := range []struct {
		name        string
		destination proto.Message
		maximum     int
		request     bool
	}{
		{"request routes", &runtimev1.ReadSessionRequest{}, sessionsemantic.MaxDocumentLinkRoutes, true},
		{"response links", &runtimev1.ReadSessionResponse{}, sessionsemantic.MaxDocumentAllowedLinks, false},
	} {
		t.Run(test.name, func(t *testing.T) {
			maximum := appendWireBytesField(nil, 4, repeatedEmptyWireMessages(2, test.maximum))
			if err := PreflightPlatformWirePayload(maximum, test.destination); err != nil {
				t.Fatalf("boundary rejected: %v", err)
			}
			for _, payload := range [][]byte{
				appendWireBytesField(nil, 4, repeatedEmptyWireMessages(2, test.maximum+1)),
				append(appendWireBytesField(nil, 4, repeatedEmptyWireMessages(2, test.maximum)), appendWireBytesField(nil, 4, repeatedEmptyWireMessages(2, 1))...),
				appendWireBytesField(nil, 4, repeatedEmptyWireMessages(2, 100_000)),
			} {
				var err error
				allocations := testing.AllocsPerRun(20, func() { err = PreflightPlatformWirePayload(payload, test.destination) })
				if test.request {
					assertPlatformLimitFailure(t, err, commonsemantic.LimitOperationCount, test.maximum)
				} else {
					assertPlatformFailure(t, err, commonsemantic.FailureInternal, "")
				}
				if allocations > 4 {
					t.Fatalf("unbounded preflight allocations: %v", allocations)
				}
				switch v := test.destination.(type) {
				case *runtimev1.ReadSessionRequest:
					if v.DocumentPolicy != nil {
						t.Fatal("request policy materialized")
					}
				case *runtimev1.ReadSessionResponse:
					if v.DocumentPolicy != nil {
						t.Fatal("response policy materialized")
					}
				}
			}
			for _, payload := range [][]byte{{0xff}, appendWireBytesField(nil, 4, []byte{0xff})} {
				if err := PreflightPlatformWirePayload(payload, test.destination); !errors.Is(err, ErrMalformedPlatformWire) {
					t.Fatalf("malformed policy accepted: %v", err)
				}
			}
		})
	}
}

func TestLayoutAuthoringHistoryProjectionRawAdmission(t *testing.T) {
	entry := appendWireBytesField(nil, 1, []byte("duplicate"))
	entry = appendWireBytesField(entry, 2, []byte("id"))
	projection := func(count int) []byte {
		var result []byte
		for range count {
			result = appendWireBytesField(result, 2, entry)
		}
		return result
	}
	payload := func(count, columns int) []byte {
		var result []byte
		for range count {
			result = appendWireBytesField(result, 3, projection(columns))
		}
		return result
	}
	for _, tt := range []struct {
		name   string
		data   []byte
		reject bool
	}{
		{"bounded", payload(layoutauthoringv2.MaxHistoryRelatedListProjections, historysemantic.HistoryResultColumnCount), false},
		{"excess projections", payload(layoutauthoringv2.MaxHistoryRelatedListProjections+1, 0), true},
		{"excess duplicate map entries", payload(1, historysemantic.HistoryResultColumnCount+1), true},
		{"malformed map entry", appendWireBytesField(nil, 3, appendWireBytesField(nil, 2, []byte{0xff})), true},
	} {
		t.Run(tt.name, func(t *testing.T) {
			err := PreflightPlatformWirePayload(tt.data, &runtimev1.LayoutAuthoringV2ServiceMutateRequest{})
			if tt.name == "excess projections" {
				assertPlatformLimitFailure(t, err, commonsemantic.LimitOperationCount, layoutauthoringv2.MaxHistoryRelatedListProjections)
				return
			}
			if tt.name == "excess duplicate map entries" {
				assertPlatformLimitFailure(t, err, commonsemantic.LimitFieldCount, historysemantic.HistoryResultColumnCount)
				return
			}
			if tt.reject && !errors.Is(err, ErrMalformedPlatformWire) {
				t.Fatalf("expected raw rejection, got %v", err)
			}
			if !tt.reject && err != nil {
				t.Fatalf("bounded payload rejected: %v", err)
			}
		})
	}
}
