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 ZoneAddController(db *gorm.DB, context context.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { var zone model.Zone if err := json.NewDecoder(r.Body).Decode(&zone); err != nil { response.BadRequest(w, "invalid request body") return } if err := validation.Struct(&zone); err != nil { response.BadRequest(w, err.Error()) return } if err := db.WithContext(context).Create(&zone).Error; err != nil { response.InternalError(w, "failed to create zone", err) return } response.JSON(w, http.StatusCreated, map[string]string{"status": "created"}) } } func ZoneListController(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 zones []model.Zone if err := db.WithContext(context).Limit(limit).Offset(offset).Find(&zones).Error; err != nil { response.InternalError(w, "failed to list zones", err) return } response.JSON(w, http.StatusOK, zones) } } func ZoneUpdateController(db *gorm.DB, context context.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { var zone model.Zone if err := json.NewDecoder(r.Body).Decode(&zone); err != nil { response.BadRequest(w, "invalid request body") return } if err := validation.Struct(&zone); err != nil { response.BadRequest(w, err.Error()) return } id := zone.ID if err := db.WithContext(context).First(&model.Zone{}, "id = ?", id).Error; err != nil { response.NotFound(w, "zone not found") return } if err := db.WithContext(context).Save(&zone).Error; err != nil { response.InternalError(w, "failed to update zone", err) return } response.JSON(w, http.StatusOK, map[string]string{"status": "updated"}) } } func ZoneDeleteController(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.Zone{}, "id = ?", id) if res.RowsAffected == 0 { response.NotFound(w, "zone not found") return } if res.Error != nil { response.InternalError(w, "failed to delete zone", res.Error) return } response.JSON(w, http.StatusOK, map[string]string{"status": "deleted"}) } }