78 lines
2.0 KiB
Go
78 lines
2.0 KiB
Go
package handler
|
|
|
|
import (
|
|
"encoding/json"
|
|
"net/http"
|
|
|
|
"github.com/daniil/homelab-api/internal/middleware"
|
|
"github.com/daniil/homelab-api/internal/model"
|
|
"github.com/daniil/homelab-api/internal/repository"
|
|
)
|
|
|
|
type ProfileHandler struct {
|
|
userRepo *repository.UserRepository
|
|
}
|
|
|
|
func NewProfileHandler(userRepo *repository.UserRepository) *ProfileHandler {
|
|
return &ProfileHandler{userRepo: userRepo}
|
|
}
|
|
|
|
func (h *ProfileHandler) Get(w http.ResponseWriter, r *http.Request) {
|
|
userID := middleware.GetUserID(r.Context())
|
|
|
|
user, err := h.userRepo.GetByID(userID)
|
|
if err != nil {
|
|
writeError(w, "user not found", http.StatusNotFound)
|
|
return
|
|
}
|
|
|
|
user.ProcessForJSON()
|
|
|
|
profile := map[string]interface{}{
|
|
"username": user.Username,
|
|
"telegram_chat_id": user.TelegramChatIDValue,
|
|
"notifications_enabled": user.NotificationsEnabled,
|
|
"timezone": user.Timezone,
|
|
"morning_reminder_time": user.MorningTime,
|
|
"evening_reminder_time": user.EveningTime,
|
|
}
|
|
|
|
writeJSON(w, profile, http.StatusOK)
|
|
}
|
|
|
|
func (h *ProfileHandler) Update(w http.ResponseWriter, r *http.Request) {
|
|
userID := middleware.GetUserID(r.Context())
|
|
|
|
var req model.UpdateProfileRequest
|
|
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
|
writeError(w, "invalid request body", http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
err := h.userRepo.UpdateProfile(userID, &req)
|
|
if err != nil {
|
|
writeError(w, "failed to update profile", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
|
|
// Get updated user
|
|
user, err := h.userRepo.GetByID(userID)
|
|
if err != nil {
|
|
writeError(w, "user not found", http.StatusNotFound)
|
|
return
|
|
}
|
|
|
|
user.ProcessForJSON()
|
|
|
|
profile := map[string]interface{}{
|
|
"username": user.Username,
|
|
"telegram_chat_id": user.TelegramChatIDValue,
|
|
"notifications_enabled": user.NotificationsEnabled,
|
|
"timezone": user.Timezone,
|
|
"morning_reminder_time": user.MorningTime,
|
|
"evening_reminder_time": user.EveningTime,
|
|
}
|
|
|
|
writeJSON(w, profile, http.StatusOK)
|
|
}
|