local _, ns = ...
local L = ns.L or {}

local function registerSlashCommand(commandKey, aliases, handler)
    if type(commandKey) ~= "string" or type(aliases) ~= "table" or type(handler) ~= "function" then
        return
    end

    for index, alias in ipairs(aliases) do
        _G["SLASH_" .. commandKey .. tostring(index)] = alias
    end
    SlashCmdList[commandKey] = handler
end

function ns:HandleSlashCommand(message)
    local rawMessage = tostring(message or "")
    local command, rest = rawMessage:match("^%s*(%S*)%s*(.-)%s*$")
    command = string.lower(command or "")
    rest = rest or ""

    if command == "help" then
        self:Print("Use /vaultloom or /vl to open.")
        return
    end

    if command == "reset" or command == "resetpos" or command == "position" then
        if self.ResetWindowPosition then
            self:ResetWindowPosition()
            self:Print("Vaultloom window position reset.")
        else
            self:Print("Vaultloom window position reset is unavailable.")
        end
        return
    end

    if (command == "stats" or command == "stat" or command == "werte" or command == "wertefokus") and self.HandleStatFocusSlash then
        self:HandleStatFocusSlash(rest)
        return
    end

    if command == "shop" or command == "shopping" or command == "einkauf" or command == "einkaufsliste" then
        if self.ToggleShoppingList then
            self:ToggleShoppingList()
        else
            self:Print("Vaultloom shopping list is unavailable.")
        end
        return
    end

    if command == "loot" or command == "beute" or command == "quietloot" or command == "ruhigebeute" then
        if self.HandleQuietLootSlash then
            self:HandleQuietLootSlash(rest)
        else
            self:Print("Vaultloom Quiet Loot is unavailable.")
        end
        return
    end

    if self.UI and self.UI.Toggle then
        local ok, err = pcall(function()
            self.UI:Toggle()
        end)
        if not ok then
            self:Print("Vaultloom UI failed to open: " .. tostring(err))
        end
    else
        self:Print("Vaultloom UI module is unavailable.")
    end
end

function ns:RegisterSlashCommands()
    registerSlashCommand("VAULTLOOM", {
        "/vaultloom",
        "/vl",
    }, function(message)
        ns:HandleSlashCommand(message)
    end)
end
