-- =========================================================
-- Cooperativa Agricola - Owner Sync Event (Server -> Clients)
-- =========================================================
-- Avisa todos os clientes quando o proprietário da cooperativa é
-- definido ou alterado. Sem isso, clientes que já estavam conectados
-- quando a coop foi colocada nunca sabem quem é o dono.

---@class CoopOwnerSyncEvent
CoopOwnerSyncEvent = {}
CoopOwnerSyncEvent_mt = Class(CoopOwnerSyncEvent, Event)

InitEventClass(CoopOwnerSyncEvent, "CoopOwnerSyncEvent")

function CoopOwnerSyncEvent.emptyNew()
    return Event.new(CoopOwnerSyncEvent_mt)
end

function CoopOwnerSyncEvent.new(ownerFarmId)
    local self = CoopOwnerSyncEvent.emptyNew()
    self.ownerFarmId = ownerFarmId or 0
    return self
end

function CoopOwnerSyncEvent:writeStream(streamId, connection)
    streamWriteUInt8(streamId, self.ownerFarmId or 0)
end

function CoopOwnerSyncEvent:readStream(streamId, connection)
    self.ownerFarmId = streamReadUInt8(streamId)
    self:run(connection)
end

function CoopOwnerSyncEvent:run(connection)
    -- Client-side: atualiza o ownerFarmId local
    if g_server then return end
    if not g_DepotManager or not g_DepotManager.coopState then return end
    g_DepotManager.coopState.ownerFarmId = self.ownerFarmId
    DepotLogger.info(">>> [CLIENT] CoopOwnerSyncEvent: owner agora é farmId=%d", self.ownerFarmId)
end

-- Server utility: avisa todos os clientes do owner atual
function CoopOwnerSyncEvent.broadcast(ownerFarmId)
    if not g_server then return end
    local evt = CoopOwnerSyncEvent.new(ownerFarmId)
    g_server:broadcastEvent(evt)
    DepotLogger.info(">>> [SERVER] CoopOwnerSyncEvent broadcast: owner=%d", ownerFarmId)
end
