package controller import ( "context" "encoding/json" "net/http" "github.com/AFASystems/presence/internal/pkg/api/response" "github.com/AFASystems/presence/internal/pkg/model" "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 := 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) { var zones []model.Zone if err := db.WithContext(context).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 } 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"}) } }