package delivery

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

// dispatchSignatureHeader carries the HMAC over a dispatch body so a receiver
// behind a public ingress can tell a real dispatch from a forged or replayed
// one. The scheme mirrors Stripe's webhook signature:
//
//	Alertstore-Signature: t=<unix-seconds>,v1=<hex(HMAC-SHA256(secret, "<t>." + body))>
//
// No "X-" prefix: RFC 6648 (BCP 178) deprecates it for new headers, and a
// vendor-namespaced name is the current convention (as Stripe-Signature is).
// Signing the timestamp alongside the body is what makes a captured request
// un-replayable once the receiver enforces a freshness window; signing the body
// itself is what makes the alert payload — which the agent feeds into a prompt —
// tamper-evident. The verifier lives in the adapter, in its own module, so the
// format is duplicated rather than imported; keep the two in step.
const dispatchSignatureHeader = "Alertstore-Signature"

// signDispatch returns the header value for a body signed at ts.
func signDispatch(secret string, ts int64, body []byte) string {
	mac := hmac.New(sha256.New, []byte(secret))
	mac.Write([]byte(strconv.FormatInt(ts, 10)))
	mac.Write([]byte("."))
	mac.Write(body)
	return "t=" + strconv.FormatInt(ts, 10) + ",v1=" + hex.EncodeToString(mac.Sum(nil))
}
