package error

import (
	"net/http"

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

type ErrorResponse struct {
	Error   bool   `json:"error"`
	Message string `json:"message"`
	Code    string `json:"code"`
	// FullText string `json:"full_text"`
}

func NewErrorResponse(err error) ErrorResponse {
	log.Error("api failed", zap.Error(err))
	return ErrorResponse{
		Error:   true,
		Message: buildSimpleMessage(err),
		Code:    buildCode(err),
	}
}

func ErrorHandlerFn(c *gin.Context) {
	c.Next()

	err := c.Errors.Last()
	if err == nil {
		return
	}

	if c.Writer.Size() > 0 {
		return
	}

	statusCode := c.Writer.Status()
	if statusCode == http.StatusOK {
		// Change the status code if it is not specified.
		statusCode = extractHTTPCodeFromError(err.Err)
	}

	c.AbortWithStatusJSON(statusCode, NewErrorResponse(err.Err))
}
