package app

import (
	"context"
	"crypto/sha256"
	"database/sql"
	"encoding/json"
	"fmt"
	"math/big"
	"strings"
	"time"

	"github.com/tidbcloud/AgentTeam/internal/core/domain"
	"github.com/tidbcloud/AgentTeam/internal/core/identifiers"
	"github.com/tidbcloud/AgentTeam/internal/coredb"
	"github.com/tidbcloud/AgentTeam/internal/store/coordinator"
	"github.com/tidbcloud/AgentTeam/internal/store/message"
	"github.com/tidbcloud/AgentTeam/internal/store/serviceaccount"
)

const (
	platformBroadcastMetadataKey = "platformServiceAccountBroadcast"
	platformBroadcastAuditBasis  = "service_grant+platform_service_account_delivery"
	platformBroadcastWorkerID    = "agentteam.platform-service-account-broadcast"
)

type platformBroadcastStoredPlan struct {
	Content     string                   `json:"content"`
	MessageType string                   `json:"messageType,omitempty"`
	Metadata    map[string]any           `json:"metadata,omitempty"`
	Assets      []platformBroadcastAsset `json:"assets,omitempty"`
}

type platformBroadcastAsset struct {
	SourceAssetRef string `json:"sourceAssetRef"`
	ContentHash    string `json:"contentHash"`
	MediaType      string `json:"mediaType,omitempty"`
	SizeBytes      int64  `json:"sizeBytes"`
	ClientLabel    string `json:"clientLabel,omitempty"`
}

type platformBroadcastDeliveryAuthority struct {
	deliveryID             string
	deliveryVersion        int64
	broadcastID            string
	platformAccountID      string
	workspaceID            string
	broadcastSeq           int64
	requiredGeneration     int64
	placementEpoch         int64
	currentPlacementEpoch  int64
	leaseExpiresAt         time.Time
	payloadSnapshot        []byte
	payloadDigest          string
	operatorPrincipalID    string
	correlationID          string
	instanceID             string
	instanceCursor         int64
	instanceProvisioning   string
	account                serviceaccount.Account
	serviceGrantID         string
	serviceGrantPolicy     int64
	serviceTargetBindingID string
}

// DeliverPlatformServiceAccountBroadcast writes the ordinary workspace-local
// Service Account message and settles the delivery/cursor under one lease-
// fenced transaction. The returned id is the authoritative local message id.
func (store *Store) DeliverPlatformServiceAccountBroadcast(ctx context.Context, deliveryID string, leaseToken string, now time.Time) (string, error) {
	if store == nil || store.db == nil {
		return "", fmt.Errorf("app store is not configured")
	}
	deliveryID = strings.TrimSpace(deliveryID)
	leaseToken = strings.TrimSpace(leaseToken)
	if deliveryID == "" || leaseToken == "" {
		return "", badRequest("deliveryId and leaseToken are required")
	}
	if now.IsZero() {
		now = time.Now().UTC()
	} else {
		now = now.UTC()
	}
	messageID, err := identifiers.NewMessageID()
	if err != nil {
		return "", fmt.Errorf("generate platform broadcast message id: %w", err)
	}
	var deliveredMessageID string
	var committedMessage postCommitMessage
	err = coordinator.New(store.db).Run(ctx, "deliver platform service-account broadcast", func(tx coredb.Tx) error {
		authority, err := loadPlatformBroadcastDeliveryAuthority(ctx, tx, deliveryID, leaseToken)
		if err != nil {
			return err
		}
		if !authority.leaseExpiresAt.After(now) {
			return conflict("platform broadcast delivery lease expired")
		}
		if authority.instanceProvisioning != "ready" || authority.account.AudienceState != serviceaccount.AudienceStateReady || authority.account.EffectiveAudienceVersion != authority.account.AudiencePolicyVersion {
			return conflict("platform service account workspace instance is not ready")
		}
		if authority.instanceCursor != authority.broadcastSeq-1 {
			return conflict("platform broadcast workspace sequence is not contiguous")
		}
		if authority.currentPlacementEpoch != authority.placementEpoch {
			return conflict("platform broadcast workspace placement epoch changed")
		}
		var plan platformBroadcastStoredPlan
		if err := json.Unmarshal(authority.payloadSnapshot, &plan); err != nil {
			return fmt.Errorf("decode platform broadcast message plan: %w", err)
		}
		attachmentIDs, err := materializePlatformBroadcastAssets(ctx, tx, authority, plan.Assets, now)
		if err != nil {
			return err
		}
		metadata := message.CopyMessageMetadata(plan.Metadata)
		if metadata == nil {
			metadata = make(map[string]any, 1)
		}
		if _, reserved := metadata[platformBroadcastMetadataKey]; reserved {
			return conflict("platform broadcast snapshot contains reserved metadata")
		}
		metadata[platformBroadcastMetadataKey] = map[string]any{
			"broadcastId":         authority.broadcastID,
			"broadcastSeq":        authority.broadcastSeq,
			"deliveryId":          authority.deliveryID,
			"payloadDigest":       authority.payloadDigest,
			"operatorPrincipalId": authority.operatorPrincipalID,
			"causedByActor": map[string]any{
				"actorType": "platform_operator", "principalId": authority.operatorPrincipalID,
			},
			"executionActor": map[string]any{
				"actorType": "internal_service", "principalId": platformBroadcastWorkerID,
			},
			"permissionBasis": map[string]any{
				"kind":       platformBroadcastAuditBasis,
				"grantId":    authority.serviceGrantID,
				"deliveryId": authority.deliveryID,
			},
		}
		target := message.ThreadAccess{
			ThreadID: authority.account.MessageScopeID, ThreadType: domain.ThreadTypeChannel,
			ChannelID: authority.account.MessageScopeID, ChannelName: authority.account.Name,
		}
		emptyRoutingPlan := message.AgentRoutingPlan{}
		source := message.ContributionSource{
			Kind:    message.ContributionSourceKindServiceDirectPost,
			RefType: message.ContributionSourceRefTypeMessage,
			RefID:   messageID, Label: authority.account.Name,
		}
		delivery, err := store.appendMessageToThread(ctx, tx,
			authority.account.AuthorMemberID, domain.MemberTypeService,
			target, strings.TrimSpace(plan.Content), attachmentIDs,
			appendMessageOptions{
				MessageType: plan.MessageType, ExplicitRoutingPlan: &emptyRoutingPlan,
				Metadata: metadata, Source: source,
				RoutingPrincipalMemberID:   authority.account.AuthorMemberID,
				NotifyPrincipalMemberID:    authority.account.AuthorMemberID,
				IdempotencySubjectMemberID: authority.account.AuthorMemberID,
				ClientMessageID:            "platform-broadcast:" + authority.broadcastID,
				ForceScopeID:               authority.account.MessageScopeID, ForceMessageID: messageID,
				AllocateWorkspaceGlobalSeq: true, CreatedAt: now,
			},
			messageAppendStoreOwnedRecoverable,
		)
		if err != nil {
			return err
		}
		source.RefID = delivery.MessageID
		delivery.Message.Source = source.Normalize()
		delivery.Message.ChannelType = serviceaccount.ServiceKind
		delivery.Message.ChannelName = authority.account.Name
		delivery.Message.ChannelDisplayName = authority.account.Name
		delivery.MentionContext.ChannelType = serviceaccount.ServiceKind
		appMessage := appMessageFromDelivery(authority.account.MessageScopeID, message.AuthorProfile{
			ActorType: message.AuthorActorTypeService, PrincipalID: authority.account.PrincipalID,
			MemberID:    authority.account.AuthorMemberID,
			TargetID:    "service-account:" + authority.account.ID,
			DisplayName: authority.account.Name,
			ServiceKind: message.AuthorServiceKindServiceAccount, ServiceSlug: authority.account.ID,
		}, delivery)
		appMessage.ChannelType = serviceaccount.ServiceKind
		appMessage.Source = source.Normalize()
		messages := []message.AppMessage{appMessage}
		if err := attachServiceAuthorProfilePresentationWithQueryer(ctx, tx, authority.workspaceID, messages); err != nil {
			return fmt.Errorf("attach platform service-account author presentation: %w", err)
		}
		appMessage = messages[0]
		if err := attachResolvedMentionsForSentAppMessage(ctx, tx, authority.workspaceID, &appMessage); err != nil {
			return err
		}
		attachAppMessageToDelivery(&delivery, &appMessage)
		if !delivery.IdempotentReplay {
			if err := insertPlatformBroadcastMessageAudit(ctx, serviceaccount.New(store.db).InTx(tx), authority, delivery); err != nil {
				return err
			}
		}
		delivery, committedMessage, err = store.preparePostCommitMessage(
			ctx,
			tx,
			authority.workspaceID,
			committedMessageProducerPlatformServiceAccountBroadcast,
			delivery,
		)
		if err != nil {
			return err
		}
		cursorResult, err := tx.Exec(ctx, `
UPDATE platform_service_account_workspace_instances
SET last_applied_broadcast_seq = $3, version = version + 1, updated_at = $4
WHERE id = $1 AND workspace_id = $2
  AND last_applied_broadcast_seq = $3 - 1
`, authority.instanceID, authority.workspaceID, authority.broadcastSeq, now)
		if err != nil {
			return fmt.Errorf("settle platform broadcast workspace cursor: %w", err)
		}
		if cursorResult.RowsAffected() != 1 {
			return conflict("platform broadcast workspace cursor changed")
		}
		settlement, err := tx.Exec(ctx, `
UPDATE platform_service_account_broadcast_deliveries
SET state = 'delivered', local_message_id = $3, outcome = 'delivered',
    last_error = '', lease_token = NULL, lease_expires_at = NULL,
    version = version + 1, updated_at = $4, completed_at = COALESCE(completed_at, $4)
WHERE id = $1 AND lease_token = $2 AND state = 'leased'
`, authority.deliveryID, leaseToken, delivery.MessageID, now)
		if err != nil {
			return fmt.Errorf("settle platform broadcast delivery: %w", err)
		}
		if settlement.RowsAffected() != 1 {
			return conflict("platform broadcast delivery lease changed")
		}
		deliveredMessageID = delivery.MessageID
		return nil
	})
	if err != nil {
		return "", err
	}
	store.emitPostCommitMessage(ctx, committedMessage)
	return deliveredMessageID, nil
}

func loadPlatformBroadcastDeliveryAuthority(ctx context.Context, tx coredb.Tx, deliveryID, leaseToken string) (platformBroadcastDeliveryAuthority, error) {
	var authority platformBroadcastDeliveryAuthority
	var platformAccountID sql.NullString
	err := tx.QueryRow(ctx, `
SELECT
  delivery.id, delivery.version, delivery.broadcast_id,
  delivery.platform_service_account_id, delivery.workspace_id,
  delivery.broadcast_seq, delivery.required_provisioning_generation,
  delivery.placement_epoch, delivery.lease_expires_at,
  broadcast.payload_snapshot, broadcast.payload_digest,
  broadcast.operator_principal_id, broadcast.correlation_id,
  instance.id, instance.last_applied_broadcast_seq, instance.provisioning_state,
  COALESCE((
    SELECT placement.placement_epoch
    FROM workspace_placements placement
    WHERE placement.workspace_id = instance.workspace_id
  ), 1),
  local.id, local.principal_id, local.workspace_id, local.management_kind,
  local.platform_service_account_id, local.service_installation_id,
  local.service_member_id, local.author_member_id, local.message_scope_id,
  local.name, local.description,
  COALESCE(local.avatar_asset_id, ''), local.applied_platform_profile_version,
  local.audience_policy_version,
  local.effective_audience_version, local.audience_state,
  local.version, COALESCE(local.created_by_operator_user_id, ''),
  service_grant.id, service_grant.policy_version, binding.id
FROM platform_service_account_broadcast_deliveries delivery
JOIN platform_service_account_broadcasts broadcast ON broadcast.id = delivery.broadcast_id
JOIN platform_service_accounts root ON root.id = delivery.platform_service_account_id
JOIN platform_service_account_workspace_instances instance
  ON instance.platform_service_account_id = delivery.platform_service_account_id
 AND instance.workspace_id = delivery.workspace_id
 AND instance.local_service_account_id = delivery.local_service_account_id
JOIN service_accounts local
  ON local.id = delivery.local_service_account_id
 AND local.workspace_id = delivery.workspace_id
 AND local.management_kind = 'platform'
JOIN service_installations installation
  ON installation.id = local.service_installation_id
 AND installation.workspace_id = local.workspace_id
 AND installation.service_definition_id = 'svcdef_service_account'
 AND installation.service_kind = 'service_account'
 AND installation.status = 'active'
JOIN service_members service_member
  ON service_member.id = local.service_member_id
 AND service_member.workspace_id = local.workspace_id
 AND service_member.service_installation_id = installation.id
 AND service_member.member_id = local.author_member_id
 AND service_member.service_kind = 'service_account'
 AND service_member.status = 'active'
JOIN members durable_author
  ON durable_author.id = local.author_member_id
 AND durable_author.workspace_id = local.workspace_id
 AND durable_author.type = 'service'
 AND durable_author.status = 'active'
JOIN scopes scope
  ON scope.id = local.message_scope_id
 AND scope.workspace_id = local.workspace_id
 AND scope.type = 'service_account'
 AND scope.status = 'active'
 AND scope.archived_at IS NULL
JOIN service_grants service_grant
  ON service_grant.service_installation_id = installation.id
 AND service_grant.workspace_id = local.workspace_id
 AND service_grant.service_definition_id = 'svcdef_service_account'
 AND service_grant.service_kind = 'service_account'
 AND service_grant.scope = 'message.write'
 AND service_grant.revoked_at IS NULL
 AND (service_grant.expires_at IS NULL OR service_grant.expires_at > CURRENT_TIMESTAMP)
JOIN service_target_bindings binding
  ON binding.service_installation_id = installation.id
 AND binding.workspace_id = local.workspace_id
 AND binding.service_definition_id = 'svcdef_service_account'
 AND binding.service_member_id = local.service_member_id
 AND binding.service_kind = 'service_account'
 AND binding.target_kind = 'service_account'
 AND binding.target_ref = CONCAT('service-account:', local.id)
 AND binding.delivery_scope_id = local.message_scope_id
 AND binding.permission_check_scope_id = local.message_scope_id
 AND binding.authority_subject_member_id = local.author_member_id
 AND binding.status = 'active'
 AND binding.removed_at IS NULL
WHERE delivery.id = $1
  AND delivery.lease_token = $2
  AND delivery.state = 'leased'
  AND delivery.recipient_eligible = TRUE
FOR UPDATE
`, deliveryID, leaseToken).Scan(
		&authority.deliveryID, &authority.deliveryVersion, &authority.broadcastID,
		&authority.platformAccountID, &authority.workspaceID,
		&authority.broadcastSeq, &authority.requiredGeneration,
		&authority.placementEpoch, &authority.leaseExpiresAt,
		&authority.payloadSnapshot, &authority.payloadDigest,
		&authority.operatorPrincipalID, &authority.correlationID,
		&authority.instanceID, &authority.instanceCursor, &authority.instanceProvisioning,
		&authority.currentPlacementEpoch,
		&authority.account.ID, &authority.account.PrincipalID, &authority.account.WorkspaceID,
		&authority.account.ManagementKind, &platformAccountID,
		&authority.account.ServiceInstallationID, &authority.account.ServiceMemberID,
		&authority.account.AuthorMemberID, &authority.account.MessageScopeID,
		&authority.account.Name, &authority.account.Description,
		&authority.account.AvatarAssetID, &authority.account.AppliedPlatformProfileVersion,
		&authority.account.AudiencePolicyVersion,
		&authority.account.EffectiveAudienceVersion, &authority.account.AudienceState,
		&authority.account.Version, &authority.account.CreatedByOperatorUserID,
		&authority.serviceGrantID, &authority.serviceGrantPolicy, &authority.serviceTargetBindingID,
	)
	if err != nil {
		if coredb.IsNotFound(err) {
			return platformBroadcastDeliveryAuthority{}, conflict("platform broadcast delivery authority or lease is unavailable")
		}
		return platformBroadcastDeliveryAuthority{}, fmt.Errorf("resolve platform broadcast delivery authority: %w", err)
	}
	authority.account.PlatformServiceAccountID = strings.TrimSpace(platformAccountID.String)
	if authority.account.PlatformServiceAccountID != authority.platformAccountID || authority.account.PrincipalID != authority.platformAccountID {
		return platformBroadcastDeliveryAuthority{}, conflict("platform broadcast local principal does not match its root account")
	}
	return authority, nil
}

func materializePlatformBroadcastAssets(ctx context.Context, tx coredb.Tx, authority platformBroadcastDeliveryAuthority, manifest []platformBroadcastAsset, now time.Time) ([]string, error) {
	rows, err := tx.Query(ctx, `
SELECT asset_ordinal, source_asset_ref, content_hash, media_type, size_bytes,
       local_attachment_id, state
FROM platform_service_account_delivery_assets
WHERE delivery_id = $1
ORDER BY asset_ordinal ASC
FOR UPDATE
`, authority.deliveryID)
	if err != nil {
		return nil, fmt.Errorf("list platform broadcast delivery assets: %w", err)
	}
	type assetRow struct {
		ordinal           int
		sourceAssetRef    string
		contentHash       string
		mediaType         string
		sizeBytes         int64
		localAttachmentID sql.NullString
		state             string
	}
	assets := make([]assetRow, 0, len(manifest))
	for rows.Next() {
		var asset assetRow
		if err := rows.Scan(
			&asset.ordinal, &asset.sourceAssetRef, &asset.contentHash,
			&asset.mediaType, &asset.sizeBytes, &asset.localAttachmentID, &asset.state,
		); err != nil {
			rows.Close()
			return nil, fmt.Errorf("scan platform broadcast delivery asset: %w", err)
		}
		assets = append(assets, asset)
	}
	if err := rows.Err(); err != nil {
		rows.Close()
		return nil, fmt.Errorf("iterate platform broadcast delivery assets: %w", err)
	}
	rows.Close()
	if len(assets) != len(manifest) {
		return nil, conflict("platform broadcast delivery asset manifest is incomplete")
	}

	attachmentIDs := make([]string, 0, len(manifest))
	ordinal := 0
	for _, asset := range assets {
		if asset.ordinal != ordinal {
			return nil, conflict("platform broadcast delivery asset ordinals are not contiguous")
		}
		if asset.sourceAssetRef != manifest[ordinal].SourceAssetRef ||
			asset.contentHash != manifest[ordinal].ContentHash ||
			asset.mediaType != manifest[ordinal].MediaType ||
			asset.sizeBytes != manifest[ordinal].SizeBytes {
			return nil, conflict("platform broadcast delivery asset differs from its immutable snapshot")
		}
		localAttachmentID := strings.TrimSpace(asset.localAttachmentID.String)
		if strings.TrimSpace(asset.state) != "materialized" || localAttachmentID == "" {
			var filename, contentType, storageDriver string
			var sourceSize int64
			var objectKey sql.NullString
			var payload []byte
			var payloadPresent bool
			if err := tx.QueryRow(ctx, `
SELECT filename, content_type, size_bytes, storage_driver, object_key,
       payload, payload IS NOT NULL
FROM attachments
WHERE id = $1
FOR UPDATE
`, asset.sourceAssetRef).Scan(
				&filename, &contentType, &sourceSize, &storageDriver,
				&objectKey, &payload, &payloadPresent,
			); err != nil {
				if coredb.IsNotFound(err) {
					return nil, conflict("platform broadcast source asset is unavailable")
				}
				return nil, fmt.Errorf("load platform broadcast source asset: %w", err)
			}
			if sourceSize != asset.sizeBytes || (asset.mediaType != "" && contentType != asset.mediaType) {
				return nil, conflict("platform broadcast source asset metadata changed")
			}
			if payloadPresent {
				digest := sha256.Sum256(payload)
				if fmt.Sprintf("%x", digest[:]) != asset.contentHash {
					return nil, conflict("platform broadcast source asset content changed")
				}
			}
			if label := strings.TrimSpace(manifest[ordinal].ClientLabel); label != "" {
				filename = label
			}
			localAttachmentID = platformDeterministicMessageID("att", "platform-broadcast-delivery-asset", authority.deliveryID, fmt.Sprint(ordinal))
			var targetObjectKey any
			if objectKey.Valid && strings.TrimSpace(objectKey.String) != "" {
				targetObjectKey = strings.TrimSpace(objectKey.String)
			}
			if _, err := tx.Exec(ctx, `
INSERT INTO attachments (
    id, workspace_id, scope_id, uploaded_by_member_id, message_id,
    filename, content_type, size_bytes, storage_driver, object_key,
    payload, created_at
) VALUES ($1, $2, $3, $4, NULL, $5, $6, $7, $8, $9, $10, $11)
ON DUPLICATE KEY UPDATE id = id
`, localAttachmentID, authority.workspaceID, authority.account.MessageScopeID,
				authority.account.AuthorMemberID, filename, contentType, sourceSize,
				storageDriver, targetObjectKey, payload, now); err != nil {
				return nil, fmt.Errorf("materialize platform broadcast attachment: %w", err)
			}
			var matches bool
			if err := tx.QueryRow(ctx, `
SELECT EXISTS (
  SELECT 1 FROM attachments
  WHERE id = $1 AND workspace_id = $2 AND scope_id = $3
    AND uploaded_by_member_id = $4 AND message_id IS NULL
    AND filename = $5 AND content_type = $6 AND size_bytes = $7
    AND storage_driver = $8
)
`, localAttachmentID, authority.workspaceID, authority.account.MessageScopeID,
				authority.account.AuthorMemberID, filename, contentType, sourceSize, storageDriver).Scan(&matches); err != nil {
				return nil, fmt.Errorf("verify platform broadcast attachment: %w", err)
			}
			if !matches {
				return nil, conflict("platform broadcast attachment id is bound to another target")
			}
			if _, err := tx.Exec(ctx, `
UPDATE platform_service_account_delivery_assets
SET local_attachment_id = $3, state = 'materialized',
    version = version + 1, updated_at = $4
WHERE delivery_id = $1 AND asset_ordinal = $2
`, authority.deliveryID, ordinal, localAttachmentID, now); err != nil {
				return nil, fmt.Errorf("settle platform broadcast delivery asset: %w", err)
			}
		}
		attachmentIDs = append(attachmentIDs, localAttachmentID)
		ordinal++
	}
	return attachmentIDs, nil
}

func insertPlatformBroadcastMessageAudit(ctx context.Context, accountTx *serviceaccount.TxStore, authority platformBroadcastDeliveryAuthority, delivery message.MessageDelivery) error {
	metadata, err := json.Marshal(map[string]any{
		"broadcastId":                    authority.broadcastID,
		"broadcastSeq":                   authority.broadcastSeq,
		"deliveryId":                     authority.deliveryID,
		"deliveryVersion":                authority.deliveryVersion,
		"placementEpoch":                 authority.placementEpoch,
		"requiredProvisioningGeneration": authority.requiredGeneration,
		"payloadDigest":                  authority.payloadDigest,
		"durableAuthorMemberId":          authority.account.AuthorMemberID,
		"serviceInstallationId":          authority.account.ServiceInstallationID,
		"serviceMemberId":                authority.account.ServiceMemberID,
		"routingPrincipalMemberId":       authority.account.AuthorMemberID,
		"notifyPrincipalMemberId":        authority.account.AuthorMemberID,
		"idempotencySubjectMemberId":     authority.account.AuthorMemberID,
		"serviceGrantPolicyVersion":      authority.serviceGrantPolicy,
		"serviceTargetBindingId":         authority.serviceTargetBindingID,
		"workspaceGlobalSeq":             delivery.GlobalSeq,
		"sourceKind":                     message.ContributionSourceKindServiceDirectPost,
	})
	if err != nil {
		return fmt.Errorf("encode platform broadcast message audit: %w", err)
	}
	return accountTx.InsertAuditEvent(ctx, serviceaccount.AuditEvent{
		ID:          platformBroadcastMessageAuditID(delivery.MessageID),
		WorkspaceID: authority.workspaceID, ServiceAccountID: authority.account.ID,
		PlatformServiceAccountID: authority.platformAccountID,
		EventType:                "platform_service_account.broadcast_message_created",
		SubjectType:              "message", SubjectID: delivery.MessageID, SubjectVersion: 1,
		ActorType: message.AuthorActorTypeService, ActorID: authority.platformAccountID,
		CausedByActorType: "platform_operator", CausedByActorID: authority.operatorPrincipalID,
		ExecutionActorType: "internal_service", ExecutionActorID: platformBroadcastWorkerID,
		PermissionBasisKind: platformBroadcastAuditBasis,
		PermissionBasisRef:  authority.serviceGrantID + ":" + authority.deliveryID,
		CorrelationID:       authority.correlationID, Metadata: metadata,
		CreatedAt: delivery.Message.Timestamp.UTC(),
	})
}

func platformBroadcastMessageAuditID(messageID string) string {
	return platformDeterministicMessageID("saaudit", "platform-broadcast-message-audit", messageID)
}

func platformDeterministicMessageID(prefix, namespace string, parts ...string) string {
	payload := strings.TrimSpace(namespace)
	for _, part := range parts {
		payload += "\x00" + strings.TrimSpace(part)
	}
	digest := sha256.Sum256([]byte(payload))
	suffix := new(big.Int).SetBytes(digest[:9]).Text(36)
	if len(suffix) < 14 {
		suffix = strings.Repeat("0", 14-len(suffix)) + suffix
	}
	return strings.TrimSpace(prefix) + "_" + suffix
}
