package tracing

import (
	"github.com/gin-gonic/gin"
	"github.com/google/uuid"
)

const (
	// TraceIDHeader is the HTTP header used for trace propagation.
	TraceIDHeader = "X-Trace-ID"
	// TraceIDContextKey is the Gin context key for the trace ID.
	TraceIDContextKey = "acp_trace_id"
)

// EnsureTraceID returns the incoming trace ID from headers if present; otherwise generates a new ID.
func EnsureTraceID(c *gin.Context) string {
	if id := c.GetHeader(TraceIDHeader); id != "" {
		c.Set(TraceIDContextKey, id)
		return id
	}
	id := uuid.NewString()
	c.Set(TraceIDContextKey, id)
	return id
}

// TraceIDFromContext returns the trace ID stored on the Gin context, or empty string.
func TraceIDFromContext(c *gin.Context) string {
	v, ok := c.Get(TraceIDContextKey)
	if !ok {
		return ""
	}
	s, _ := v.(string)
	return s
}
