package ctxinfo

import (
	"github.com/gin-gonic/gin"
	"github.com/tidbcloud/pkgv2/log"
	"go.uber.org/zap"
)

func ExtractCtxInfoMW(c *gin.Context) {
	defer c.Next()

	value := c.GetHeader(CtxInfoHeaderKey)
	if value == "" {
		return
	}
	ci, err := UnpackCtxInfo([]byte(value))
	if err != nil {
		log.WithContextL(c.Request.Context()).Info("unpack ctx info failed", zap.Error(err))
		return
	}

	c.Request = c.Request.WithContext(InjectCtxInfo2Ctx(c.Request.Context(), ci))
}
