package mymiddleware

import (
	"net/http"

	echo "github.com/labstack/echo/v4"
	"github.com/tidbcloud/pov-service/internal/handler/dto"
)

func HandleHttpError(err error, c echo.Context) {
	var (
		code = http.StatusInternalServerError
		msg  any
	)

	if he, ok := err.(*echo.HTTPError); ok {
		code = he.Code
		msg = he.Message
		// if he.Internal != nil {
		// handle details
		// }
	} else {
		msg = http.StatusText(code) // "Internal Server Error"
	}

	if s, ok := msg.(string); ok {
		msg = s
	} else if m, ok := msg.(error); ok {
		msg = m.Error()
	}

	if code == http.StatusInternalServerError {
		c.Logger().Error(err)
	}

	if !c.Response().Committed {
		err = c.JSON(code, dto.ErrorResp{
			Code:    code,
			Message: msg.(string),
		})
		if err != nil {
			c.Logger().Error(err)
		}
	}
}
