local addonName, ns = ...

local function addCommand(rest)
    local id, qty = rest:match("^(%d+)%s*(%d*)$")
    if id then
        local decorID = tonumber(id)
        local name = ns.ResolveName and ns.ResolveName("DECOR", decorID) or nil
        ns.ShoppingList.Add("DECOR", decorID, tonumber(qty) or 1, name)
        return
    end
    if ns.AddItemLink and ns:AddItemLink(rest) then return end
    ns.Print("Usage: /hherald add <decorID> [qty]  or  /hherald add <item link>")
end

local function trackerCommand(rest)
    local arg = (rest or ""):lower()
    if arg == "blizzard" or arg == "standalone" then
        ns:SetTrackerMode(arg)
        return
    end
    local current = (ns.db and ns.db.trackerMode) or "standalone"
    ns.Print("Tracker mode: " .. current
        .. ". Use /hherald tracker standalone  or  /hherald tracker blizzard")
end

local function listCommand()
    local list = ns.ShoppingList.GetEntries()
    if #list == 0 then
        ns.Print("Shopping list is empty.")
        return
    end
    ns.Print("Shopping list:")
    for _, e in ipairs(list) do
        local available, inUse = ns.Availability.Get(e.type, e.id)
        print("  " .. ns.FormatEntryLine(e, available, inUse))
    end
end

function ns:RunCommand(msg)
    msg = (msg or ""):match("^%s*(.-)%s*$")
    local cmd, rest = msg:match("^(%S+)%s*(.-)$")
    cmd = cmd and cmd:lower() or ""

    if cmd == "" then
        if ns.ToggleMainFrame then ns:ToggleMainFrame() end
    elseif cmd == "add" then
        addCommand(rest)
    elseif cmd == "list" then
        listCommand()
    elseif cmd == "tracker" then
        trackerCommand(rest)
    elseif cmd == "settings" or cmd == "options" then
        if ns.OpenSettings then ns:OpenSettings() end
    else
        ns.Print("Commands: /hherald (toggle window), /hherald add <decorID|item link> [qty], /hherald list, /hherald tracker [standalone|blizzard], /hherald settings")
    end
end

SLASH_HOUSINGHERALD1 = "/hherald"
SLASH_HOUSINGHERALD2 = "/housingherald"
SlashCmdList["HOUSINGHERALD"] = function(msg)
    ns:RunCommand(msg)
end
