- Added GetStats method to ChatService with database access - Returns active_users (distinct users who sent messages in last 24h) - Returns total_messages (non-deleted messages count) - Returns rooms_active (rooms with messages in last 24h) - Added GetStats handler and GET /chat/stats route - Updated ChatService to use NewChatServiceWithDB for database access Phase: PHASE-2 Priority: P1 Progress: 15/267 (5.6%)
82 lines
2.2 KiB
Go
82 lines
2.2 KiB
Go
package handlers
|
|
|
|
import (
|
|
"fmt"
|
|
"github.com/google/uuid"
|
|
"net/http"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
"go.uber.org/zap"
|
|
apperrors "veza-backend-api/internal/errors"
|
|
"veza-backend-api/internal/services"
|
|
)
|
|
|
|
type ChatHandler struct {
|
|
chatService *services.ChatService
|
|
userService *services.UserService
|
|
logger *zap.Logger
|
|
}
|
|
|
|
func NewChatHandler(chatService *services.ChatService, userService *services.UserService, logger *zap.Logger) *ChatHandler {
|
|
return &ChatHandler{
|
|
chatService: chatService,
|
|
userService: userService,
|
|
logger: logger,
|
|
}
|
|
}
|
|
|
|
// GetToken generates a JWT token for the chat service
|
|
// @Summary Get Chat Token
|
|
// @Description Generate a short-lived token for chat authentication
|
|
// @Tags Chat
|
|
// @Accept json
|
|
// @Produce json
|
|
// @Security BearerAuth
|
|
// @Success 200 {object} APIResponse{data=object{token=string}}
|
|
// @Failure 401 {object} APIResponse "Unauthorized"
|
|
// @Failure 500 {object} APIResponse "Internal Error"
|
|
// @Router /chat/token [get]
|
|
func (h *ChatHandler) GetToken(c *gin.Context) {
|
|
userIDVal, exists := c.Get("user_id")
|
|
if !exists {
|
|
c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
|
|
return
|
|
}
|
|
userID, ok := userIDVal.(uuid.UUID)
|
|
if !ok || userID == uuid.Nil {
|
|
c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
|
|
return
|
|
}
|
|
|
|
// Get username from DB
|
|
user, err := h.userService.GetByID(userID)
|
|
username := "user"
|
|
if err == nil && user != nil {
|
|
username = user.Username
|
|
} else {
|
|
// Fallback
|
|
username = fmt.Sprintf("user_%s", userID)
|
|
}
|
|
|
|
token, err := h.chatService.GenerateToken(userID, username)
|
|
if err != nil {
|
|
h.logger.Error("Failed to generate chat token", zap.Error(err))
|
|
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to generate token"})
|
|
return
|
|
}
|
|
|
|
RespondSuccess(c, http.StatusOK, token)
|
|
}
|
|
|
|
// GetStats returns chat statistics
|
|
// BE-API-006: Implement chat stats endpoint
|
|
func (h *ChatHandler) GetStats(c *gin.Context) {
|
|
stats, err := h.chatService.GetStats(c.Request.Context())
|
|
if err != nil {
|
|
h.logger.Error("Failed to get chat stats", zap.Error(err))
|
|
RespondWithAppError(c, apperrors.Wrap(apperrors.ErrCodeInternal, "Failed to get chat stats", err))
|
|
return
|
|
}
|
|
|
|
RespondSuccess(c, http.StatusOK, stats)
|
|
}
|