package middleware

import (
	"eslogad-be/internal/contract"
	"eslogad-be/internal/logger"
	"eslogad-be/internal/util"
	"github.com/gin-gonic/gin"
	"net/http"
	"runtime/debug"
)

func Recover() gin.HandlerFunc {
	return func(c *gin.Context) {
		defer func() {
			if err := recover(); err != nil {
				logger.NonContext.Errorf(nil, "Recovered from panic %v", map[string]interface{}{
					"stack_trace": string(debug.Stack()),
					"error":       err,
				})
				debug.PrintStack()
				errorResponse := contract.BuildErrorResponse([]*contract.ResponseError{
					contract.NewResponseError("900", "", string(debug.Stack())),
				})
				util.WriteResponse(c.Writer, c.Request, *errorResponse, http.StatusInternalServerError, "Middleware::Recover")
				c.Abort()
			}
		}()
		c.Next()
	}
}
