package middleware

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

const (
	// RequestIDKey is the Gin context key for the request ID.
	RequestIDKey = "request_id"
	// RequestIDHeader is the HTTP header used to propagate request IDs.
	RequestIDHeader = "X-Request-Id"
)

// RequestID generates a UUID per request and sets it in the Gin context
// and response header. If the incoming request already carries an
// X-Request-Id header, it is preserved (useful for tracing across proxies).
func RequestID() gin.HandlerFunc {
	return func(c *gin.Context) {
		id := c.GetHeader(RequestIDHeader)
		if id == "" {
			id = uuid.New().String()
		}
		c.Set(RequestIDKey, id)
		c.Header(RequestIDHeader, id)
		c.Next()
	}
}
