package logid

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

// InjectLogid4GinMW get logid from ctx or generate a new logid, then set the logid into http response header
// Attention: due to the context of grpc-gateway(http layer) is NOT same as grpc-handler(grpc layer),
// the logid in gin.Context.Request.ctx can't be used by grpc service.
// you CAN'T use this middleware with grpc-gateway.
func InjectLogid4GinMW(c *gin.Context) {
	logid := GetLogid(c.Request.Context())
	if logid == "" {
		logid = GenLogid()
		ctx := c.Request.Context()
		c.Request = c.Request.WithContext(WithLogid(ctx, logid))
	}
	c.Header(LogidHTTPHeaderKey, logid)

	c.Next()
}

func InjectLogid4GRPCGatewayMW(c *gin.Context) {
	ctx := c.Request.Context()
	logid := GetLogid(ctx)
	if logid == "" {
		logid = GenLogid()
		ctx = WithLogid(ctx, logid)
		c.Request = c.Request.WithContext(ctx)
	}
	// The only way to carry HTTP layer information to the GRPC layer.
	// you must use grpc-gateway:runtime.WithIncomingHeaderMatcher to ensure your expected HTTP header will be carried.
	// refer to github.com/grpc-ecosystem/grpc-gateway/runtime/context.go:AnnotateIncomingContext.
	c.Request.Header.Set(LogidHTTPHeaderKey, logid)
	c.Header(LogidHTTPHeaderKey, logid)

	c.Next()
}
