package httphandlers

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

	"github.com/fiskerinc/cloud-services/pkg/logger"
	"github.com/fiskerinc/cloud-services/pkg/utils"
)

// PanicHandler Panic handler wrapper for http handlers
func PanicHandler(next http.HandlerFunc) http.HandlerFunc {
	wrapper := func(w http.ResponseWriter, r *http.Request) {
		logger.Debug().Msgf("%s %s", r.Method, r.RequestURI)

		defer func() {
			if err := recover(); err != nil {
				HttpRouterPanicHandler(w, r, err)
			}
		}()

		next.ServeHTTP(w, r)
	}

	return wrapper
}

func HttpRouterPanicHandler(w http.ResponseWriter, r *http.Request, p interface{}) {
	logger.Error().Msgf("PanicHandler %v %s", p, string(debug.Stack()))
	utils.RespError(w, http.StatusInternalServerError, fmt.Sprintf("PanicHandler %v", p))
}
