messaging-center/internal/api/commands.go

88 lines
2.2 KiB
Go

package api
import (
"encoding/json"
"net/http"
"time"
"github.com/go-chi/chi/v5"
"github.com/google/uuid"
"github.com/inou-ai/messaging-center/internal/core"
)
// CommandResponse wraps a command for API response.
type CommandResponse struct {
Command *core.Command `json:"command"`
}
// CreateCommandRequest is the request body for creating a command.
type CreateCommandRequest struct {
Type string `json:"type"`
Payload json.RawMessage `json:"payload"`
}
var validCommandTypes = map[string]bool{
"send": true,
"route": true,
"delete": true,
"archive": true,
"forward": true,
}
// handleCreateCommand handles POST /api/v1/commands (stub).
func (s *Server) handleCreateCommand(w http.ResponseWriter, r *http.Request) {
var req CreateCommandRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid request body"})
return
}
if req.Type == "" {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "type is required"})
return
}
if !validCommandTypes[req.Type] {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid command type"})
return
}
now := time.Now()
cmd := &core.Command{
ID: "cmd_" + uuid.New().String()[:8],
Type: req.Type,
Payload: req.Payload,
Status: "pending",
CreatedAt: now,
UpdatedAt: now,
}
if err := s.store.CreateCommand(cmd); err != nil {
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": err.Error()})
return
}
// TODO: Actually execute the command via adapters
// For now, just mark it as pending
writeJSON(w, http.StatusAccepted, CommandResponse{Command: cmd})
}
// handleGetCommand handles GET /api/v1/commands/:id.
func (s *Server) handleGetCommand(w http.ResponseWriter, r *http.Request) {
id := chi.URLParam(r, "id")
cmd, err := s.store.GetCommand(id)
if err != nil {
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": err.Error()})
return
}
if cmd == nil {
writeJSON(w, http.StatusNotFound, map[string]string{"error": "command not found"})
return
}
writeJSON(w, http.StatusOK, CommandResponse{Command: cmd})
}