package middleware

import (
	"git.yeij.top/AskaEth/Cyrene/pkg/logger"
	"time"

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

// RequestLogging 请求日志中间件
func RequestLogging() gin.HandlerFunc {
	return func(c *gin.Context) {
		start := time.Now()

		// 处理请求
		c.Next()

		// 记录日志
		duration := time.Since(start)
		statusCode := c.Writer.Status()
		method := c.Request.Method
		path := c.Request.URL.Path
		clientIP := c.ClientIP()

		logLevel := "[INFO]"
		if statusCode >= 500 {
			logLevel = "[ERROR]"
		} else if statusCode >= 400 {
			logLevel = "[WARN]"
		}

		logger.Printf("%s %s %s %d %v %s",
			logLevel, method, path, statusCode, duration, clientIP,
		)
	}
}
