//! Per-room broadcast topics tracking the latest observed message sequence.

use std::sync::atomic::{AtomicI64, Ordering};

use tokio::sync::broadcast;

use crate::protocol::ServerWsEvent;

/// Broadcast channel for a single room scope with monotonic sequence tracking for resume gaps.
#[derive(Debug)]
pub struct RoomTopic {
    pub sender: broadcast::Sender<ServerWsEvent>,
    pub last_seq: AtomicI64,
}

impl RoomTopic {
    /// Creates a topic with the given broadcast buffer capacity.
    pub fn new(capacity: usize) -> Self {
        let (sender, _) = broadcast::channel(capacity);
        Self {
            sender,
            last_seq: AtomicI64::new(0),
        }
    }

    /// Returns the highest `room_seq` observed on this topic (in-memory, may lag durable state).
    pub fn current_seq(&self) -> i64 {
        self.last_seq.load(Ordering::Relaxed)
    }

    /// Records a new sequence number, keeping the maximum seen value.
    pub fn observe_seq(&self, seq: i64) {
        self.last_seq.fetch_max(seq, Ordering::Relaxed);
    }
}
