-- =========================================================
-- Cooperativa Agricola - Sell All Stock Event
-- =========================================================
-- O dono liquida TODO o estoque da cooperativa ao preço de mercado.
-- Enviado do cliente (dono) pro servidor.

---@class DepotSellAllEvent
DepotSellAllEvent = {}
DepotSellAllEvent_mt = Class(DepotSellAllEvent, Event)

InitEventClass(DepotSellAllEvent, "DepotSellAllEvent")

function DepotSellAllEvent.emptyNew()
    return Event.new(DepotSellAllEvent_mt)
end

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

function DepotSellAllEvent:writeStream(streamId, connection)
    streamWriteInt32(streamId, self.depotId or 0)
    streamWriteUInt8(streamId, self.farmId or 0)
end

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

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

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

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

    if ok then
        g_DepotManager:broadcastSync(self.depotId)
        DepotLogger.info(">>> DepotSellAllEvent OK: %.0f L vendidos, $%.2f", liters, revenue)
    else
        DepotLogger.info(">>> DepotSellAllEvent FALHOU: %s", tostring(msgKey))
    end
end

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