#include "broadcast_ack_manager.hpp"

BroadcastAckManager broadcastAckMgr;

void BroadcastAckManager::addPending(uint16_t seq)
{
    std::lock_guard<std::mutex> lock(mutex_);
    pendingAcks_[seq] = std::chrono::steady_clock::now();
    LOG_INFO("[AckManager] Added pending seq = " + std::to_string(seq));
}

void BroadcastAckManager::receiveAck(uint16_t seq)
{
    std::lock_guard<std::mutex> lock(mutex_);
    if (pendingAcks_.erase(seq) > 0)
    {
        LOG_INFO("[AckManager] Received ACK for seq = " + std::to_string(seq));
    }
    else
    {
        LOG_WARN("[AckManager] Received unexpected ACK for seq = " + std::to_string(seq));
    }
}

std::vector<uint16_t> BroadcastAckManager::checkTimeouts(std::chrono::seconds timeout)
{
    std::vector<uint16_t> timedOut;
    auto now = std::chrono::steady_clock::now();
    std::lock_guard<std::mutex> lock(mutex_);
    for (auto it = pendingAcks_.begin(); it != pendingAcks_.end();)
    {
        if (now - it->second > timeout)
        {
            timedOut.push_back(it->first);
            it = pendingAcks_.erase(it);
        }
        else
        {
            ++it;
        }
    }
    return timedOut;
}
