package controller import ( "context" "encoding/json" "errors" "net/http" "github.com/AFASystems/presence/internal/pkg/api/response" "github.com/AFASystems/presence/internal/pkg/service" "github.com/AFASystems/presence/internal/pkg/validation" "github.com/gorilla/mux" "gorm.io/gorm" ) func AlertsListController(db *gorm.DB, ctx context.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { alerts, err := service.GetAllAlerts(db, ctx) if err != nil { response.InternalError(w, "failed to list alerts", err) return } response.JSON(w, http.StatusOK, alerts) } } func ListAlertsByTrackerIDController(db *gorm.DB, ctx context.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { id := mux.Vars(r)["id"] alert, err := service.GetAlertById(id, db, ctx) if err != nil { if errors.Is(err, gorm.ErrRecordNotFound) { response.NotFound(w, "alert not found") return } response.InternalError(w, "failed to get alert", err) return } response.JSON(w, http.StatusOK, alert) } } func AlertDeleteController(db *gorm.DB, ctx context.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { id := mux.Vars(r)["id"] if err := service.DeleteAlertByTrackerID(id, db, ctx); err != nil { response.InternalError(w, "failed to delete alert", err) return } response.JSON(w, http.StatusOK, map[string]string{"status": "deleted"}) } } // AlertUpdateStatusController updates an alert's status by id. Body: {"status": "resolved"} (or other status string). func AlertUpdateStatusController(db *gorm.DB, ctx context.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { id := mux.Vars(r)["id"] var body struct { Status string `json:"status"` } if err := json.NewDecoder(r.Body).Decode(&body); err != nil { response.BadRequest(w, "invalid request body") return } if err := validation.Var(body.Status, "required"); err != nil { response.BadRequest(w, err.Error()) return } if err := service.UpdateAlertStatus(id, body.Status, db, ctx); err != nil { if errors.Is(err, gorm.ErrRecordNotFound) { response.NotFound(w, "alert not found") return } response.InternalError(w, "failed to update alert status", err) return } response.JSON(w, http.StatusOK, map[string]string{"status": "updated"}) } }