package httpapi import ( "log/slog" "net/http" "strings" "github.com/mitbringsl/backend/internal/auth" ) // MeHandler exposes the authenticated user's own profile (/api/me). type MeHandler struct { users *auth.UserStore } // NewMeHandler constructs a MeHandler. func NewMeHandler(users *auth.UserStore) *MeHandler { return &MeHandler{users: users} } type updateMeRequest struct { DisplayName *string `json:"display_name"` // nil = unchanged, "" = clear } // Get returns the current user's profile. // GET /api/me func (h *MeHandler) Get(w http.ResponseWriter, r *http.Request) { userID, ok := userIDFromCtx(r) if !ok { renderError(w, http.StatusUnauthorized, "Unauthorized", "Missing user context.") return } u, err := h.users.GetUserByID(r.Context(), userID) if err != nil { slog.Error("get me failed", "error", err, "user_id", userID) renderError(w, http.StatusInternalServerError, "Internal error", "Could not load user.") return } renderJSON(w, http.StatusOK, toUserDTO(u)) } // Update changes editable fields of the current user (currently display_name). // PUT /api/me func (h *MeHandler) Update(w http.ResponseWriter, r *http.Request) { userID, ok := userIDFromCtx(r) if !ok { renderError(w, http.StatusUnauthorized, "Unauthorized", "Missing user context.") return } var req updateMeRequest if !decodeJSON(w, r, &req) { return } // Only update when display_name is provided in the body (pointer non-nil). // Trimming to keep stored names tidy; an empty string clears the field. if req.DisplayName == nil { // Nothing to change – return the current profile. u, err := h.users.GetUserByID(r.Context(), userID) if err != nil { renderError(w, http.StatusInternalServerError, "Internal error", "Could not load user.") return } renderJSON(w, http.StatusOK, toUserDTO(u)) return } name := strings.TrimSpace(*req.DisplayName) u, err := h.users.UpdateDisplayName(r.Context(), userID, name) if err != nil { slog.Error("update me failed", "error", err, "user_id", userID) renderError(w, http.StatusInternalServerError, "Internal error", "Could not update user.") return } renderJSON(w, http.StatusOK, toUserDTO(u)) }