package middleware

import (
	"bytes"

	"yh_web/server/pkg/logger"

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

// responseBodyWriter 包装 ResponseWriter 以捕获响应体
type responseBodyWriter struct {
	gin.ResponseWriter
	body *bytes.Buffer
}

func (w responseBodyWriter) Write(b []byte) (int, error) {
	w.body.Write(b)
	return w.ResponseWriter.Write(b)
}

// ErrorLogger 在 4xx/5xx 时记录响应体中的错误信息
func ErrorLogger() gin.HandlerFunc {
	return func(c *gin.Context) {
		w := &responseBodyWriter{
			ResponseWriter: c.Writer,
			body:           &bytes.Buffer{},
		}
		c.Writer = w

		c.Next()

		if w.Status() >= 400 {
			if body := w.body.String(); body != "" {
				logger.Err("middleware/logger", "[%d] %s %s | body: %s", w.Status(), c.Request.Method, c.Request.URL.Path, body)
			}
		}
	}
}
