// Package middleware provides HTTP middleware components for the Veylant proxy.
package middleware

import "context"

// contextKey is an unexported type for context keys in this package.
type contextKey string

const (
	claimsKey    contextKey = "veylant.claims"
	requestIDKey contextKey = "veylant.request_id"
)

// UserClaims holds the authenticated user information extracted from a JWT.
type UserClaims struct {
	UserID     string   // JWT "sub" claim (Keycloak UUID).
	TenantID   string   // Custom "tenant_id" claim added via Keycloak protocol mapper.
	Email      string   // JWT "email" claim.
	Roles      []string // realm_access.roles from the JWT.
	Department string   // JWT "department" claim (optional, used for routing).
}

// WithClaims returns a new context carrying c.
func WithClaims(ctx context.Context, c *UserClaims) context.Context {
	return context.WithValue(ctx, claimsKey, c)
}

// ClaimsFromContext retrieves UserClaims from ctx.
// The second return value is false if no claims are present.
func ClaimsFromContext(ctx context.Context) (*UserClaims, bool) {
	c, ok := ctx.Value(claimsKey).(*UserClaims)
	return c, ok
}

// withRequestID returns a new context carrying id.
func withRequestID(ctx context.Context, id string) context.Context {
	return context.WithValue(ctx, requestIDKey, id)
}

// RequestIDFromContext retrieves the request ID string from ctx.
// Returns an empty string if not set.
func RequestIDFromContext(ctx context.Context) string {
	id, _ := ctx.Value(requestIDKey).(string)
	return id
}
