-- Roundtrip + malformed-input test for HDG.Projects.CrateCodec (HDGRCRATE:1:).
dofile("wow_mock.lua")
dofile("../Core/HDGR_Codec.lua")
dofile("../Core/HDGR_ProjectsCrateCodec.lua")

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

-- ===== roundtrip (name with a comma -> exercises urlencode) =====
local crate = { name = "Throne Hall, v2", decor = { { id = 111, count = 4 }, { id = 222, count = 1 }, { id = 333, count = 7 } } }
local enc = C.Encode(crate)
assertTrue(type(enc) == "string", "Encode returns a string")
assertTrue(enc:match("^HDGRCRATE:1:") ~= nil, "Encode has the magic prefix")
local dec = C.Decode(enc)
assertTrue(dec ~= nil, "Decode returns a record")
assertEq(dec.name, "Throne Hall, v2", "name roundtrips (comma survives urlencode)")
assertEq(#dec.decor, 3, "3 decor roundtrip")
assertEq(dec.decor[1].id, 111, "decor[1].id");  assertEq(dec.decor[1].count, 4, "decor[1].count")
assertEq(dec.decor[3].id, 333, "decor[3].id");  assertEq(dec.decor[3].count, 7, "decor[3].count")

-- ===== malformed / untrusted input -> nil (NEVER errors -- import boundary) =====
assertEq(C.Decode(nil), nil, "nil -> nil")
assertEq(C.Decode(""), nil, "empty -> nil")
assertEq(C.Decode("garbage"), nil, "no magic -> nil")
assertEq(C.Decode("HDGRCRATE:9:abc"), nil, "wrong version -> nil")
assertEq(C.Decode("HDGRCRATE:1:"), nil, "empty payload -> nil")
assertEq(C.Encode(nil), nil, "Encode(nil) -> nil")
assertEq(C.Encode("x"), nil, "Encode(non-table) -> nil")

-- ===== empty crate roundtrips (name only) =====
local d2 = C.Decode(C.Encode({ name = "Empty", decor = {} }))
assertEq(d2.name, "Empty", "empty crate name");  assertEq(#d2.decor, 0, "empty crate has no decor")

print("test_projects_cratecodec.lua passed")
