aboutsummaryrefslogtreecommitdiff
path: root/internal/admin/api_rooms_bulk.go
blob: eb5e89d42ed7753746b67e07e29bc348b094aa95 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
package admin

import (
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"os"
	"path/filepath"
	"strconv"

	"thehouseoficarus/internal/persistence"
)

type bulkEditPatch struct {
	Color          *string `json:"color"`
	BlockTransport *bool   `json:"block_transport"`
	Dir            *string `json:"dir"`
	Hazard         *string `json:"hazard"`
}

type bulkEditRequest struct {
	Patch bulkEditPatch `json:"patch"`
	IDs   []int         `json:"ids"`
}

// handleBulkEdit applies one patch to many rooms as a single mutation
// plan:
//
//  1. Preflight reads, parses, patches, and marshals every selected room in
//     memory — including destination-directory and conflict checks for
//     moves. Any failure aborts BEFORE any file is touched: a failed bulk
//     edit never leaves partial changes behind.
//  2. The writes apply as one journal transaction (in-place replaces, and
//     move+replace for real directory moves) that rolls back on failure.
//  3. One undo record captures every before/after image, so undo restores
//     the whole plan.
func (s *AdminServer) handleBulkEdit(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodPost {
		http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
		return
	}

	body, readErr := io.ReadAll(r.Body)
	r.Body.Close()
	if readErr != nil {
		failJSON(w, fmt.Sprintf("read body: %v", readErr))
		return
	}

	var req bulkEditRequest
	if err := json.Unmarshal(body, &req); err != nil {
		failJSON(w, fmt.Sprintf("invalid json: %v", err))
		return
	}

	if len(req.IDs) == 0 {
		failJSON(w, "no room ids")
		return
	}

	if isEmptyPatch(req.Patch) {
		failJSON(w, "no patch fields")
		return
	}

	patch := req.Patch

	type roomWrite struct {
		id                     int
		oldPath, newPath       string
		oldContent, newContent []byte
	}

	// ---- Preflight: everything that can fail happens here, before any
	// file is modified. ----
	writes := make([]roomWrite, 0, len(req.IDs))
	for _, id := range req.IDs {
		path, ok := s.world.GetRoomPath(id)
		if !ok {
			failJSON(w, fmt.Sprintf("room %d not found", id))
			return
		}
		oldContent, err := os.ReadFile(path)
		if err != nil {
			failJSON(w, fmt.Sprintf("read room %d: %v", id, err))
			return
		}
		m, yamlErr := yamlToMap(oldContent)
		if yamlErr != nil {
			failJSON(w, fmt.Sprintf("parse room %d: %v", id, yamlErr))
			return
		}

		if patch.Color != nil {
			m["color"] = *patch.Color
		}
		if patch.BlockTransport != nil {
			m["block_transport"] = *patch.BlockTransport
		}
		if patch.Hazard != nil {
			if *patch.Hazard == "" {
				delete(m, "hazard")
			} else {
				m["hazard"] = *patch.Hazard
			}
		}

		newPath := path
		if patch.Dir != nil && *patch.Dir != "" {
			dir, dirErr := s.resolveRoomSubdir(*patch.Dir)
			if dirErr != nil {
				failJSON(w, dirErr.Error())
				return
			}
			destDir := filepath.Join(s.dataDir, "rooms", dir)
			if _, statErr := os.Stat(destDir); os.IsNotExist(statErr) {
				failJSON(w, fmt.Sprintf("directory does not exist: %s", *patch.Dir))
				return
			}
			newPath = filepath.Join(destDir, strconv.Itoa(id)+".yaml")
			if newPath != path {
				if _, statErr := os.Stat(newPath); statErr == nil {
					failJSON(w, fmt.Sprintf("room %d already exists in target directory", id))
					return
				}
			}
			// newPath == path is an in-place edit: the room already lives
			// in the target directory and must NOT be removed after its
			// write (that deleted existing rooms).
		}

		newContent, marshalErr := marshalMapYAML(m)
		if marshalErr != nil {
			failJSON(w, fmt.Sprintf("marshal room %d: %v", id, marshalErr))
			return
		}
		if err := validateRoomSchema(newContent); err != nil {
			failJSON(w, fmt.Sprintf("room %d failed schema validation: %v", id, err))
			return
		}
		writes = append(writes, roomWrite{id: id, oldPath: path, newPath: newPath, oldContent: oldContent, newContent: newContent})
	}

	// ---- Apply as one journaled transaction. ----
	txn := persistence.NewTransaction(persistence.JournalDir(s.dataDir))
	for _, wr := range writes {
		if wr.newPath != wr.oldPath {
			if err := txn.Move(wr.oldPath, wr.newPath); err != nil {
				failJSON(w, fmt.Sprintf("move room %d: %v", wr.id, err))
				return
			}
		}
		if err := txn.Replace(wr.newPath, wr.newContent, 0644); err != nil {
			failJSON(w, fmt.Sprintf("write room %d: %v", wr.id, err))
			return
		}
	}
	if err := txn.Commit(); err != nil {
		failJSON(w, fmt.Sprintf("commit bulk edit: %v", err))
		return
	}

	s.world.RebuildRoomIndex(s.dataDir)
	if s.reconcileRoom != nil {
		for _, wr := range writes {
			s.reconcileRoom(wr.id)
		}
	}

	var desc string
	if patch.Dir != nil && *patch.Dir != "" {
		desc = fmt.Sprintf("bulk edit %d rooms (move to %s)", len(req.IDs), *patch.Dir)
	} else {
		desc = fmt.Sprintf("bulk edit %d rooms", len(req.IDs))
	}

	var extraFiles []ExtraFile
	var firstDesc ChangeDesc
	for i, wr := range writes {
		ef := ExtraFile{
			FilePath:   wr.oldPath,
			OldContent: wr.oldContent,
			NewContent: wr.newContent,
		}
		if wr.newPath != wr.oldPath {
			ef.NewFilePath = wr.newPath
		}
		if i == 0 {
			firstDesc = ChangeDesc{
				Description: desc,
				FilePath:    wr.oldPath,
				OldContent:  wr.oldContent,
				NewContent:  wr.newContent,
			}
			if wr.newPath != wr.oldPath {
				firstDesc.NewFilePath = wr.newPath
			}
		} else {
			extraFiles = append(extraFiles, ef)
		}
	}

	firstDesc.ExtraFiles = extraFiles
	s.undoStack.Push(firstDesc)

	writeJSON(w, map[string]any{"ok": true, "count": len(req.IDs)})
}

func isEmptyPatch(p bulkEditPatch) bool {
	return p.Color == nil && p.BlockTransport == nil && p.Dir == nil && p.Hazard == nil
}