package api

import(
	"net/http"
	"errors"

	"party.at/party/cmd/party/common"
	"party.at/party/internal/data"
)

func (api *Api) LogError(r *http.Request, err error) {
	api.App.Logger.PrintError(err, map[string]string{
		"request_method": r.Method,
		"request_url":    r.URL.String(),
	})
}

func (api *Api) errorResponse(w http.ResponseWriter, r *http.Request, err error) {
	apiErr := &data.Error{
        HttpCode: http.StatusInternalServerError,
        Message:  "the server encountered a problem",
    }

    // Try to "unbox" the error to see if it's our rich *Error type
    var customErr *data.Error
    if errors.As(err, &customErr) {
        apiErr = customErr
    }

	if err := common.WriteJSON(w, apiErr.HttpCode, common.Envelope{"error": apiErr}, nil); err != nil {
		api.App.LogError(r, err)
		w.WriteHeader(500)
	}
}

func (api *Api) ServerErrorResponse(w http.ResponseWriter, r *http.Request, err error) {
    api.App.LogError(r, err)

    api.errorResponse(w, r, err)
}
