-- =========================================================
-- Cooperativa Agricola - Sell Stock Item Event
-- =========================================================
-- O dono vende UM item do estoque da cooperativa ao mercado.
-- Permite liquidação seletiva (sem vender tudo por engano).

---@class DepotSellItemEvent
DepotSellItemEvent = {}
DepotSellItemEvent_mt = Class(DepotSellItemEvent, Event)

InitEventClass(DepotSellItemEvent, "DepotSellItemEvent")

function DepotSellItemEvent.emptyNew()
    return Event.new(DepotSellItemEvent_mt)
end

function DepotSellItemEvent.new(depotId, fillTypeName, farmId)
    local self = DepotSellItemEvent.emptyNew()
    self.depotId      = depotId
    self.fillTypeName = fillTypeName
    self.farmId       = farmId
    return self
end

function DepotSellItemEvent:writeStream(streamId, connection)
    streamWriteInt32(streamId, self.depotId or 0)
    streamWriteString(streamId, self.fillTypeName or "")
    streamWriteUInt8(streamId, self.farmId or 0)
end

function DepotSellItemEvent:readStream(streamId, connection)
    self.depotId      = streamReadInt32(streamId)
    self.fillTypeName = streamReadString(streamId)
    self.farmId       = streamReadUInt8(streamId)
    self:run(connection)
end

function DepotSellItemEvent:run(connection)
    if not g_server or not g_DepotManager then return end

    -- Segurança: só o dono pode vender o estoque
    local coop = g_DepotManager.coopState
    if not coop or not coop:isOwner(self.farmId) then
        DepotLogger.warning(">>> DepotSellItemEvent NEGADO: farm=%d não é o dono", self.farmId)
        return
    end

    local ok, msgKey, liters, revenue = g_DepotManager.depotSystem:sellStockItem(
        self.depotId, self.fillTypeName, self.farmId)

    if ok then
        g_DepotManager:broadcastSync(self.depotId)
        DepotLogger.info(">>> DepotSellItemEvent OK: %s %.0f L, $%.2f",
            self.fillTypeName, liters, revenue)
    end
end

function DepotSellItemEvent.sendToServer(depotId, fillTypeName, farmId)
    local evt = DepotSellItemEvent.new(depotId, fillTypeName, farmId)
    if g_server then
        evt:run(nil)
    else
        g_client:getServerConnection():sendEvent(evt)
    end
end
