package middleware

import (
	"log"
	"net/http"
	"os"
	"runtime/debug"

	"github.com/acp/interceptor/internal/tracing"
	"github.com/acp/interceptor/internal/utils"
	"github.com/gin-gonic/gin"
)

// Recovery returns a middleware that recovers from panics and returns 500 JSON.
func Recovery() gin.HandlerFunc {
	logger := log.New(os.Stderr, "", log.LstdFlags)
	return func(c *gin.Context) {
		defer func() {
			if rec := recover(); rec != nil {
				traceID := tracing.TraceIDFromContext(c)
				logger.Printf("panic trace_id=%s err=%v\n%s", traceID, rec, string(debug.Stack()))
				utils.AbortWithErrorJSON(c, http.StatusInternalServerError, traceID, "internal server error")
			}
		}()
		c.Next()
	}
}
