package routes

import (
	"dashboard/models"
	"dashboard/utils"
	"errors"
	"net/http"

	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
)

type appHandler func(*gin.Context) error

func errWapper(appH appHandler) gin.HandlerFunc {
	return func(c *gin.Context) {
		log, _ := utils.GetLogFromContext(c)

		err := appH(c)

		if err != nil {
			var baseErr *models.BaseError
			if errors.As(err, &baseErr) {
				log.Error("Base error", zap.Any("baseErr", baseErr))

				c.JSON(http.StatusBadRequest, baseErr)

				return
			}

			log.Error("Other error", zap.Error(err))
			c.String(http.StatusBadGateway, err.Error())

			return
		}
	}
}
