package controller import ( "context" "encoding/json" "errors" "log/slog" "net/http" "strconv" "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) { query := r.URL.Query() lStr := query.Get("limit") if lStr == "" { lStr = "100" } limit, err := strconv.Atoi(lStr) if err != nil { slog.Error("invalid limit parameter", "value", lStr) response.BadRequest(w, "invalid limit parameter") return } oStr := query.Get("offset") if oStr == "" { oStr = "0" } offset, err := strconv.Atoi(oStr) if err != nil { slog.Error("invalid offset parameter", "value", oStr) response.BadRequest(w, "invalid offset parameter") return } alerts, err := service.GetAllAlerts(db, ctx, limit, offset) 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"}) } }