package compatibility

import (
	"strings"
	"testing"

	catalogv1 "github.com/pingcap-inc/nexuscrm-contract/wire-go/gen/catalog/v1"
	runtimev1 "github.com/pingcap-inc/nexuscrm-contract/wire-go/gen/runtime/v1"
	"google.golang.org/protobuf/reflect/protoreflect"
)

func TestPlatformAPIWireContainsOnlyReviewedNeutralCoarseOperations(t *testing.T) {
	servingBinding := (&runtimev1.CatalogServingBinding{}).ProtoReflect().Descriptor()
	assertFieldNames(t, servingBinding.Fields(), []protoreflect.Name{
		"org_id", "app_installation_id", "app_release_digest", "workload_id",
		"canonical_resource", "tool_contract_digest", "scope_route_receipt_digest",
		"workload_capability_ceiling", "receipts",
	})
	appView := (&catalogv1.GetAppMetadataViewRequest{}).ProtoReflect().Descriptor()
	assertFieldNames(t, appView.Fields(), []protoreflect.Name{"min_catalog_revision"})
	appViewV2 := (&catalogv1.AppMetadataViewV2{}).ProtoReflect().Descriptor()
	assertFieldNames(t, appViewV2.Fields(), []protoreflect.Name{
		"org_id", "app_installation_id", "app_id", "app_release_digest",
		"lineage", "app_components", "effective_components", "receipts",
	})
	appViewV3 := (&catalogv1.AppMetadataViewV3{}).ProtoReflect().Descriptor()
	assertFieldNames(t, appViewV3.Fields(), []protoreflect.Name{
		"org_id", "app_installation_id", "app_id", "app_release_digest",
		"lineage", "app_components", "effective_components", "receipts",
	})
	effectiveComponent := (&catalogv1.EffectiveMetadataComponent{}).
		ProtoReflect().Descriptor()
	assertFieldNames(t, effectiveComponent.Fields(), []protoreflect.Name{
		"component_kind", "component_format_version", "business_key",
		"content_digest", "canonical_behavior",
	})
	integrationView := (&catalogv1.WatchIntegrationBindingViewRequest{}).ProtoReflect().Descriptor()
	assertFieldNames(t, integrationView.Fields(), []protoreflect.Name{"after_catalog_revision"})
	integrationBinding := (&catalogv1.IntegrationBinding{}).ProtoReflect().Descriptor()
	assertFieldNames(t, integrationBinding.Fields(), []protoreflect.Name{
		"kind", "owner_pack", "pack_installation_id", "pack_payload_digest",
		"business_key", "definition_version", "credential_refs", "runtime_command",
	})
	runtimeCommandBinding := (&catalogv1.RuntimeCommandBinding{}).ProtoReflect().Descriptor()
	assertFieldNames(t, runtimeCommandBinding.Fields(), []protoreflect.Name{
		"command_kind", "payload_format_version", "definition_ref", "definition_version",
	})
	search := (&runtimev1.SearchRecordsRequest{}).ProtoReflect().Descriptor()
	assertFieldNames(t, search.Fields(), []protoreflect.Name{
		"object_ids", "term", "selected_fields", "limit", "min_catalog_revision", "search_fields",
		"object_plans",
	})
	searchPlan := (&runtimev1.SearchObjectPlan{}).ProtoReflect().Descriptor()
	assertFieldNames(t, searchPlan.Fields(), []protoreflect.Name{
		"object_id", "search_fields", "selected_fields", "limit",
	})
	searchScope := (&runtimev1.ReadSearchScopeOrderRequest{}).ProtoReflect().Descriptor()
	assertFieldNames(t, searchScope.Fields(), []protoreflect.Name{
		"object_ids", "min_catalog_revision",
	})
	searchScopeResponse := (&runtimev1.ReadSearchScopeOrderResponse{}).ProtoReflect().Descriptor()
	assertFieldNames(t, searchScopeResponse.Fields(), []protoreflect.Name{
		"object_ids", "receipts",
	})
	flow := (&runtimev1.ExecuteFlowRequest{}).ProtoReflect().Descriptor()
	assertFieldNames(t, flow.Fields(), []protoreflect.Name{
		"definition_ref", "definition_version", "idempotency_key", "canonical_inputs", "min_catalog_revision",
		"catalog_action",
	})
	previewAction := (&runtimev1.PreviewCatalogActionRequest{}).ProtoReflect().Descriptor()
	assertFieldNames(t, previewAction.Fields(), []protoreflect.Name{
		"mode", "canonical_inputs", "min_catalog_revision", "catalog_action", "record_id",
	})
	previewActionResponse := (&runtimev1.PreviewCatalogActionResponse{}).ProtoReflect().Descriptor()
	assertFieldNames(t, previewActionResponse.Fields(), []protoreflect.Name{
		"canonical_result", "receipts",
	})
	catalogAction := (&runtimev1.CatalogActionBinding{}).ProtoReflect().Descriptor()
	assertFieldNames(t, catalogAction.Fields(), []protoreflect.Name{
		"component_ref", "action_ref",
	})
	report := (&runtimev1.ReadReportRequest{}).ProtoReflect().Descriptor()
	assertFieldNames(t, report.Fields(), []protoreflect.Name{
		"report_id", "canonical_filters", "limit", "offset", "min_catalog_revision",
	})
	fileHeader := (&runtimev1.CreateFileHeader{}).ProtoReflect().Descriptor()
	assertFieldNames(t, fileHeader.Fields(), []protoreflect.Name{
		"idempotency_key", "parent_object_id", "parent_record_id", "file_name", "content_type",
		"content_length", "attachment_kind", "min_catalog_revision",
	})
	command := (&runtimev1.AcceptCommandRequest{}).ProtoReflect().Descriptor()
	assertFieldNames(t, command.Fields(), []protoreflect.Name{
		"command_id", "idempotency_key", "command_kind", "partition_key", "payload", "min_catalog_revision",
		"payload_format_version", "payload_digest",
	})
	applicationResultRequest := (&runtimev1.GetApplicationResultRequest{}).ProtoReflect().Descriptor()
	assertFieldNames(t, applicationResultRequest.Fields(), []protoreflect.Name{
		"command_id", "execution_ref_digest",
	})
	applicationResult := (&runtimev1.ApplicationResult{}).ProtoReflect().Descriptor()
	assertFieldNames(t, applicationResult.Fields(), []protoreflect.Name{
		"command_id", "execution_ref_digest", "outcome", "result_digest", "runtime_commit_receipt", "failure_code",
	})
	applicationResultResponse := (&runtimev1.GetApplicationResultResponse{}).ProtoReflect().Descriptor()
	assertFieldNames(t, applicationResultResponse.Fields(), []protoreflect.Name{
		"command_id", "execution_ref_digest", "state", "result",
	})
	outboundGenerationRead := (&runtimev1.ReadOutboundIntentGenerationRequest{}).ProtoReflect().Descriptor()
	assertFieldNames(t, outboundGenerationRead.Fields(), []protoreflect.Name{
		"after_generation",
	})
	outboundGeneration := (&runtimev1.ReadOutboundIntentGenerationResponse{}).ProtoReflect().Descriptor()
	assertFieldNames(t, outboundGeneration.Fields(), []protoreflect.Name{
		"generation", "receipts",
	})
	outboundList := (&runtimev1.ListPendingOutboundIntentsRequest{}).ProtoReflect().Descriptor()
	assertFieldNames(t, outboundList.Fields(), []protoreflect.Name{
		"limit", "min_catalog_revision", "max_operation_set_version",
	})
	if outboundList.Fields().ByName("max_intent_version") != nil {
		t.Fatal("logical-effect identity added wire version negotiation")
	}
	outboundIntent := (&runtimev1.OutboundIntent{}).ProtoReflect().Descriptor()
	assertFieldNames(t, outboundIntent.Fields(), []protoreflect.Name{
		"intent_id", "idempotency_key", "payload_format_version", "payload_digest",
		"catalog_revision", "operation", "source_object", "source_record_id",
		"connector_owner_key", "action_slot_id", "destination_slot_id", "bindings",
		"canonical_payload", "flow_developer_name", "flow_action_name", "logical_effect_root_id",
		"logical_effect_generation_id",
	})
	assertFieldNumbers(t, outboundIntent, []protoreflect.FieldNumber{
		1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 18, 19,
	})
	if got := outboundIntent.Fields().ByNumber(18); got == nil || got.Name() != "logical_effect_root_id" {
		t.Fatalf("OutboundIntent field 18 = %v, want logical_effect_root_id", got)
	}
	if got := outboundIntent.Fields().ByNumber(19); got == nil || got.Name() != "logical_effect_generation_id" {
		t.Fatalf("OutboundIntent field 19 = %v, want logical_effect_generation_id", got)
	}
	for _, absent := range []protoreflect.Name{"execution_ref_digest", "intent_version"} {
		if outboundIntent.Fields().ByName(absent) != nil {
			t.Fatalf("OutboundIntent retained forbidden identity field %q", absent)
		}
	}
	outboundAcknowledge := (&runtimev1.AcknowledgeOutboundIntentRequest{}).ProtoReflect().Descriptor()
	assertFieldNames(t, outboundAcknowledge.Fields(), []protoreflect.Name{
		"intent_id", "payload_digest", "catalog_revision", "outcome", "integration_command_id", "rejection_code",
	})
	outboundCommit := (&runtimev1.CommitOutboundResultRequest{}).ProtoReflect().Descriptor()
	assertFieldNames(t, outboundCommit.Fields(), []protoreflect.Name{
		"intent_id", "payload_digest", "catalog_revision", "integration_command_id", "remote_id",
		"result_format_version", "result_digest", "canonical_result",
	})
	outboundNoEffect := (&runtimev1.CommitOutboundNoEffectRequest{}).ProtoReflect().Descriptor()
	assertFieldNames(t, outboundNoEffect.Fields(), []protoreflect.Name{
		"intent_id", "payload_digest", "catalog_revision", "integration_command_id", "reason",
	})
	outboundServices := outboundNoEffect.ParentFile().Services()
	currentOutboundService := outboundServices.ByName("OutboundIntentService")
	if currentOutboundService == nil || currentOutboundService.Methods().Len() != 5 ||
		currentOutboundService.Methods().ByName("OpenOutboundMailAttachment") == nil ||
		currentOutboundService.Methods().ByName("CommitOutboundNoEffect") != nil {
		t.Fatalf("published OutboundIntentService method set changed: %v", currentOutboundService)
	}
	noEffectService := outboundServices.ByName("OutboundIntentNoEffectService")
	if noEffectService == nil || noEffectService.Methods().Len() != 1 ||
		noEffectService.Methods().ByName("CommitOutboundNoEffect") == nil {
		t.Fatalf("additive OutboundIntentNoEffectService shape = %v", noEffectService)
	}
	mailboxAuthorization := (&runtimev1.AuthorizeConnectedMailboxRequest{}).ProtoReflect().Descriptor()
	assertFieldNames(t, mailboxAuthorization.Fields(), []protoreflect.Name{
		"operation", "min_catalog_revision",
	})
	mailboxReauthorization := (&runtimev1.ReauthorizeConnectedMailboxRequest{}).ProtoReflect().Descriptor()
	assertFieldNames(t, mailboxReauthorization.Fields(), []protoreflect.Name{
		"reauthorization_handle", "min_catalog_revision",
	})
	permissions := (&runtimev1.ReadEffectivePermissionsRequest{}).ProtoReflect().Descriptor()
	assertFieldNames(t, permissions.Fields(), []protoreflect.Name{
		"target_principal_id", "min_catalog_revision", "selection",
	})
	permissionSelection := (&runtimev1.EffectivePermissionSelection{}).ProtoReflect().Descriptor()
	assertFieldNames(t, permissionSelection.Fields(), []protoreflect.Name{
		"sections", "resource_types",
	})
	permissionResponse := (&runtimev1.ReadEffectivePermissionsResponse{}).ProtoReflect().Descriptor()
	assertFieldNames(t, permissionResponse.Fields(), []protoreflect.Name{
		"system_permissions", "custom_permissions", "object_permissions",
		"field_permissions", "receipts", "application_permissions",
		"navigation_permissions", "record_type_permissions",
	})
	permissionAdminRead := (&runtimev1.ReadPermissionAdministrationRequest{}).ProtoReflect().Descriptor()
	assertFieldNames(t, permissionAdminRead.Fields(), []protoreflect.Name{
		"selector", "permission_set_id", "min_catalog_revision",
	})
	permissionAdminReadResponse := (&runtimev1.ReadPermissionAdministrationResponse{}).ProtoReflect().Descriptor()
	assertFieldNames(t, permissionAdminReadResponse.Fields(), []protoreflect.Name{
		"system_catalog", "system_grants", "record_type_catalog", "record_type_grants",
		"custom_catalog", "custom_grants", "receipts",
	})
	permissionAdminMutation := (&runtimev1.MutatePermissionAdministrationRequest{}).ProtoReflect().Descriptor()
	assertFieldNames(t, permissionAdminMutation.Fields(), []protoreflect.Name{
		"selector", "permission_set_id", "grants", "min_catalog_revision",
	})
	analyticsAuthoring := (&runtimev1.MutateAnalyticsDefinitionRequest{}).ProtoReflect().Descriptor()
	assertFieldNames(t, analyticsAuthoring.Fields(), []protoreflect.Name{
		"operation", "resource_id", "min_catalog_revision", "command_id", "dashboard", "folder", "report",
	})
	analyticsDashboard := (&runtimev1.AnalyticsDashboardDefinition{}).ProtoReflect().Descriptor()
	assertFieldNames(t, analyticsDashboard.Fields(), []protoreflect.Name{
		"name", "stable_name", "folder_id", "description", "layout_kind", "kind", "component_set",
	})
	analyticsReport := (&runtimev1.AnalyticsReportDefinition{}).ProtoReflect().Descriptor()
	assertFieldNames(t, analyticsReport.Fields(), []protoreflect.Name{
		"name", "stable_name", "folder_id", "description", "source_object", "source_ref",
		"display_mode", "scope", "column_set", "filter_set", "grouping_set", "date_filter", "clear_date_filter",
	})
	dateFilterOneof := analyticsReport.Fields().ByName("date_filter").ContainingOneof()
	clearDateFilterOneof := analyticsReport.Fields().ByName("clear_date_filter").ContainingOneof()
	if dateFilterOneof == nil || clearDateFilterOneof != dateFilterOneof || dateFilterOneof.Name() != "date_filter_change" {
		t.Fatalf("report date-filter actions do not share date_filter_change oneof")
	}
	analyticsFolder := (&runtimev1.AnalyticsFolderDefinition{}).ProtoReflect().Descriptor()
	assertFieldNames(t, analyticsFolder.Fields(), []protoreflect.Name{
		"name", "stable_name", "description", "kind", "access", "parent_folder_id",
	})
	analyticsAuthoringResponse := (&runtimev1.MutateAnalyticsDefinitionResponse{}).ProtoReflect().Descriptor()
	assertFieldNames(t, analyticsAuthoringResponse.Fields(), []protoreflect.Name{
		"resource_id", "receipts", "command_id",
	})
	resourceAccess := (&runtimev1.AccessResourceRequest{}).ProtoReflect().Descriptor()
	assertFieldNames(t, resourceAccess.Fields(), []protoreflect.Name{
		"operation", "resource_type", "resource_id", "grant_id", "grant", "grants",
		"access_level", "principal_type", "source_owner_id", "target_owner_id", "min_catalog_revision", "command_id",
	})
	resourceAccessResponse := (&runtimev1.AccessResourceResponse{}).ProtoReflect().Descriptor()
	assertFieldNames(t, resourceAccessResponse.Fields(), []protoreflect.Name{
		"grants", "receipts", "command_id", "affected_resources",
	})
	listViewsRead := (&runtimev1.ReadPrivateListViewsRequest{}).ProtoReflect().Descriptor()
	assertFieldNames(t, listViewsRead.Fields(), []protoreflect.Name{
		"selector", "object_id", "view_id", "min_catalog_revision",
	})
	listViewsMutate := (&runtimev1.MutatePrivateListViewRequest{}).ProtoReflect().Descriptor()
	assertFieldNames(t, listViewsMutate.Fields(), []protoreflect.Name{
		"operation", "object_id", "view_id", "patch", "min_catalog_revision",
	})
	objectAdminIndex := (&runtimev1.ReadObjectAdminIndexRequest{}).ProtoReflect().Descriptor()
	assertFieldNames(t, objectAdminIndex.Fields(), []protoreflect.Name{"min_catalog_revision"})
	layoutAdminWorkspace := (&runtimev1.ReadLayoutAdminWorkspaceResponse{}).ProtoReflect().Descriptor()
	assertFieldNames(t, layoutAdminWorkspace.Fields(), []protoreflect.Name{
		"object_id", "layouts", "assignments", "receipts",
	})
	storedLayout := (&runtimev1.ReadStoredLayoutResponse{}).ProtoReflect().Descriptor()
	assertFieldNames(t, storedLayout.Fields(), []protoreflect.Name{
		"layout_id", "object_id", "stored_document", "receipts",
	})
	validationRuleIndex := (&runtimev1.ReadValidationRuleAdminIndexResponse{}).ProtoReflect().Descriptor()
	assertFieldNames(t, validationRuleIndex.Fields(), []protoreflect.Name{
		"object_id", "rules", "receipts",
	})
	approvalNotificationRequest := (&runtimev1.ReadApprovalNotificationFlowsRequest{}).ProtoReflect().Descriptor()
	assertFieldNames(t, approvalNotificationRequest.Fields(), []protoreflect.Name{"min_catalog_revision"})
	approvalNotificationDescriptor := (&runtimev1.ApprovalNotificationFlowDescriptor{}).ProtoReflect().Descriptor()
	assertFieldNames(t, approvalNotificationDescriptor.Fields(), []protoreflect.Name{
		"name", "label", "description",
	})
	approvalNotificationResponse := (&runtimev1.ReadApprovalNotificationFlowsResponse{}).ProtoReflect().Descriptor()
	assertFieldNames(t, approvalNotificationResponse.Fields(), []protoreflect.Name{"flows", "receipts"})
	pageLayoutRequest := (&runtimev1.ResolvePageLayoutRequest{}).ProtoReflect().Descriptor()
	assertFieldNames(t, pageLayoutRequest.Fields(), []protoreflect.Name{
		"object_id", "record_type_ids", "min_catalog_revision",
	})
	pageLayoutResponse := (&runtimev1.ResolvePageLayoutResponse{}).ProtoReflect().Descriptor()
	assertFieldNames(t, pageLayoutResponse.Fields(), []protoreflect.Name{
		"object_id", "selections", "layouts", "receipts",
	})

	methods := []string{
		catalogv1.ConsumerViewService_GetAppMetadataView_FullMethodName,
		catalogv1.ConsumerViewService_WatchAppMetadataView_FullMethodName,
		catalogv1.ConsumerViewService_GetAppMetadataViewV2_FullMethodName,
		catalogv1.ConsumerViewService_WatchAppMetadataViewV2_FullMethodName,
		catalogv1.AppMetadataViewV3Service_GetAppMetadataViewV3_FullMethodName,
		catalogv1.AppMetadataViewV3Service_WatchAppMetadataViewV3_FullMethodName,
		catalogv1.ConsumerViewService_GetIntegrationBindingView_FullMethodName,
		catalogv1.ConsumerViewService_WatchIntegrationBindingView_FullMethodName,
		runtimev1.RecordSearchService_SearchRecords_FullMethodName,
		runtimev1.RecordSearchService_ReadSearchScopeOrder_FullMethodName,
		runtimev1.FlowExecutionService_ExecuteFlow_FullMethodName,
		runtimev1.FlowExecutionService_PreviewCatalogAction_FullMethodName,
		runtimev1.ReportReadService_ReadReport_FullMethodName,
		runtimev1.AuthorizedFilesService_CreateFile_FullMethodName,
		runtimev1.AuthorizedFilesService_OpenFile_FullMethodName,
		runtimev1.AuthorizedFilesService_DeleteFile_FullMethodName,
		runtimev1.ApplicationResultService_GetApplicationResult_FullMethodName,
		runtimev1.OutboundIntentService_ReadOutboundIntentGeneration_FullMethodName,
		runtimev1.OutboundIntentService_ListPendingOutboundIntents_FullMethodName,
		runtimev1.OutboundIntentService_AcknowledgeOutboundIntent_FullMethodName,
		runtimev1.OutboundIntentService_CommitOutboundResult_FullMethodName,
		runtimev1.OutboundIntentNoEffectService_CommitOutboundNoEffect_FullMethodName,
		runtimev1.OutboundIntentService_OpenOutboundMailAttachment_FullMethodName,
		runtimev1.ConnectedMailboxAuthorizationService_AuthorizeConnectedMailbox_FullMethodName,
		runtimev1.ConnectedMailboxAuthorizationService_ReauthorizeConnectedMailbox_FullMethodName,
		runtimev1.CommandAcceptanceService_AcceptCommand_FullMethodName,
		runtimev1.EffectivePermissionService_ReadEffectivePermissions_FullMethodName,
		runtimev1.PrivateListViewService_ReadPrivateListViews_FullMethodName,
		runtimev1.PrivateListViewService_MutatePrivateListView_FullMethodName,
		runtimev1.MetadataAdminReadService_ReadObjectAdminIndex_FullMethodName,
		runtimev1.MetadataAdminReadService_ReadLayoutAdminWorkspace_FullMethodName,
		runtimev1.MetadataAdminReadService_ReadStoredLayout_FullMethodName,
		runtimev1.MetadataAdminReadService_ReadValidationRuleAdminIndex_FullMethodName,
		runtimev1.ApprovalNotificationFlowReadService_ReadApprovalNotificationFlows_FullMethodName,
		runtimev1.PageLayoutResolutionService_ResolvePageLayout_FullMethodName,
		runtimev1.PermissionAdministrationService_ReadPermissionAdministration_FullMethodName,
		runtimev1.PermissionAdministrationService_MutatePermissionAdministration_FullMethodName,
		runtimev1.AnalyticsAuthoringService_MutateAnalyticsDefinition_FullMethodName,
		runtimev1.ResourceAccessService_AccessResource_FullMethodName,
		runtimev1.LayoutAuthoringService_Submit_FullMethodName,
		runtimev1.LayoutAuthoringService_GetCommand_FullMethodName,
		runtimev1.LayoutAuthoringService_ReadWorkspace_FullMethodName,
		runtimev1.LayoutAuthoringService_ReadStoredLayout_FullMethodName,
	}
	for _, method := range methods {
		if !strings.HasPrefix(method, "/nexuscrm.runtime.v1.") &&
			!strings.HasPrefix(method, "/nexuscrm.catalog.v1.") {
			t.Fatalf("Platform API method %q escaped the private Catalog/Runtime v1 namespaces", method)
		}
		for _, forbidden := range []string{"Salesforce", "SObject", "SOQL", "/services/data"} {
			if strings.Contains(strings.ToLower(method), strings.ToLower(forbidden)) {
				t.Fatalf("product vocabulary %q entered Platform API method %q", forbidden, method)
			}
		}
	}
}
