package web

import(
	"net/http"
	"errors"

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

// ── Error responses ──────────────────────────────────────────────────────────

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

func (web *Web) errorResponse(w http.ResponseWriter, r *http.Request, err error) {
	displayError := data.Error{
		HttpCode: http.StatusInternalServerError,
		Message:  "the server encountered a problem and could not process your request",
	}

	var customErr *data.Error
	if errors.As(err, &customErr) {
		displayError = *customErr
	}

	user := common.GetUser(r)
	
	web.render(w, r, displayError.HttpCode, "error", struct {
		AuthenticatedUser *data.User
		IsDevelopment     bool
		Error             data.Error
	}{
		AuthenticatedUser: user,
		IsDevelopment:     web.App.Config.Env == "development",
		Error:             displayError,
	})
}

func (web *Web) ServerErrorResponse(w http.ResponseWriter, r *http.Request, err error) {
	web.LogError(r, err)

	web.errorResponse(w, r, err)
}
