package middleware

import (
	"runtime/debug"

	"github.com/gin-gonic/gin"

	"tower_api/pkg/app"
	"tower_api/pkg/errcode"
	"tower_api/pkg/feishu"
	"tower_api/pkg/util"
)

func Recovery() gin.HandlerFunc {
	return func(c *gin.Context) {
		defer func() {
			if err := recover(); err != nil {
				debug.PrintStack()
				msg, ok := err.(string)
				var importMsg string
				if ok {
					importMsg = msg
				} else {
					importMsg = string(debug.Stack())
				}
				domain := util.Ter(util.GetRunMod() == "debug", feishu.DEMO_Dev, feishu.DEMO)
				feishu.NewFeiShu(domain).ImportanceNotify("塔防网关崩溃通知", importMsg)
				app.Failed(c, errcode.ERROR)
				c.Abort()
			}
		}()
		c.Next()
	}
}
