package controller import ( "context" "encoding/json" "log/slog" "net/http" "strconv" "github.com/AFASystems/presence/internal/pkg/api/response" "github.com/AFASystems/presence/internal/pkg/model" "github.com/AFASystems/presence/internal/pkg/validation" "github.com/gorilla/mux" "gorm.io/gorm" ) func TrackerZoneAddController(db *gorm.DB, context context.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { var tz model.TrackerZones if err := json.NewDecoder(r.Body).Decode(&tz); err != nil { response.BadRequest(w, "invalid request body") return } if err := validation.Struct(&tz); err != nil { response.BadRequest(w, err.Error()) return } if err := db.WithContext(context).Create(&tz).Error; err != nil { response.InternalError(w, "failed to create tracker zone", err) return } response.JSON(w, http.StatusCreated, map[string]string{"status": "created"}) } } func TrackerZoneListController(db *gorm.DB, context 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 } var list []model.TrackerZones if err := db.WithContext(context).Limit(limit).Offset(offset).Find(&list).Error; err != nil { response.InternalError(w, "failed to list tracker zones", err) return } response.JSON(w, http.StatusOK, list) } } func TrackerZoneUpdateController(db *gorm.DB, context context.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { var tz model.TrackerZones if err := json.NewDecoder(r.Body).Decode(&tz); err != nil { response.BadRequest(w, "invalid request body") return } if err := validation.Struct(&tz); err != nil { response.BadRequest(w, err.Error()) return } id := tz.ID if err := db.WithContext(context).First(&model.TrackerZones{}, "id = ?", id).Error; err != nil { response.NotFound(w, "tracker zone not found") return } if err := db.WithContext(context).Save(&tz).Error; err != nil { response.InternalError(w, "failed to update tracker zone", err) return } response.JSON(w, http.StatusOK, map[string]string{"status": "updated"}) } } func TrackerZoneDeleteController(db *gorm.DB, context context.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { id := mux.Vars(r)["id"] res := db.WithContext(context).Delete(&model.TrackerZones{}, "id = ?", id) if res.RowsAffected == 0 { response.NotFound(w, "tracker zone not found") return } if res.Error != nil { response.InternalError(w, "failed to delete tracker zone", res.Error) return } response.JSON(w, http.StatusOK, map[string]string{"status": "deleted"}) } }