//! Shared state and message types for the CDC WebSocket server.

use serde::{Deserialize, Serialize};
use std::collections::HashSet;
use std::sync::Arc;
use tokio::sync::{Mutex, broadcast};

/// Broadcast sender type for event messages (JSON string).
pub type Tx = broadcast::Sender<String>;

/// JSON subscription request (deprecated). Prefer `X-Athena-Client` header at upgrade.
#[derive(Debug, Serialize, Deserialize)]
#[deprecated(
    since = "0.80.3",
    note = "Use X-Athena-Client header when connecting to WebSocket instead"
)]
pub struct SubscriptionRequest {
    /// Organization (client) ID to subscribe to.
    pub subscribe_to_organization_id: String,
}

/// Client-to-server control message (tagged JSON).
#[derive(Debug, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum ClientControlMessage {
    /// Replay ("time travel") buffered events for a channel.
    ///
    /// When `organization_id` is omitted, replays for all currently subscribed channels.
    Travel {
        #[serde(default)]
        organization_id: Option<String>,
        #[serde(default)]
        since_seq: Option<u64>,
        #[serde(default)]
        since_ts_ms: Option<i64>,
        #[serde(default)]
        limit: Option<usize>,
    },
}

/// Application state shared across WebSocket and HTTP handlers.
#[derive(Clone)]
pub struct AppState {
    /// Broadcast channel for event JSON strings.
    pub tx: Tx,
    /// Set of organization IDs that have at least one active WebSocket subscriber.
    pub active_subscribers: Arc<Mutex<HashSet<String>>>,
}
