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

function AutoSell:Initialize()
    function MOD:MERCHANT_SHOW(event)
        if DugisGuideViewer:UserSetting(DGV_AUTOSELL) then
            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 info = C_Container.GetContainerItemInfo(bagId, slot)
                        if info and info.hyperlink then
                            -- Use official quality instead of string.find on the link color
                            local quality = info.quality
                            if quality == 0 then  -- grey (poor) quality
                                local merchantPrice = select(11, GetItemInfo(info.hyperlink))
                                local stackSize = info.stackCount or 1

                                if merchantPrice and merchantPrice > 0 then
                                    total = total + merchantPrice * stackSize
                                    C_Container.UseContainerItem(bagId, slot)
                                end
                            end
                        end
                    end
                end
            end

            if total > 0 then
                DEFAULT_CHAT_FRAME:AddMessage(
                    string.format("|cff11ff11Dugi Guides: |rGrey quality 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
end
