import type { Payload } from "payload"; import type { GameStructure, StructureRoom } from "@/payload-types"; import type { InteriorBlueprintRoom } from "./types"; import { relId } from "@/lib/interior/relations"; /** * Idempotent provisioning of runtime room rows from the structure blueprint. * * Runs once per game-structure (tracked by `game-structures.interior.provisionedAt`). * For each blueprint room we upsert a `structure-rooms` row keyed by * (structure, roomKey), seeding level/condition/junk/fixtures from the blueprint * defaults. Blueprint edits after provisioning never retarget live rooms: the * snapshot of the floorplan + access config is stored on the game-structure at * provision time, and runtime state lives only in structure-rooms. */ export async function provisionInterior( payload: Payload, structure: Pick, ): Promise<{ provisioned: boolean; rooms: number }> { const snapshot = structure.interior; if (!snapshot || !Array.isArray(snapshot.rooms)) { return { provisioned: false, rooms: 0 }; } const blueprintRooms = snapshot.rooms as unknown as InteriorBlueprintRoom[]; if (blueprintRooms.length === 0) { return { provisioned: false, rooms: 0 }; } const existing = await payload.find({ collection: "structure-rooms", overrideAccess: true, depth: 0, limit: blueprintRooms.length, where: { structure: { equals: relId(structure.id) }, }, }); const created = await Promise.all( blueprintRooms.map((room) => provisionRoomRow(payload, structure.id, room, existing.docs)), ); const count = created.filter(Boolean).length; if (count > 0 || !snapshot.provisionedAt) { await payload.update({ collection: "game-structures", id: relId(structure.id)!, overrideAccess: true, data: { interior: { ...(structure.interior as Record), provisionedAt: new Date().toISOString(), }, }, }); } return { provisioned: count > 0, rooms: count }; } async function provisionRoomRow( payload: Payload, structureId: number | string, room: InteriorBlueprintRoom, existing: StructureRoom[], ): Promise { const roomKey = room.key; if (!roomKey) return false; const existingRow = (existing as unknown as Array>).find( (doc) => doc.roomKey === roomKey, ); if (existingRow) return false; await payload.create({ collection: "structure-rooms", overrideAccess: true, data: { structure: relId(structureId)!, roomKey, name: room.name ?? roomKey, level: room.initialLevel ?? 0, condition: 100, junkLevel: room.decay?.initialJunkLevel ?? 0, fixtures: (room.fixtures ?? []).map((f) => ({ key: f.key, name: f.name ?? f.key, broken: f.brokenByDefault ?? false, condition: f.brokenByDefault ? (f.condition ?? 0) : (f.condition ?? 100), blocksStation: f.blocksStation, })), }, }); return true; }