package middleware

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

	"github.com/gin-gonic/gin"
	"github.com/nexuscrm/backend/pkg/errors"
	"github.com/rs/zerolog/log"
)

// Recovery returns a middleware that recovers from any panics and writes a 500 if there was one.
func Recovery() gin.HandlerFunc {
	return func(c *gin.Context) {
		defer func() {
			if err := recover(); err != nil {
				RecordPanicRecovered()
				// Log the stack trace with structured logging
				log.Error().
					Interface("panic", err).
					Str("stack", string(debug.Stack())).
					Str("path", c.Request.URL.Path).
					Str("method", c.Request.Method).
					Msg("PANIC RECOVERED")

				// Extract Request ID
				reqID := c.GetString(ContextKeyRequestID)

				// Create standard Internal Error
				appErr := errors.NewInternalError("An unexpected error occurred", nil)

				// Return standardized JSON response
				response := errors.ToResponseWithID(appErr, reqID)
				c.AbortWithStatusJSON(http.StatusInternalServerError, response)
			}
		}()
		c.Next()
	}
}
