package outboundintentv1

import (
	"crypto/sha256"
	"encoding/hex"
	"strings"
)

// IntegrationScopeDigest is the stable digest of an authorized application
// scope used by the Integration V2 identity protocol. Catalog revision is
// deliberately absent: a serving revision change cannot move an identity.
// This is a pure identity codec, not an authority check. Callers must obtain
// scope from trusted context and validate identifiers before using the hash.
func IntegrationScopeDigest(scope LogicalEffectScope) string {
	return integrationIdentityDigest("\x00",
		scope.OrgID, scope.AppInstallationID, scope.AuthorizedWorkloadID,
	)
}

// IntegrationLinkKeyV2 identifies one local owner/action/destination lane in
// the shared Integration V2 identity protocol. Its historical discriminator,
// separator and prefix are compatibility bytes; neither Runtime nor
// Integration may independently reinterpret them. Inputs must already be
// authorized, validated identifiers (in particular, no control characters).
// The returned key is not proof of remote ownership or provider completion.
func IntegrationLinkKeyV2(
	scope LogicalEffectScope,
	connectorOwnerKey, actionSlotID, sourceObject, sourceRecordID, destinationSlotID string,
) string {
	return "integration_link_v2:" + integrationIdentityDigest("\x1f",
		scope.OrgID, scope.AppInstallationID, scope.AuthorizedWorkloadID,
		connectorOwnerKey, actionSlotID, "PushToConnector",
		sourceObject, sourceRecordID, destinationSlotID,
	)
}

// IntegrationRemoteLocatorHash identifies one remote resource within its
// complete authorized application, connector owner and destination scope.
// The existing protocol trims surrounding remote-ID whitespace; it preserves
// all other bytes and case. Callers still compare complete identities and
// authoritative receipts; this digest alone is not completion evidence.
func IntegrationRemoteLocatorHash(
	scope LogicalEffectScope,
	connectorOwnerKey, destinationSlotID, remoteID string,
) string {
	return integrationIdentityDigest("\x1f",
		scope.OrgID, scope.AppInstallationID, scope.AuthorizedWorkloadID,
		connectorOwnerKey, destinationSlotID, strings.TrimSpace(remoteID),
	)
}

func integrationIdentityDigest(separator string, parts ...string) string {
	sum := sha256.Sum256([]byte(strings.Join(parts, separator)))
	return hex.EncodeToString(sum[:])
}
