package router

import (
	"net/http"

	"github.com/caarlos0/httperr"
	"github.com/gin-gonic/gin"
	"github.com/tidbcloud/inference-service/internal/service"
	"go.uber.org/zap"
)

// mCatchError is a middleware turns errors into a standard JSON error response.
func mCatchError(c *gin.Context) {
	c.Next()
	if len(c.Errors) > 0 {
		err := c.Errors.Last().Err
		zap.L().Warn("Respond with error",
			zap.String("remoteAddr", c.Request.RemoteAddr),
			zap.String("path", c.Request.URL.Path),
			zap.Error(err))
		if httperr, ok := err.(httperr.Error); ok {
			c.JSON(httperr.Status, service.ErrorResponse{Error: httperr.Error()})
		} else {
			c.JSON(http.StatusInternalServerError, service.ErrorResponse{Error: err.Error()})
		}
	}
}
