//! Concurrent server state management.
//!
//! This module defines the global application state shared across all active
//! Tokio tasks. It heavily relies on lock-free and fine-grained locking primitives
//! like `DashMap` and `AtomicU32` to ensure high performance without stuttering.

use dashmap::DashMap;
use std::sync::atomic::{AtomicU32, Ordering};

/// Represents the session data for a single connected user.
#[allow(dead_code)]
pub struct UserState {
    /// The client-chosen username for display in channels.
    pub username: String,
}

/// The global application state tracking all connections and rooms.
pub struct AppState {
    /// A highly concurrent hash map linking active session tokens to their user data.
    pub active_users: DashMap<u32, UserState>,
    /// A simple atomic counter for issuing unique sequential session tokens.
    next_token: AtomicU32,
}

impl AppState {
    /// Creates a new, empty application state.
    #[must_use]
    pub fn new() -> Self {
        Self {
            active_users: DashMap::new(),
            next_token: AtomicU32::new(1),
        }
    }

    /// Generates a strictly unique, monotonically increasing session token.
    ///
    /// We use `Ordering::Relaxed` because we only need atomicity on the counter
    /// itself, not strict memory ordering with other operations.
    #[must_use]
    pub fn generate_token(&self) -> u32 {
        self.next_token.fetch_add(1, Ordering::Relaxed)
    }
}

impl Default for AppState {
    fn default() -> Self {
        Self::new()
    }
}
