local MOD = DugisGuideViewer
local AutoSell = MOD:RegisterModule("AutoSell")
AutoSell.essential = true

-- Grey quality constant
local POOR_QUALITY = 0

function AutoSell:Initialize()

    function MOD:MERCHANT_SHOW(event)
        if not DugisGuideViewer:UserSetting(DGV_AUTOSELL) then
            return
        end

        local total = 0

        for bagId = 0, 4 do
            local numSlots = C_Container.GetContainerNumSlots(bagId)

            if numSlots and numSlots > 0 then
                for slot = 1, numSlots do
                    local itemInfo = C_Container.GetContainerItemInfo(bagId, slot)

                    if itemInfo and itemInfo.hyperlink then
                        local quality = itemInfo.quality or -1

                        -- Only sell grey items (safe, official API)
                        if quality == POOR_QUALITY then
                            local merchantPrice = select(11, C_Item.GetItemInfo(itemInfo.hyperlink))
                            local stackSize = itemInfo.stackCount or 1

                            if merchantPrice and merchantPrice > 0 then
                                total = total + (merchantPrice * stackSize)

                                -- Safe call: only use if merchant frame is open
                                if MerchantFrame and MerchantFrame:IsShown() then
                                    C_Container.UseContainerItem(bagId, slot)
                                end
                            end
                        end
                    end
                end
            end
        end

        if total > 0 then
            DEFAULT_CHAT_FRAME:AddMessage(
                string.format("|cff11ff11Dugi Guides: |rGrey items sold for %s",
                GetCoinTextureString(total))
            )
        end
    end
end

function AutoSell:Load()
    MOD:RegisterEvent("MERCHANT_SHOW")
end

function AutoSell:Unload()
    MOD:UnregisterEvent("MERCHANT_SHOW")
end
