package middleware

import (
	"time"

	"github.com/gin-gonic/gin"
	"go.uber.org/zap"

	pkglogger "nex/backend/pkg/logger"
)

func Logging(logger *zap.Logger) gin.HandlerFunc {
	return func(c *gin.Context) {
		start := time.Now()
		path := c.Request.URL.Path
		query := c.Request.URL.RawQuery

		requestID, _ := c.Get(RequestIDKey)
		var requestIDStr string
		if id, ok := requestID.(string); ok {
			requestIDStr = id
		}
		logger.Info("请求开始",
			pkglogger.Method(c.Request.Method),
			pkglogger.Path(path),
			pkglogger.Query(query),
			pkglogger.ClientIP(c.ClientIP()),
			pkglogger.RequestID(requestIDStr),
		)

		c.Next()

		latency := time.Since(start)
		statusCode := c.Writer.Status()

		logger.Info("请求结束",
			pkglogger.StatusCode(statusCode),
			pkglogger.Method(c.Request.Method),
			pkglogger.Path(path),
			pkglogger.Latency(latency),
			pkglogger.BodySize(c.Writer.Size()),
			pkglogger.RequestID(requestIDStr),
		)
	}
}
