package server

import (
	"net/http"
	"os"

	"github.com/labstack/echo/v4"
)

// apiError handles API errors consistently
func (s *Server) apiError(c echo.Context, err error, status ...int) error {
	s.logger.Warnf("server: error serving %s %s: %v", c.Request().Method, c.Request().URL.Path, err)

	if len(status) > 0 {
		return c.JSON(status[0], map[string]any{
			"error": err.Error(),
		})
	}

	switch {
	case os.IsNotExist(err):
		return c.JSON(http.StatusNotFound, nil)
	case os.IsPermission(err):
		return c.JSON(http.StatusUnauthorized, nil)
	default:
		return c.JSON(http.StatusInternalServerError, map[string]any{
			"error": err.Error(),
		})
	}
}
