// Filename: internal/middleware/request_id.go

package middleware

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

// RequestIDMiddleware 请求 ID 追踪中间件
func RequestIDMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		// 1. 尝试从 Header 获取现有的 Request ID
		requestID := c.GetHeader("X-Request-Id")

		// 2. 如果没有，生成新的
		if requestID == "" {
			requestID = uuid.New().String()
		}

		// 3. 设置到 Context
		c.Set("request_id", requestID)

		// 4. 返回给客户端（用于追踪）
		c.Writer.Header().Set("X-Request-Id", requestID)

		c.Next()
	}
}

// GetRequestID 获取当前请求的 Request ID
func GetRequestID(c *gin.Context) string {
	if id, exists := c.Get("request_id"); exists {
		if requestID, ok := id.(string); ok {
			return requestID
		}
	}
	return ""
}
