-- Roundtrip + malformed-input test for HDG.Projects.LayoutCodec (HDGRLAYOUT:2:).
-- Geometry-only, house-agnostic, ONE record per room. Multi-floor rooms carry a
-- `floors` span override (no stack links).
dofile("wow_mock.lua")
dofile("../Core/HDGR_Codec.lua")
dofile("../Core/HDGR_ProjectsIDs.lua")
dofile("../Core/HDGR_ProjectsLayoutCodec.lua")

local C   = HDG.Projects.LayoutCodec
local IDs = HDG.Projects.IDs
local function assertEq(a, e, l) if a ~= e then error((l or "") .. ": expected " .. tostring(e) .. ", got " .. tostring(a), 2) end end
local function assert_(c, l) if not c then error((l or "assert") .. " failed", 2) end end

-- Build a version: entry (floor 1) + a stairwell expanded to a 3-floor span override.
local h   = IDs.makeHouseID("alliance")
local f1  = IDs.makeFloorID(h, 1)
local st  = IDs.makeRoomID(f1, "a1")
local en  = IDs.makeRoomID(f1, "b1")
local version = { name = "My Build", numFloors = 2, rooms = {
    [en] = { shape = "entry",     cell = { x = 5, y = 5, rotation = 0 } },
    [st] = { shape = "staircase", cell = { x = 9, y = 5, rotation = 1 }, floors = 3 },
} }

-- ===== Roundtrip ============================================================
local code = C.Encode(version)
assert_(type(code) == "string" and code:match("^HDGRLAYOUT:2:") ~= nil, "encode produces a v2 tagged code")
local dec = C.Decode(code)
assert_(dec ~= nil, "decode succeeds")
assertEq(dec.name, "My Build", "name round-trips")
assertEq(dec.numFloors, 2, "numFloors round-trips")
assertEq(#dec.rooms, 2, "both rooms decoded")

-- Find the stairwell + entry descriptors.
local stair, entry
for _, r in ipairs(dec.rooms) do
    if r.shape == "staircase" then stair = r elseif r.shape == "entry" then entry = r end
end
assert_(stair ~= nil and entry ~= nil, "both shapes present")
assertEq(stair.rotation, 1, "rotation round-trips")
assertEq(stair.floors, 3, "stairwell floors override round-trips")
assertEq(entry.floors, nil, "default-span room has no floors override (0 -> nil)")
assertEq(stair.x, 9, "x round-trips")
assertEq(entry.y, 5, "y round-trips")

-- ===== Malformed input ======================================================
assertEq(C.Decode("garbage"), nil, "garbage -> nil")
assertEq(C.Decode("HDGRCRATE:2:abc"), nil, "wrong magic -> nil")
assertEq(C.Decode("HDGRLAYOUT:1:abc"), nil, "old version -> nil")
assertEq(C.Decode(""), nil, "empty -> nil")
assertEq(C.Encode(nil), nil, "encode nil -> nil")
assertEq(C.Encode({ name = "x" }), nil, "encode no-rooms -> nil")

print("test_projects_layoutcodec.lua passed")
