-- test_catalog_state.lua
-- Verifies session.catalog slot exists with correct shape.
dofile("wow_mock.lua")
dofile("../Core/HDGR_SchemeConstants.lua")
dofile("../Core/HDGR_Constants.lua")
dofile("../Core/HDGR_Actions.lua")
dofile("../Core/HDGR_Resolvers.lua")
dofile("../Core/HDGR_Format.lua")
dofile("../Core/HDGR_StoreFurnishings.lua")
dofile("../Core/HDGR_Store.lua")
dofile("../UI/HDGR_Selectors.lua")

HDG.Store:LoadFromSavedVariables()
local s = HDG.Store:GetState()
assert(s.session.catalog, "session.catalog slot exists")
assert(s.session.catalog.status == "idle", "status defaults to 'idle'")
assert(s.session.resolvers.catalog.tick == 0, "sweepGeneration starts at 0")
assert(s.session.catalog.refreshPending == false, "refreshPending starts false")
assert(s.session.catalog.variantsLoaded == false, "variantsLoaded starts false")
print("test_catalog_state: PASS")

-- Reducer transitions (appended in Task 2.3)
local A = HDG.Constants.ACTIONS

local function assertEq(actual, expected, msg)
    if actual ~= expected then
        error(string.format("FAIL [%s]: expected %s got %s", msg or "?",
            tostring(expected), tostring(actual)))
    end
end

-- CATALOG_LOAD_REQUESTED -> status = "loading"
HDG.Store:Dispatch({ type = A.CATALOG_LOAD_REQUESTED })
assertEq(HDG.Store:GetState().session.catalog.status, "loading", "REQUESTED -> loading")

-- CATALOG_LOAD_COMPLETED -> status = "ready", itemCount/vendorCount/generation set
HDG.Store:Dispatch({
    type = A.CATALOG_LOAD_COMPLETED,
    payload = { loadedAt = 0, itemCount = 1700, vendorCount = 195, generation = 1 },
})
local c = HDG.Store:GetState().session.catalog
assertEq(c.status, "ready", "COMPLETED -> ready")
assertEq(c.itemCount, 1700, "itemCount set from payload")
assertEq(c.vendorCount, 195, "vendorCount set from payload")
assertEq(HDG.Store:GetState().session.resolvers.catalog.tick, 1, "generation stamped into resolver tick")

-- CATALOG_REFRESH_QUEUED -> refreshPending true, variantsLoaded false, status unchanged
HDG.Store:Dispatch({ type = A.CATALOG_REFRESH_QUEUED })
local c2 = HDG.Store:GetState().session.catalog
assertEq(c2.refreshPending, true, "QUEUED -> refreshPending true")
assertEq(c2.variantsLoaded, false, "QUEUED -> variantsLoaded false (ownership may have changed)")
assertEq(c2.status, "ready", "QUEUED leaves status alone (still ready)")

-- CATALOG_REFRESH_COMPLETED -> refreshPending false, generation incremented
HDG.Store:Dispatch({
    type = A.CATALOG_REFRESH_COMPLETED,
    payload = { generation = 2 },
})
local c3 = HDG.Store:GetState().session.catalog
assertEq(c3.refreshPending, false, "REFRESH_COMPLETED clears refreshPending")
assertEq(HDG.Store:GetState().session.resolvers.catalog.tick, 2, "generation incremented")

-- CATALOG_VARIANTS_LOADED -> variantsLoaded true
HDG.Store:Dispatch({ type = A.CATALOG_VARIANTS_LOADED })
assertEq(HDG.Store:GetState().session.catalog.variantsLoaded, true, "VARIANTS_LOADED true")

print("test_catalog_state: reducer transitions PASS")
