package messagesend

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

type bearerIDContextKey struct{}

// BearerID returns the irreversible identity of the bearer the current MCP
// request authenticated with, injected by the access-control middleware. It
// binds send-scope reads to the caller's credential so a request from a
// replaced process cannot observe another turn's scope.
func BearerID(ctx context.Context) (string, bool) {
	identity, ok := ctx.Value(bearerIDContextKey{}).(string)
	if !ok || identity == "" {
		return "", false
	}
	return identity, true
}

// WithBearerID stores the token identity in the context.
func WithBearerID(ctx context.Context, token string) context.Context {
	return context.WithValue(ctx, bearerIDContextKey{}, TokenIdentity(token))
}

// TokenIdentity is the irreversible identity of a raw bearer token.
func TokenIdentity(token string) string {
	sum := sha256.Sum256([]byte(token))
	return hex.EncodeToString(sum[:])
}
