package handlers import ( "encoding/json" "net/http" "github.com/rede5/gohorsejobs/backend/internal/services" ) type NotificationHandler struct { service *services.NotificationService } func NewNotificationHandler(service *services.NotificationService) *NotificationHandler { return &NotificationHandler{service: service} } // GetNotifications lists notifications func (h *NotificationHandler) GetNotifications(w http.ResponseWriter, r *http.Request) { userID := getUserIDFromContext(r) if userID == "" { http.Error(w, "Unauthorized", http.StatusUnauthorized) return } notifications, err := h.service.ListNotifications(r.Context(), userID) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(notifications) // Returns []models.Notification } // MarkAsRead marks a notification as read func (h *NotificationHandler) MarkAsRead(w http.ResponseWriter, r *http.Request) { userID := getUserIDFromContext(r) if userID == "" { http.Error(w, "Unauthorized", http.StatusUnauthorized) return } id := r.PathValue("id") if id == "" { http.Error(w, "Invalid notification ID", http.StatusBadRequest) return } if err := h.service.MarkAsRead(r.Context(), userID, id); err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } w.WriteHeader(http.StatusOK) } // MarkAllAsRead marks all as read func (h *NotificationHandler) MarkAllAsRead(w http.ResponseWriter, r *http.Request) { userID := getUserIDFromContext(r) if userID == "" { http.Error(w, "Unauthorized", http.StatusUnauthorized) return } if err := h.service.MarkAllAsRead(r.Context(), userID); err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } w.WriteHeader(http.StatusOK) } // RegisterFCMToken registers a device token func (h *NotificationHandler) RegisterFCMToken(w http.ResponseWriter, r *http.Request) { userID := getUserIDFromContext(r) if userID == "" { http.Error(w, "Unauthorized", http.StatusUnauthorized) return } var req struct { Token string `json:"token"` DeviceType string `json:"deviceType"` } if err := json.NewDecoder(r.Body).Decode(&req); err != nil { http.Error(w, "Invalid request", http.StatusBadRequest) return } if req.Token == "" { http.Error(w, "Token is required", http.StatusBadRequest) return } if err := h.service.SaveFCMToken(r.Context(), userID, req.Token, req.DeviceType); err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } w.WriteHeader(http.StatusOK) } // Helper: Extract UserID (String) func getUserIDFromContext(r *http.Request) string { // 1. Check Context (set by correct middleware) if userID, ok := r.Context().Value("userID").(string); ok && userID != "" { return userID } // 2. Check Header (testing/dev) if userID := r.Header.Get("X-User-ID"); userID != "" { return userID } return "" }