veza/veza-backend-api/internal/handlers/notification_handlers.go

101 lines
2.7 KiB
Go

package handlers
import (
"github.com/google/uuid"
"net/http"
"veza-backend-api/internal/services"
"github.com/gin-gonic/gin"
)
var NotificationHandlersInstance *NotificationHandlers
type NotificationHandlers struct {
notificationService *services.NotificationService
}
func NewNotificationHandlers(notificationService *services.NotificationService) {
NotificationHandlersInstance = &NotificationHandlers{
notificationService: notificationService,
}
}
// GetNotifications retrieves all notifications for the authenticated user
func (nh *NotificationHandlers) GetNotifications(c *gin.Context) {
userID, exists := c.Get("user_id")
if !exists {
c.JSON(http.StatusUnauthorized, gin.H{"error": "User not authenticated"})
return
}
read := c.DefaultQuery("read", "")
var unreadOnly bool
if read == "false" {
unreadOnly = true
}
notifications, err := nh.notificationService.GetNotifications(userID.(uuid.UUID), unreadOnly)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
RespondSuccess(c, http.StatusOK, notifications)
}
// MarkAsRead marks a notification as read
func (nh *NotificationHandlers) MarkAsRead(c *gin.Context) {
userID, exists := c.Get("user_id")
if !exists {
c.JSON(http.StatusUnauthorized, gin.H{"error": "User not authenticated"})
return
}
notificationID, err := uuid.Parse(c.Param("id"))
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid notification ID"})
return
}
err = nh.notificationService.MarkAsRead(userID.(uuid.UUID), notificationID)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
RespondSuccess(c, http.StatusOK, gin.H{"message": "Notification marked as read"})
}
// MarkAllAsRead marks all notifications as read for the user
func (nh *NotificationHandlers) MarkAllAsRead(c *gin.Context) {
userID, exists := c.Get("user_id")
if !exists {
c.JSON(http.StatusUnauthorized, gin.H{"error": "User not authenticated"})
return
}
if err := nh.notificationService.MarkAllAsRead(userID.(uuid.UUID)); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
RespondSuccess(c, http.StatusOK, gin.H{"message": "All notifications marked as read"})
}
// GetUnreadCount returns the count of unread notifications
func (nh *NotificationHandlers) GetUnreadCount(c *gin.Context) {
userID, exists := c.Get("user_id")
if !exists {
c.JSON(http.StatusUnauthorized, gin.H{"error": "User not authenticated"})
return
}
count, err := nh.notificationService.GetUnreadCount(userID.(uuid.UUID))
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
RespondSuccess(c, http.StatusOK, gin.H{"count": count})
}