package webhook

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

// RemoteCallbackSignature computes the HMAC signature attached to external
// App callback deliveries. Keep this narrow helper even though the legacy
// generic remote-webhook surface has been retired: callback App delivery still
// uses the same signature contract.
func RemoteCallbackSignature(secret string, payload []byte) string {
	mac := hmac.New(sha256.New, []byte(strings.TrimSpace(secret)))
	_, _ = mac.Write(payload)
	return hex.EncodeToString(mac.Sum(nil))
}

// DeliveryKey returns a stable delivery key from an optional delivery header or event payload.
func DeliveryKey(deliveryHeader string, eventType string, payload []byte) string {
	trimmedDelivery := strings.TrimSpace(deliveryHeader)
	if trimmedDelivery != "" {
		return trimmedDelivery
	}

	digest := sha256.Sum256(append([]byte(strings.TrimSpace(eventType)+"\n"), payload...))
	return "sha256:" + hex.EncodeToString(digest[:])
}

// StringValue extracts and trims a string value from an arbitrary JSON value.
func StringValue(value any) string {
	switch typed := value.(type) {
	case string:
		return strings.TrimSpace(typed)
	default:
		return ""
	}
}
