package handlers import ( "net/http" "strconv" "github.com/gin-gonic/gin" "github.com/treytartt/mycrib-api/internal/middleware" "github.com/treytartt/mycrib-api/internal/models" "github.com/treytartt/mycrib-api/internal/services" ) // UserHandler handles user-related HTTP requests type UserHandler struct { userService *services.UserService } // NewUserHandler creates a new user handler func NewUserHandler(userService *services.UserService) *UserHandler { return &UserHandler{ userService: userService, } } // ListUsers handles GET /api/users/ func (h *UserHandler) ListUsers(c *gin.Context) { user := c.MustGet(middleware.AuthUserKey).(*models.User) // Only allow listing users that share residences with the current user users, err := h.userService.ListUsersInSharedResidences(user.ID) if err != nil { c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) return } c.JSON(http.StatusOK, gin.H{ "count": len(users), "results": users, }) } // GetUser handles GET /api/users/:id/ func (h *UserHandler) GetUser(c *gin.Context) { user := c.MustGet(middleware.AuthUserKey).(*models.User) userID, err := strconv.ParseUint(c.Param("id"), 10, 32) if err != nil { c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid user ID"}) return } // Can only view users that share a residence targetUser, err := h.userService.GetUserIfSharedResidence(uint(userID), user.ID) if err != nil { if err == services.ErrUserNotFound { c.JSON(http.StatusNotFound, gin.H{"error": "User not found"}) return } c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) return } c.JSON(http.StatusOK, targetUser) } // ListProfiles handles GET /api/users/profiles/ func (h *UserHandler) ListProfiles(c *gin.Context) { user := c.MustGet(middleware.AuthUserKey).(*models.User) // List profiles of users in shared residences profiles, err := h.userService.ListProfilesInSharedResidences(user.ID) if err != nil { c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) return } c.JSON(http.StatusOK, gin.H{ "count": len(profiles), "results": profiles, }) }