package middleware

import (
	"fmt"
	"net/http"
	"runtime/debug"

	"hfb_sys/backend/pkg/response"

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

func Recovery(logger *zap.Logger) gin.HandlerFunc {
	return func(c *gin.Context) {
		defer func() {
			if recovered := recover(); recovered != nil {
				err := fmt.Errorf("panic: %v", recovered)
				_ = c.Error(err)
				logger.Error("http panic recovered",
					zap.String("request_id", GetRequestID(c)),
					zap.String("method", c.Request.Method),
					zap.String("path", c.Request.URL.Path),
					zap.String("route", c.FullPath()),
					zap.String("client_ip", c.ClientIP()),
					zap.String("user_agent", c.GetHeader("User-Agent")),
					zap.String("panic", fmt.Sprint(recovered)),
					zap.ByteString("stack", debug.Stack()),
				)
				if !c.Writer.Written() {
					response.Error(c, http.StatusInternalServerError, "internal_error", "服务暂时不可用")
				}
				c.Abort()
			}
		}()
		c.Next()
	}
}
