Skip to main content

runecast_protocol/protocol/
types.rs

1//! Shared types used in protocol messages.
2//!
3//! These types are used by both client and server messages and represent
4//! the core data structures of the game.
5
6use serde::{Deserialize, Serialize};
7
8// Re-export model types that are part of the protocol
9// These would come from crate::models in the actual backend
10// For now, we define them here for the protocol module to be self-contained
11
12/// Why a turn was passed.
13#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
14#[serde(rename_all = "snake_case")]
15pub enum TurnPassReason {
16    /// The player chose to pass.
17    Voluntary,
18    /// The turn timer expired.
19    Timer,
20    /// The player disconnected and the turn grace period ran out.
21    Disconnected,
22    /// The player left the game.
23    Left,
24}
25
26/// How a WebSocket connection relates to an existing session of the player.
27#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
28#[serde(rename_all = "snake_case")]
29pub enum ConnectKind {
30    /// A first connection.
31    Fresh,
32    /// Re-establishing a dropped connection from the same tab.
33    Reconnect,
34    /// Deliberately replacing a live connection from another tab.
35    TakeOver,
36}
37
38/// The handshake on the WebSocket URL query: `?token=...&tab=...&kind=...`.
39#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
40pub struct ConnectParams {
41    /// Identifier of the connecting browser tab.
42    #[serde(default, skip_serializing_if = "Option::is_none")]
43    pub tab: Option<String>,
44    /// How this connection relates to an existing session.
45    #[serde(default, skip_serializing_if = "Option::is_none")]
46    pub kind: Option<ConnectKind>,
47}
48
49/// A per-mode player cap.
50#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
51pub struct ModeCap {
52    /// The mode the cap applies to.
53    pub game_type: GameType,
54    /// Maximum players in a game of that mode.
55    pub max_players: u8,
56}
57
58/// Grid position (row, column).
59#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
60pub struct Position {
61    pub row: usize,
62    pub col: usize,
63}
64
65/// Letter multiplier on a grid cell.
66#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
67#[serde(rename_all = "snake_case")]
68pub enum Multiplier {
69    DoubleLetter,
70    TripleLetter,
71    DoubleWord,
72}
73
74/// A single cell in the game grid.
75#[derive(Debug, Clone, Serialize, Deserialize)]
76pub struct GridCell {
77    pub letter: char,
78    pub value: u8,
79    #[serde(skip_serializing_if = "Option::is_none")]
80    pub multiplier: Option<Multiplier>,
81    #[serde(default)]
82    pub has_gem: bool,
83    /// True when this cell is a "hole" — occupies its position in the
84    /// layout but can't be selected as part of a word path. Used by
85    /// Adventure Mode levels that want asymmetric playable regions.
86    /// Hole cells have no letter contribution and are skipped by the
87    /// refill pipeline.
88    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
89    pub is_hole: bool,
90    /// True when this cell has been **poisoned** by a Snake adventure
91    /// event. Poisoned letters contribute negative value when used in
92    /// a word (sign-flipped — `value` becomes `-value` for scoring),
93    /// so players want to avoid them. Poison clears when the cell is
94    /// rerolled (word consumption or another event hitting the cell).
95    /// Adventure-only; multiplayer sessions never set this.
96    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
97    pub is_poisoned: bool,
98    /// True when this cell has been **abducted** by a UFO adventure
99    /// event. Abducted cells are temporarily unselectable (mirrors
100    /// `is_hole` for path validation) and reroll back to normal on a
101    /// later round. Adventure-only; multiplayer sessions never set
102    /// this.
103    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
104    pub is_abducted: bool,
105}
106
107/// The 5x5 game grid.
108pub type Grid = Vec<Vec<GridCell>>;
109
110/// Adventure Mode random-event kinds. Carried on `ServerMessage::AdventureEvent`.
111///
112/// The `Unknown` variant catches any future kind an older client doesn't
113/// recognize, so adding new kinds server-side is non-breaking. Clients
114/// matching on this enum should always handle the `Unknown` arm (e.g.
115/// by rendering a generic "Something happened!" toast).
116#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
117#[serde(rename_all = "snake_case")]
118pub enum AdventureEventKind {
119    /// 3×3 blast centered on a random cell; those cells reroll.
120    Bomb,
121    /// Poisons a handful of cells for a couple of rounds.
122    Snake,
123    /// Steals all multipliers currently on the board.
124    Ufo,
125    /// Forward-compat fallback. Serde decodes any unknown kind string
126    /// to this variant via `#[serde(other)]`.
127    #[serde(other)]
128    Unknown,
129}
130
131// ============================================================================
132// Lobby Types
133// ============================================================================
134
135/// Type of lobby - determines how players join.
136#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
137#[serde(rename_all = "snake_case")]
138pub enum LobbyType {
139    /// Lobby tied to a specific Discord channel
140    Channel,
141    /// Custom lobby with a shareable code
142    Custom,
143}
144
145/// Game type for game pools within a lobby.
146///
147/// Each lobby can have multiple game pools, one per game type. Players wait in pools for matchmaking.
148/// Players join a game pool to find matches for that game type.
149#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
150#[serde(rename_all = "snake_case")]
151pub enum GameType {
152    /// Free-for-all open game (default)
153    Open,
154    /// 2v2 team game
155    TwoVTwo,
156    /// Adventure/co-op mode
157    Adventure,
158    /// Configurable unranked custom ("sandbox") game.
159    Sandbox,
160    /// Daily Challenge — solo timed run on the shared daily board.
161    Daily,
162    /// RuneBox — timed simultaneous word hunt. No turns, no bonus tiles and no
163    /// tile replacement; a word scores its letter count. All players work the
164    /// same static board at once for the round's duration.
165    RuneBox,
166    /// Forward-compat fallback for game types this client doesn't know.
167    #[serde(other)]
168    Unknown,
169}
170
171/// `Unknown`, so that a payload predating a field carrying `GameType` decodes
172/// to the forward-compat variant instead of failing outright. Deliberately not
173/// `Open`: a wrong-but-plausible default is worse than an explicitly unknown
174/// one, because it reads as a real answer.
175impl Default for GameType {
176    fn default() -> Self {
177        Self::Unknown
178    }
179}
180
181impl std::fmt::Display for GameType {
182    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
183        match self {
184            GameType::Open => write!(f, "open"),
185            GameType::TwoVTwo => write!(f, "two_v_two"),
186            GameType::Adventure => write!(f, "adventure"),
187            GameType::Sandbox => write!(f, "sandbox"),
188            GameType::Daily => write!(f, "daily"),
189            GameType::RuneBox => write!(f, "rune_box"),
190            GameType::Unknown => write!(f, "unknown"),
191        }
192    }
193}
194
195// ============================================================================
196// Player names
197// ============================================================================
198
199/// What to call a player, in the context this message was sent in.
200///
201/// Show [`runecast`](Self::runecast) when it is set, otherwise
202/// [`discord`](Self::discord). A viewer who has turned on austere nicknames is
203/// shown `discord` always. [`shown`](Self::shown) applies that rule.
204///
205/// ```
206/// use runecast_protocol::PlayerName;
207///
208/// let name = PlayerName::new("Ada", Some("Rune Queen".to_string()));
209/// assert_eq!(name.shown(false), "Rune Queen");
210/// assert_eq!(name.shown(true), "Ada");
211/// ```
212#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
213pub struct PlayerName {
214    /// The name Discord itself would show here: the player's nickname in this
215    /// server (when the lobby is in one and they have one there), else their
216    /// Discord display name, else their username.
217    pub discord: String,
218    /// The nickname the player chose in RuneCast, if any.
219    #[serde(default, skip_serializing_if = "Option::is_none")]
220    pub runecast: Option<String>,
221}
222
223impl PlayerName {
224    /// A name from its two layers.
225    #[must_use]
226    pub fn new(discord: impl Into<String>, runecast: Option<String>) -> Self {
227        Self {
228            discord: discord.into(),
229            runecast,
230        }
231    }
232
233    /// The name to display, given the viewer's austere-nicknames setting.
234    #[must_use]
235    pub fn shown(&self, austere: bool) -> &str {
236        match &self.runecast {
237            Some(chosen) if !austere && !chosen.is_empty() => chosen,
238            _ => &self.discord,
239        }
240    }
241}
242
243/// Player information in the lobby (pre-game).
244#[serde_with::serde_as]
245#[derive(Debug, Clone, Serialize, Deserialize)]
246pub struct LobbyPlayerInfo {
247    /// User ID
248    #[serde_as(as = "serde_with::DisplayFromStr")]
249    pub user_id: i64,
250    /// The player's raw Discord username: the unique handle. Display
251    /// [`name`](Self::name) instead when it is present.
252    pub username: String,
253    /// What to call this player. Absent from servers older than protocol
254    /// 0.20; fall back to `username`.
255    #[serde(default, skip_serializing_if = "Option::is_none")]
256    pub name: Option<PlayerName>,
257    #[serde(skip_serializing_if = "Option::is_none")]
258    pub avatar_url: Option<String>,
259    /// Profile banner URL (Discord CDN)
260    #[serde(skip_serializing_if = "Option::is_none")]
261    pub banner_url: Option<String>,
262    /// Profile accent color (integer representation)
263    #[serde(skip_serializing_if = "Option::is_none")]
264    pub accent_color: Option<i32>,
265    /// The player's status within a game pool, if they are in one.
266    #[serde(skip_serializing_if = "Option::is_none")]
267    pub current_game_pool: Option<GameType>,
268    /// Game they are in, if any
269    pub active_game_id: Option<String>,
270    /// Game they are spectating, if any
271    pub spectate_game_id: Option<String>,
272}
273
274/// Summary of a game visible from the lobby.
275#[derive(Debug, Clone, Serialize, Deserialize)]
276pub struct GameSummary {
277    pub game_id: String,
278    pub state: GameState,
279    pub current_round: u8,
280    pub max_rounds: u8,
281    pub player_count: u8,
282    pub spectator_count: u8,
283}
284
285/// High-level game state (not the full game data).
286#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
287#[serde(rename_all = "snake_case")]
288pub enum GameState {
289    /// Waiting for players / not started
290    Idle,
291    /// Players are queueing
292    Queueing,
293    /// Game is starting (countdown)
294    Starting,
295    /// Game is in progress
296    InProgress,
297    /// Game has ended
298    Finished,
299    /// Game was cancelled
300    Cancelled,
301}
302
303// ============================================================================
304// In-Game Types
305// ============================================================================
306
307/// Player information during a game.
308#[serde_with::serde_as]
309#[derive(Debug, Clone, Serialize, Deserialize)]
310pub struct PlayerInfo {
311    /// User ID (string to preserve JS number precision)
312    #[serde_as(as = "serde_with::DisplayFromStr")]
313    pub user_id: i64,
314    /// The player's raw Discord username: the unique handle. Display
315    /// [`name`](Self::name) instead when it is present.
316    pub username: String,
317    /// What to call this player. Absent from servers older than protocol
318    /// 0.20; fall back to `username`.
319    #[serde(default, skip_serializing_if = "Option::is_none")]
320    pub name: Option<PlayerName>,
321    #[serde(skip_serializing_if = "Option::is_none")]
322    pub avatar_url: Option<String>,
323    pub score: i32,
324    /// Gems collected (0-10, used for powers)
325    #[serde(default)]
326    pub gems: i32,
327    /// Team number for team modes
328    #[serde(skip_serializing_if = "Option::is_none")]
329    pub team: Option<i32>,
330    /// Whether the player is currently connected
331    #[serde(default = "default_true")]
332    pub is_connected: bool,
333}
334
335fn default_true() -> bool {
336    true
337}
338
339/// Slug of the standard, ranked dictionary. Every other dictionary is unranked.
340pub const MAIN_DICTIONARY: &str = "main";
341
342/// Serde default for `dictionary` fields: payloads from before v0.23.0 carry
343/// none, and every game then used the standard dictionary.
344#[must_use]
345pub fn default_dictionary() -> String {
346    MAIN_DICTIONARY.to_string()
347}
348
349/// Player info specifically for `GameStarted` message (includes turn order).
350#[serde_with::serde_as]
351#[derive(Debug, Clone, Serialize, Deserialize)]
352pub struct GamePlayerInfo {
353    #[serde_as(as = "serde_with::DisplayFromStr")]
354    pub user_id: i64,
355    /// The player's raw Discord username: the unique handle. Display
356    /// [`name`](Self::name) instead when it is present.
357    pub username: String,
358    /// What to call this player. Absent from servers older than protocol
359    /// 0.20; fall back to `username`.
360    #[serde(default, skip_serializing_if = "Option::is_none")]
361    pub name: Option<PlayerName>,
362    #[serde(skip_serializing_if = "Option::is_none")]
363    pub avatar_url: Option<String>,
364    pub turn_order: u8,
365    pub score: i32,
366    pub gems: i32,
367    pub is_connected: bool,
368    #[serde(skip_serializing_if = "Option::is_none")]
369    pub team: Option<i32>,
370}
371
372/// Spectator information.
373#[serde_with::serde_as]
374#[derive(Debug, Clone, Serialize, Deserialize)]
375pub struct SpectatorInfo {
376    #[serde_as(as = "serde_with::DisplayFromStr")]
377    pub user_id: i64,
378    /// The player's raw Discord username: the unique handle. Display
379    /// [`name`](Self::name) instead when it is present.
380    pub username: String,
381    /// What to call this player. Absent from servers older than protocol
382    /// 0.20; fall back to `username`.
383    #[serde(default, skip_serializing_if = "Option::is_none")]
384    pub name: Option<PlayerName>,
385    #[serde(skip_serializing_if = "Option::is_none")]
386    pub avatar_url: Option<String>,
387}
388
389/// Score information for results/leaderboards.
390#[serde_with::serde_as]
391#[derive(Debug, Clone, Serialize, Deserialize)]
392pub struct ScoreInfo {
393    #[serde_as(as = "serde_with::DisplayFromStr")]
394    pub user_id: i64,
395    /// The player's raw Discord username: the unique handle. Display
396    /// [`name`](Self::name) instead when it is present.
397    pub username: String,
398    /// What to call this player. Absent from servers older than protocol
399    /// 0.20; fall back to `username`.
400    #[serde(default, skip_serializing_if = "Option::is_none")]
401    pub name: Option<PlayerName>,
402    pub score: i32,
403}
404
405/// One player's standing in a RuneBox **match**, as of the end of some round.
406///
407/// A match is several rounds; [`ScoreInfo`] describes a single round. Both are
408/// sent on `RuneBoxRoundEnded` because they answer different questions — "who
409/// won this round" and "who is winning the match".
410///
411/// Carries no word list, by construction. RuneBox found-sets are independent,
412/// so another player's words stay worth full value to you and naming them at
413/// round end would hand over the answers for a board that is still fresh in
414/// everyone's memory.
415#[serde_with::serde_as]
416#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
417pub struct RuneBoxStanding {
418    /// Serializes as a quoted STRING, like every snowflake on this wire — an
419    /// id above 2^53 silently loses precision as a JSON number in JS.
420    #[serde_as(as = "serde_with::DisplayFromStr")]
421    pub player_id: i64,
422    /// The player's raw Discord username: the unique handle. Display
423    /// [`name`](Self::name) instead when it is present.
424    pub username: String,
425    /// What to call this player. Absent from servers older than protocol
426    /// 0.20; fall back to `username`.
427    #[serde(default, skip_serializing_if = "Option::is_none")]
428    pub name: Option<PlayerName>,
429    /// Rounds this player has won outright.
430    ///
431    /// The deciding number in a two-player match, which is best-of-3 rather
432    /// than elimination — there is nobody to eliminate until it is over. In a
433    /// three-or-more-player match the field still counts round wins, but
434    /// elimination is what decides the match, so nothing reads it.
435    pub round_wins: u8,
436    /// This player's scores summed across every round played so far.
437    pub total_score: i32,
438    /// True once this player has been eliminated and moved to spectating.
439    pub eliminated: bool,
440}
441
442/// Player info in lobby game list (simplified).
443#[serde_with::serde_as]
444#[derive(Debug, Clone, Serialize, Deserialize)]
445pub struct LobbyGamePlayerInfo {
446    #[serde_as(as = "serde_with::DisplayFromStr")]
447    pub user_id: i64,
448    /// The player's raw Discord username: the unique handle. Display
449    /// [`name`](Self::name) instead when it is present.
450    pub username: String,
451    /// What to call this player. Absent from servers older than protocol
452    /// 0.20; fall back to `username`.
453    #[serde(default, skip_serializing_if = "Option::is_none")]
454    pub name: Option<PlayerName>,
455    pub score: i32,
456}
457
458/// Game info as shown in lobby games list.
459#[derive(Debug, Clone, Serialize, Deserialize)]
460pub struct LobbyGameInfo {
461    pub game_id: String,
462    /// Which game type / pool this game belongs to (Open/Sandbox/Adventure),
463    /// so clients can distinguish concurrent games in one lobby.
464    pub game_type: GameType,
465    pub current_round: i32,
466    pub max_rounds: i32,
467    pub players: Vec<LobbyGamePlayerInfo>,
468}
469
470// ============================================================================
471// Snapshot Types
472// ============================================================================
473
474/// Complete snapshot of the game state.
475#[serde_with::serde_as]
476#[derive(Debug, Clone, Serialize, Deserialize)]
477pub struct GameSnapshot {
478    pub game_id: String,
479    /// Which mode this game is, so the snapshot is self-describing.
480    ///
481    /// Without this a client has to *infer* the mode from indirect tells — the
482    /// lobby games list, the joined pool, or the presence of a per-viewer
483    /// field. That inference was load-bearing for RuneBox and it read the
484    /// wrong thing more than once, so the type rides on the snapshot itself.
485    ///
486    /// `#[serde(default)]` (→ `GameType::Unknown`) keeps a payload written
487    /// before this field existed decodable; it is NOT an invitation to omit
488    /// the field when building one. Every construction site must set it, which
489    /// is why this is a plain field and not an `Option`.
490    #[serde(default)]
491    pub game_type: GameType,
492    pub state: GameState,
493    pub grid: Grid,
494    pub players: Vec<PlayerInfo>,
495    pub spectators: Vec<SpectatorInfo>,
496    #[serde_as(as = "serde_with::DisplayFromStr")]
497    pub current_turn: i64,
498    pub round: u8,
499    pub max_rounds: u8,
500    pub used_words: Vec<String>,
501    pub timer_vote_state: TimerVoteState,
502    /// Your player info (for the receiving client)
503    #[serde(skip_serializing_if = "Option::is_none")]
504    pub your_player: Option<PlayerInfo>,
505    /// When the turn timer expires (if active)
506    #[serde(skip_serializing_if = "Option::is_none")]
507    pub timer_expiration_time: Option<chrono::DateTime<chrono::Utc>>,
508    /// `Some` marks an unranked custom (sandbox) game, mirroring
509    /// `GameStarted.custom`, so the unranked badge survives reconnect/spectate.
510    #[serde(default, skip_serializing_if = "Option::is_none")]
511    pub custom: Option<CustomMeta>,
512    /// Server-authoritative time left in a Daily Challenge run, in milliseconds.
513    /// Mirrors `GameStarted.time_remaining_ms` so a daily run that recovers via
514    /// the snapshot/reconnect path keeps its deadline. Omitted otherwise.
515    #[serde(default, skip_serializing_if = "Option::is_none")]
516    pub time_remaining_ms: Option<u64>,
517    /// The receiving player's own found words (RuneBox only).
518    ///
519    /// Restores the word list after a reconnect. The authoritative score
520    /// already rides on `PlayerInfo`, but without this a reconnecting player
521    /// sees an empty list and gets a confusing "already found" when
522    /// re-submitting a word they had already scored. Omitted for every other
523    /// mode, whose found-words concept is the game-global `used_words`.
524    #[serde(default, skip_serializing_if = "Option::is_none")]
525    pub your_found_words: Option<Vec<String>>,
526    /// Slug of the dictionary this game was started with, so the badge survives
527    /// reconnect/spectate. Absent from backends before v0.23.0, so it reads as
528    /// `main`; always serialized.
529    #[serde(default = "default_dictionary")]
530    pub dictionary: String,
531}
532
533// ============================================================================
534// Timer Vote Types
535// ============================================================================
536
537/// State of the timer vote system.
538///
539/// The timer vote allows players to collectively vote to start a turn timer
540/// on the current player. This prevents indefinite stalling.
541#[serde_with::serde_as]
542#[derive(Debug, Clone, Serialize, Deserialize, Default)]
543#[serde(tag = "status", rename_all = "snake_case")]
544pub enum TimerVoteState {
545    /// No vote in progress, button is idle
546    #[default]
547    Idle,
548
549    /// Vote is in progress
550    VoteInProgress {
551        /// User ID of who initiated the vote
552        #[serde_as(as = "serde_with::DisplayFromStr")]
553        initiator_id: i64,
554        /// User IDs of players who have voted yes
555        #[serde_as(as = "Vec<serde_with::DisplayFromStr>")]
556        voters: Vec<i64>,
557        /// Total votes needed to pass
558        votes_needed: u32,
559        /// When the vote expires
560        expires_at: chrono::DateTime<chrono::Utc>,
561    },
562
563    /// Timer is actively counting down
564    TimerActive {
565        /// When the timer expires
566        expires_at: chrono::DateTime<chrono::Utc>,
567        /// Target player ID (user ID)
568        #[serde_as(as = "serde_with::DisplayFromStr")]
569        target_player_id: i64,
570    },
571
572    /// Vote failed, in cooldown before another can start
573    Cooldown {
574        /// When the cooldown expires
575        expires_at: chrono::DateTime<chrono::Utc>,
576    },
577
578    /// Feature disabled (not enough players)
579    Disabled,
580}
581
582// ============================================================================
583// Rematch Countdown Types
584// ============================================================================
585
586/// State of the auto-rematch countdown after a game ends.
587///
588/// When a game ends, players are automatically re-queued and a countdown begins.
589/// Any player can trigger an early start, or opt out to return to the lobby.
590#[serde_with::serde_as]
591#[derive(Debug, Clone, Serialize, Deserialize, Default)]
592#[serde(tag = "status", rename_all = "snake_case")]
593pub enum RematchCountdownState {
594    /// No rematch countdown active
595    #[default]
596    Idle,
597
598    /// Countdown is active - new game will start when it reaches 0
599    Active {
600        /// When the countdown expires (absolute time for clock sync)
601        expires_at: chrono::DateTime<chrono::Utc>,
602        /// Seconds remaining (for initial state display)
603        seconds_remaining: u32,
604        /// Player IDs still in the rematch pool
605        #[serde_as(as = "Vec<serde_with::DisplayFromStr>")]
606        player_ids: Vec<i64>,
607        /// The game pool/game type for the rematch
608        game_type: GameType,
609    },
610
611    /// Auto-rematch is off for the lobby, or was switched off mid-countdown: no
612    /// timer. Each eligible player who presses Play Again (`TriggerRematch`)
613    /// joins `ready`; the rematch starts for `ready` only, once it reaches
614    /// `needed`. Exists only while at least `needed` players are eligible.
615    OptIn {
616        /// Players who pressed Play Again.
617        #[serde_as(as = "Vec<serde_with::DisplayFromStr>")]
618        ready: Vec<i64>,
619        /// The previous game's players who may still opt in (a superset of `ready`).
620        #[serde_as(as = "Vec<serde_with::DisplayFromStr>")]
621        eligible: Vec<i64>,
622        /// How many must be ready before the rematch starts (`REMATCH_MIN_PLAYERS`).
623        needed: u8,
624        /// The game pool/game type for the rematch
625        game_type: GameType,
626    },
627
628    /// A player triggered an early start
629    Starting {
630        /// Who triggered the early start (None if countdown expired naturally)
631        #[serde(skip_serializing_if = "Option::is_none")]
632        #[serde_as(as = "Option<serde_with::DisplayFromStr>")]
633        triggered_by: Option<i64>,
634    },
635}
636
637// ============================================================================
638// Delta Types (for efficient state updates)
639// ============================================================================
640
641/// Changes to lobby state (for delta updates instead of full snapshots).
642#[serde_with::serde_as]
643#[derive(Debug, Clone, Serialize, Deserialize)]
644#[serde(tag = "change_type", rename_all = "snake_case")]
645pub enum LobbyChange {
646    /// The lobby's auto-rematch setting changed. Any lobby member may change it.
647    AutoRematchChanged {
648        enabled: bool,
649        #[serde_as(as = "serde_with::DisplayFromStr")]
650        changed_by: i64,
651    },
652
653    /// The lobby's dictionary changed. Any lobby member may change it.
654    DictionaryChanged {
655        dictionary: String,
656        #[serde_as(as = "serde_with::DisplayFromStr")]
657        changed_by: i64,
658    },
659}
660
661// ============================================================================
662// Admin Types
663// ============================================================================
664
665/// Admin game info (for admin panel).
666#[serde_with::serde_as]
667#[derive(Debug, Clone, Serialize, Deserialize)]
668pub struct AdminGameInfo {
669    pub game_id: String,
670    pub state: GameState,
671    pub created_at: chrono::DateTime<chrono::Utc>,
672    #[serde_as(as = "Vec<serde_with::DisplayFromStr>")]
673    pub players: Vec<i64>,
674}
675
676// ============================================================================
677// Error Types
678// ============================================================================
679
680/// Standard error codes for protocol errors.
681#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
682#[serde(rename_all = "snake_case")]
683pub enum ErrorCode {
684    // Lobby errors
685    LobbyNotFound,
686    LobbyFull,
687    NotInLobby,
688    AlreadyInLobby,
689
690    // Game errors
691    GameNotFound,
692    GameInProgress,
693    GameNotActive,
694    NotInGame,
695    AlreadyInGame,
696
697    // Turn errors
698    NotYourTurn,
699    InvalidAction,
700
701    // Word submission errors
702    InvalidPath,
703    PathTooShort,
704    WordNotInDictionary,
705    WordAlreadyUsed,
706
707    // Permission errors
708    NotHost,
709    NotEnoughPlayers,
710    TooManyPlayers,
711    /// Caller lacks the capability for an entitlement-gated action
712    /// (e.g. starting or configuring a custom sandbox game when
713    /// `sandbox_enabled` is false for them). Server-authoritative.
714    NotAuthorized,
715
716    // Resource errors
717    InsufficientGems,
718
719    // Generic
720    InvalidRequest,
721    InternalError,
722}
723
724impl ErrorCode {
725    /// Get a human-readable message for this error code.
726    #[must_use]
727    pub fn message(&self) -> &'static str {
728        match self {
729            Self::LobbyNotFound => "Lobby not found",
730            Self::LobbyFull => "Lobby is full",
731            Self::NotInLobby => "You must be in a lobby",
732            Self::AlreadyInLobby => "Already in a lobby",
733            Self::GameNotFound => "Game not found",
734            Self::GameInProgress => "A game is already in progress",
735            Self::GameNotActive => "Game is not active",
736            Self::NotInGame => "You are not in this game",
737            Self::AlreadyInGame => "You are already in this game",
738            Self::NotYourTurn => "It's not your turn",
739            Self::InvalidAction => "Invalid action",
740            Self::InvalidPath => "Invalid path - letters must be adjacent",
741            Self::PathTooShort => "Word must be at least 3 letters",
742            Self::WordNotInDictionary => "Word not found in dictionary",
743            Self::WordAlreadyUsed => "Word has already been used",
744            Self::NotHost => "Only the host can do this",
745            Self::NotEnoughPlayers => "Not enough players",
746            Self::TooManyPlayers => "Too many players",
747            Self::NotAuthorized => "You are not authorized to do this",
748            Self::InsufficientGems => "Not enough gems",
749            Self::InvalidRequest => "Invalid request",
750            Self::InternalError => "Internal server error",
751        }
752    }
753}
754
755impl std::fmt::Display for ErrorCode {
756    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
757        write!(f, "{}", self.message())
758    }
759}
760
761// ============================================================================
762// Bot Types
763// ============================================================================
764
765/// Bot difficulty on the wire. Lowercase to match the backend's
766/// `game_players.bot_difficulty` CHECK constraint (`easy|medium|hard`).
767#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
768#[serde(rename_all = "lowercase")]
769pub enum BotDifficulty {
770    Easy,
771    Medium,
772    Hard,
773}
774
775/// One bot seat requested for a custom game.
776#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
777pub struct BotSpec {
778    pub difficulty: BotDifficulty,
779}
780
781// ============================================================================
782// Game Configuration Types
783// ============================================================================
784
785/// Random-event config for a custom (sandbox) game. Absent for FFA/Adventure.
786#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
787pub struct EventConfig {
788    /// Kinds eligible to fire (ambient or fire-now). Empty = none.
789    #[serde(default)]
790    pub enabled_kinds: Vec<AdventureEventKind>,
791    /// Ambient per-turn probability one enabled kind fires (0.0–1.0).
792    #[serde(default)]
793    pub frequency: f64,
794}
795
796/// Configuration options for starting a new game.
797///
798/// These options customize game behavior for a single game session.
799#[derive(Debug, Clone, Serialize, Deserialize)]
800pub struct GameConfig {
801    /// If true, regenerate the entire board at the start of each round.
802    /// Default is false (board persists across rounds).
803    #[serde(default)]
804    pub regenerate_board_each_round: bool,
805
806    /// Grid size (4 or 5). Determines which dice set is used.
807    /// Default is 5 (standard 5x5 Big Boggle-style).
808    #[serde(default = "default_grid_size")]
809    pub grid_size: u8,
810
811    /// Adventure level ID (1..=50). `Some` signals this session is an
812    /// Adventure Mode run; the server pins bot difficulty, grid size, and
813    /// target thresholds from the level manifest. `None` = normal session.
814    #[serde(default, skip_serializing_if = "Option::is_none")]
815    pub adventure_level: Option<u32>,
816
817    /// Score thresholds for 1/2/3-star completion of the current Adventure
818    /// level. Sent from server → client at session start so the UI can
819    /// render target chips. Only present when `adventure_level.is_some()`.
820    #[serde(default, skip_serializing_if = "Option::is_none")]
821    pub level_targets: Option<LevelTargets>,
822
823    /// Number of rounds for a custom game. `None` = server default (5).
824    /// Honored only for custom (sandbox) games; ignored for FFA.
825    #[serde(default, skip_serializing_if = "Option::is_none")]
826    pub num_rounds: Option<u8>,
827
828    /// Bot seats to add (custom games only). Empty for FFA.
829    #[serde(default, skip_serializing_if = "Vec::is_empty")]
830    pub bots: Vec<BotSpec>,
831
832    /// `Some` marks this session as a custom (unranked) sandbox game.
833    /// Mirrors `adventure_level` — both gate the same ranked-skip paths.
834    #[serde(default, skip_serializing_if = "Option::is_none")]
835    pub custom: Option<CustomMeta>,
836
837    /// Random-event config for custom games. `None` for FFA/Adventure.
838    #[serde(default, skip_serializing_if = "Option::is_none")]
839    pub events: Option<EventConfig>,
840}
841
842fn default_grid_size() -> u8 {
843    5
844}
845
846impl Default for GameConfig {
847    fn default() -> Self {
848        Self {
849            regenerate_board_each_round: false,
850            grid_size: default_grid_size(),
851            adventure_level: None,
852            level_targets: None,
853            num_rounds: None,
854            bots: Vec::new(),
855            custom: None,
856            events: None,
857        }
858    }
859}
860
861/// Marker payload for a custom (sandbox) game. Empty for now; a struct
862/// (not a bare bool) so we can carry custom metadata later without a
863/// wire break.
864#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
865pub struct CustomMeta {}
866
867/// Per-level score thresholds for Adventure Mode star awards.
868///
869/// Hitting `one_star` completes the level; `two_star` and `three_star`
870/// are progressive bonuses. Stars are awarded server-side at session end.
871#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
872pub struct LevelTargets {
873    pub one_star: i32,
874    pub two_star: i32,
875    pub three_star: i32,
876}
877
878// ============================================================================
879// Debug State Types (for diagnostics)
880// ============================================================================
881
882/// Player info in debug state response.
883#[derive(Debug, Clone, Serialize, Deserialize)]
884pub struct DebugPlayerInfo {
885    pub user_id: i64,
886    pub username: String,
887}
888
889/// WebSocket connection context in debug state response.
890#[derive(Debug, Clone, Serialize, Deserialize)]
891pub struct DebugWebsocketContext {
892    pub lobby_id: Option<String>,
893    pub game_id: Option<String>,
894    pub is_spectating: bool,
895}
896
897/// Lobby state in debug state response.
898#[derive(Debug, Clone, Serialize, Deserialize)]
899#[serde(untagged)]
900pub enum DebugLobbyState {
901    Found {
902        lobby_id: String,
903        player_in_lobby: bool,
904        lobby_player_ids: Vec<i64>,
905        active_game_id: Option<String>,
906    },
907    Error {
908        error: String,
909    },
910}
911
912/// Backend game state in debug state response.
913#[derive(Debug, Clone, Serialize, Deserialize)]
914#[serde(untagged)]
915pub enum DebugBackendGameState {
916    Found {
917        game_id: String,
918        player_in_session_players: bool,
919        spectator_in_session: bool,
920        session_player_ids: Vec<i64>,
921        session_spectator_ids: Vec<i64>,
922        lobby_id: String,
923    },
924    Error {
925        error: String,
926    },
927}
928
929/// Handler game state in debug state response.
930#[derive(Debug, Clone, Serialize, Deserialize)]
931#[serde(untagged)]
932pub enum DebugHandlerGameState {
933    Found {
934        game_id: String,
935        player_in_handler_game: bool,
936        handler_player_ids: Vec<i64>,
937        current_turn_index: usize,
938        round: u8,
939        state: String,
940    },
941    Error {
942        error: String,
943    },
944}
945
946/// Type of news notification. Mirrors the canonical values the backend
947/// stores in `news.notification_type` (validated against the
948/// `ALLOWED_NOTIFICATION_TYPES` list at the API boundary).
949///
950/// `#[serde(other)]` keeps old clients functional when the server
951/// introduces a new variant — unknown values deserialize to
952/// `Unknown` instead of erroring out. Mirrors the
953/// `AdventureEventKind::Unknown` pattern already in this crate.
954#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
955#[serde(rename_all = "snake_case")]
956pub enum NewsNotificationType {
957    Maintenance,
958    Announcement,
959    Update,
960    /// Fallback for variants the server adds after this client was built.
961    #[serde(other)]
962    Unknown,
963}
964
965impl NewsNotificationType {
966    /// Parse a wire-string into the typed enum. Unknown / unrecognized
967    /// strings map to `Unknown` so callers don't have to handle parse
968    /// errors — backend's `validate_news_payload` already rejects
969    /// unknown values at the API boundary, so this only kicks in
970    /// defensively for forward-compat.
971    #[must_use]
972    pub fn from_wire_str(s: &str) -> Self {
973        match s {
974            "maintenance" => Self::Maintenance,
975            "announcement" => Self::Announcement,
976            "update" => Self::Update,
977            _ => Self::Unknown,
978        }
979    }
980}
981
982impl From<&str> for NewsNotificationType {
983    fn from(s: &str) -> Self {
984        Self::from_wire_str(s)
985    }
986}
987
988impl From<&String> for NewsNotificationType {
989    fn from(s: &String) -> Self {
990        Self::from_wire_str(s.as_str())
991    }
992}
993
994/// A news/notification item as sent over the wire (server → client).
995///
996/// Mirrors the backend's `NewsItem` model but stripped of fields that
997/// shouldn't leave the server (`created_by` user id).
998///
999/// Used in [`ServerMessage::NewsAnnounced`](crate::ServerMessage::NewsAnnounced) for live push
1000/// and is shape-compatible with what `/api/news` returns, so the same UI code path can render
1001/// either source.
1002#[derive(Debug, Clone, serde::Deserialize, serde::Serialize, PartialEq, Eq)]
1003pub struct NewsItemPayload {
1004    pub id: String,
1005    pub title: String,
1006    pub message: String,
1007    pub notification_type: NewsNotificationType,
1008    pub created_at: chrono::DateTime<chrono::Utc>,
1009    pub expires_at: Option<chrono::DateTime<chrono::Utc>>,
1010    /// 0 = popup stays until dismissed; > 0 = auto-hide after N seconds.
1011    pub auto_hide_seconds: u32,
1012    /// When true the frontend re-shows the popup every page load even if
1013    /// the user has dismissed it (dismissal becomes session-scoped only).
1014    pub refresh_on_every_login: bool,
1015    /// Higher priority wins when multiple items are active.
1016    pub priority: i32,
1017}
1018
1019/// Build provenance for one artifact (frontend or backend). The wire contract
1020/// for the backend's `GET /api/version`, and the shape the frontend mirrors for
1021/// its own baked-in info. Every field degrades to `"unknown"` (or `dirty=false`)
1022/// rather than failing a build, so a build without git context still produces a
1023/// well-formed value.
1024#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1025pub struct BuildInfo {
1026    /// Semver from the manifest (Cargo.toml / package.json), e.g. `"0.16.0"`.
1027    pub version: String,
1028    /// Short commit hash, e.g. `"a1b2c3d"`, or `"unknown"`.
1029    pub git_sha: String,
1030    /// `git describe --tags --always --dirty`, e.g. `"v0.16.0"`,
1031    /// `"v0.16.0-3-ga1b2c3d"`, `"v0.16.0-dirty"`, or `"unknown"`.
1032    pub git_describe: String,
1033    /// Branch at build, e.g. `"master"`, or `"unknown"`.
1034    pub git_branch: String,
1035    /// True if the working tree had uncommitted changes at build.
1036    pub dirty: bool,
1037    /// RFC 3339 UTC build timestamp, e.g. `"2026-07-14T11:20:05Z"`, or `"unknown"`.
1038    pub built_at: String,
1039}
1040
1041#[cfg(test)]
1042mod tests {
1043    use super::*;
1044
1045    #[test]
1046    fn build_info_round_trips_snake_case() {
1047        let info = BuildInfo {
1048            version: "0.16.0".to_string(),
1049            git_sha: "a1b2c3d".to_string(),
1050            git_describe: "v0.16.0-2-ga1b2c3d".to_string(),
1051            git_branch: "master".to_string(),
1052            dirty: true,
1053            built_at: "2026-07-14T11:20:05Z".to_string(),
1054        };
1055        let json = serde_json::to_string(&info).unwrap();
1056        // snake_case field names on the wire.
1057        assert!(json.contains(r#""git_sha":"a1b2c3d""#));
1058        assert!(json.contains(r#""git_describe":"#));
1059        assert!(json.contains(r#""git_branch":"master""#));
1060        assert!(json.contains(r#""dirty":true"#));
1061        assert!(json.contains(r#""built_at":"#));
1062        // Round-trips back to an equal value.
1063        let back: BuildInfo = serde_json::from_str(&json).unwrap();
1064        assert_eq!(back, info);
1065    }
1066
1067    #[test]
1068    fn test_position_serialization() {
1069        let pos = Position { row: 2, col: 3 };
1070        let json = serde_json::to_string(&pos).unwrap();
1071        assert_eq!(json, r#"{"row":2,"col":3}"#);
1072    }
1073
1074    #[test]
1075    fn test_multiplier_serialization() {
1076        assert_eq!(
1077            serde_json::to_string(&Multiplier::DoubleLetter).unwrap(),
1078            r#""double_letter""#
1079        );
1080        assert_eq!(
1081            serde_json::to_string(&Multiplier::DoubleWord).unwrap(),
1082            r#""double_word""#
1083        );
1084    }
1085
1086    #[test]
1087    fn test_timer_vote_state_serialization() {
1088        let idle = TimerVoteState::Idle;
1089        let json = serde_json::to_string(&idle).unwrap();
1090        assert!(json.contains(r#""status":"idle""#));
1091
1092        let now = chrono::Utc::now();
1093        let vote = TimerVoteState::VoteInProgress {
1094            initiator_id: 123,
1095            voters: vec![456],
1096            votes_needed: 2,
1097            expires_at: now,
1098        };
1099        let json = serde_json::to_string(&vote).unwrap();
1100        assert!(json.contains(r#""status":"vote_in_progress""#));
1101        assert!(json.contains(r#""initiator_id":"123""#));
1102        assert!(json.contains(r#""expires_at""#));
1103
1104        let active = TimerVoteState::TimerActive {
1105            expires_at: now,
1106            target_player_id: 789,
1107        };
1108        let json = serde_json::to_string(&active).unwrap();
1109        assert!(json.contains(r#""status":"timer_active""#));
1110        assert!(json.contains(r#""target_player_id":"789""#));
1111
1112        let cooldown = TimerVoteState::Cooldown { expires_at: now };
1113        let json = serde_json::to_string(&cooldown).unwrap();
1114        assert!(json.contains(r#""status":"cooldown""#));
1115        assert!(json.contains(r#""expires_at""#));
1116    }
1117
1118    #[test]
1119    fn test_lobby_change_serialization() {
1120        let change = LobbyChange::DictionaryChanged {
1121            dictionary: "main".to_string(),
1122            changed_by: 123,
1123        };
1124        let json = serde_json::to_string(&change).unwrap();
1125        assert!(json.contains(r#""change_type":"dictionary_changed""#));
1126        assert!(json.contains(r#""changed_by":"123""#));
1127    }
1128
1129    #[test]
1130    fn test_error_code_message() {
1131        assert_eq!(ErrorCode::NotYourTurn.message(), "It's not your turn");
1132        assert_eq!(
1133            ErrorCode::WordNotInDictionary.message(),
1134            "Word not found in dictionary"
1135        );
1136    }
1137
1138    #[test]
1139    fn test_game_snapshot_serialization() {
1140        let player = PlayerInfo {
1141            user_id: 1,
1142            username: "Player1".to_string(),
1143            name: None,
1144            avatar_url: None,
1145            score: 10,
1146            gems: 5,
1147            team: None,
1148            is_connected: true,
1149        };
1150
1151        let spectator = SpectatorInfo {
1152            user_id: 2,
1153            username: "Spec1".to_string(),
1154            name: None,
1155            avatar_url: Some("http://avatar.url".to_string()),
1156        };
1157
1158        let snapshot = GameSnapshot {
1159            game_id: "game1".to_string(),
1160            game_type: GameType::Open,
1161            state: GameState::InProgress,
1162            grid: vec![vec![GridCell {
1163                is_hole: false,
1164                letter: 'A',
1165                value: 1,
1166                multiplier: None,
1167                has_gem: false,
1168                is_poisoned: false,
1169                is_abducted: false,
1170            }]],
1171            players: vec![player],
1172            spectators: vec![spectator],
1173            current_turn: 1,
1174            round: 1,
1175            max_rounds: 3,
1176            used_words: vec!["WORD".to_string()],
1177            timer_vote_state: TimerVoteState::default(),
1178            your_player: None,
1179            timer_expiration_time: None,
1180            custom: None,
1181            time_remaining_ms: None,
1182            your_found_words: None,
1183            dictionary: "main".to_string(),
1184        };
1185
1186        let json = serde_json::to_string(&snapshot).unwrap();
1187        assert!(json.contains(r#""game_id":"game1""#));
1188        assert!(json.contains(r#""players":[{"user_id":"1""#));
1189        assert!(json.contains(r#""spectators":[{"user_id":"2""#));
1190        assert!(json.contains(r#""current_turn":"1""#));
1191    }
1192
1193    #[test]
1194    fn test_game_config_default() {
1195        let config = GameConfig::default();
1196        assert!(!config.regenerate_board_each_round);
1197    }
1198
1199    #[test]
1200    fn test_game_config_serialization() {
1201        // Test with default value (false)
1202        let config = GameConfig {
1203            regenerate_board_each_round: false,
1204            grid_size: 5,
1205            adventure_level: None,
1206            level_targets: None,
1207            num_rounds: None,
1208            bots: Vec::new(),
1209            custom: None,
1210            events: None,
1211        };
1212        let json = serde_json::to_string(&config).unwrap();
1213        assert!(json.contains(r#""regenerate_board_each_round":false"#));
1214        assert!(json.contains(r#""grid_size":5"#));
1215        // None-valued adventure fields are skipped on the wire.
1216        assert!(
1217            !json.contains("adventure_level"),
1218            "adventure_level should be omitted when None"
1219        );
1220        assert!(
1221            !json.contains("level_targets"),
1222            "level_targets should be omitted when None"
1223        );
1224
1225        // Test with true value and 4x4 grid
1226        let config = GameConfig {
1227            regenerate_board_each_round: true,
1228            grid_size: 4,
1229            adventure_level: None,
1230            level_targets: None,
1231            num_rounds: None,
1232            bots: Vec::new(),
1233            custom: None,
1234            events: None,
1235        };
1236        let json = serde_json::to_string(&config).unwrap();
1237        assert!(json.contains(r#""regenerate_board_each_round":true"#));
1238        assert!(json.contains(r#""grid_size":4"#));
1239
1240        // Adventure fields present should serialize with their expected names.
1241        let config = GameConfig {
1242            regenerate_board_each_round: false,
1243            grid_size: 4,
1244            adventure_level: Some(7),
1245            level_targets: Some(LevelTargets {
1246                one_star: 30,
1247                two_star: 60,
1248                three_star: 90,
1249            }),
1250            num_rounds: None,
1251            bots: Vec::new(),
1252            custom: None,
1253            events: None,
1254        };
1255        let json = serde_json::to_string(&config).unwrap();
1256        assert!(json.contains(r#""adventure_level":7"#));
1257        assert!(json.contains(r#""level_targets""#));
1258        assert!(json.contains(r#""one_star":30"#));
1259        assert!(json.contains(r#""two_star":60"#));
1260        assert!(json.contains(r#""three_star":90"#));
1261    }
1262
1263    #[test]
1264    fn test_game_config_deserialization() {
1265        // Test deserializing with explicit false
1266        let json = r#"{"regenerate_board_each_round":false}"#;
1267        let config: GameConfig = serde_json::from_str(json).unwrap();
1268        assert!(!config.regenerate_board_each_round);
1269        assert_eq!(config.grid_size, 5, "grid_size should default to 5");
1270        assert!(
1271            config.adventure_level.is_none(),
1272            "adventure_level defaults to None"
1273        );
1274        assert!(
1275            config.level_targets.is_none(),
1276            "level_targets defaults to None"
1277        );
1278
1279        // Test deserializing with explicit true
1280        let json = r#"{"regenerate_board_each_round":true}"#;
1281        let config: GameConfig = serde_json::from_str(json).unwrap();
1282        assert!(config.regenerate_board_each_round);
1283
1284        // Test deserializing with missing field (should use default)
1285        let json = r"{}";
1286        let config: GameConfig = serde_json::from_str(json).unwrap();
1287        assert!(!config.regenerate_board_each_round);
1288        assert_eq!(config.grid_size, 5);
1289        assert!(config.adventure_level.is_none());
1290        assert!(config.level_targets.is_none());
1291
1292        // Test deserializing with grid_size: 4
1293        let json = r#"{"grid_size":4}"#;
1294        let config: GameConfig = serde_json::from_str(json).unwrap();
1295        assert_eq!(config.grid_size, 4);
1296        assert!(!config.regenerate_board_each_round);
1297
1298        // Adventure fields present should deserialize through.
1299        let json = r#"{
1300            "grid_size": 4,
1301            "adventure_level": 12,
1302            "level_targets": { "one_star": 50, "two_star": 75, "three_star": 100 }
1303        }"#;
1304        let config: GameConfig = serde_json::from_str(json).unwrap();
1305        assert_eq!(config.adventure_level, Some(12));
1306        assert_eq!(
1307            config.level_targets,
1308            Some(LevelTargets {
1309                one_star: 50,
1310                two_star: 75,
1311                three_star: 100
1312            })
1313        );
1314    }
1315
1316    #[test]
1317    fn test_level_targets_serde_round_trip() {
1318        // Lock in the exact wire-level field names — renaming any of
1319        // them would silently break every client that had already
1320        // cached adventure progress.
1321        let targets = LevelTargets {
1322            one_star: 100,
1323            two_star: 200,
1324            three_star: 300,
1325        };
1326        let json = serde_json::to_value(targets).expect("LevelTargets should serialize");
1327        let expected = serde_json::json!({
1328            "one_star": 100,
1329            "two_star": 200,
1330            "three_star": 300,
1331        });
1332        assert_eq!(json, expected);
1333
1334        let round_tripped: LevelTargets =
1335            serde_json::from_value(json).expect("LevelTargets should deserialize");
1336        assert_eq!(round_tripped, targets);
1337    }
1338
1339    #[test]
1340    fn test_grid_cell_is_hole_wire_compat() {
1341        // Default (non-hole) cells should omit `is_hole` on the wire —
1342        // otherwise every existing cell in every broadcast pays the
1343        // bytes and older clients see an unexpected field. Hole cells
1344        // must carry the flag.
1345        let plain = GridCell {
1346            letter: 'A',
1347            value: 1,
1348            multiplier: None,
1349            has_gem: false,
1350            is_hole: false,
1351            is_poisoned: false,
1352            is_abducted: false,
1353        };
1354        let json = serde_json::to_string(&plain).unwrap();
1355        assert!(
1356            !json.contains("is_hole"),
1357            "is_hole should be omitted when false (got: {json})"
1358        );
1359
1360        let hole = GridCell {
1361            letter: ' ',
1362            value: 0,
1363            multiplier: None,
1364            has_gem: false,
1365            is_hole: true,
1366            is_poisoned: false,
1367            is_abducted: false,
1368        };
1369        let json = serde_json::to_string(&hole).unwrap();
1370        assert!(json.contains(r#""is_hole":true"#));
1371
1372        // Missing is_hole on the wire should deserialize to false.
1373        let incoming = r#"{"letter":"B","value":3,"has_gem":false}"#;
1374        let cell: GridCell = serde_json::from_str(incoming).unwrap();
1375        assert!(!cell.is_hole, "is_hole should default to false when absent");
1376    }
1377
1378    #[test]
1379    fn test_grid_cell_is_poisoned_wire_compat() {
1380        // Default (non-poisoned) cells must omit `is_poisoned` on the
1381        // wire so every existing cell in non-adventure (or non-snaked)
1382        // broadcasts doesn't carry the field.
1383        let plain = GridCell {
1384            letter: 'A',
1385            value: 1,
1386            multiplier: None,
1387            has_gem: false,
1388            is_hole: false,
1389            is_poisoned: false,
1390            is_abducted: false,
1391        };
1392        let json = serde_json::to_string(&plain).unwrap();
1393        assert!(
1394            !json.contains("is_poisoned"),
1395            "is_poisoned should be omitted when false (got: {json})"
1396        );
1397
1398        let poisoned = GridCell {
1399            letter: 'E',
1400            value: 1,
1401            multiplier: None,
1402            has_gem: false,
1403            is_hole: false,
1404            is_poisoned: true,
1405            is_abducted: false,
1406        };
1407        let json = serde_json::to_string(&poisoned).unwrap();
1408        assert!(json.contains(r#""is_poisoned":true"#));
1409
1410        // Older client/server payloads without the field deserialize
1411        // to is_poisoned=false — wire-compat with pre-v0.9.0.
1412        let incoming = r#"{"letter":"B","value":3,"has_gem":false}"#;
1413        let cell: GridCell = serde_json::from_str(incoming).unwrap();
1414        assert!(
1415            !cell.is_poisoned,
1416            "is_poisoned should default to false when absent"
1417        );
1418    }
1419
1420    #[test]
1421    fn test_grid_cell_is_abducted_wire_compat() {
1422        // Mirrors the is_hole / is_poisoned wire-compat contract:
1423        // default-false cells omit the field; abducted cells carry it.
1424        let plain = GridCell {
1425            letter: 'A',
1426            value: 1,
1427            multiplier: None,
1428            has_gem: false,
1429            is_hole: false,
1430            is_poisoned: false,
1431            is_abducted: false,
1432        };
1433        let json = serde_json::to_string(&plain).unwrap();
1434        assert!(
1435            !json.contains("is_abducted"),
1436            "is_abducted should be omitted when false (got: {json})"
1437        );
1438
1439        let abducted = GridCell {
1440            letter: 'T',
1441            value: 1,
1442            multiplier: None,
1443            has_gem: false,
1444            is_hole: false,
1445            is_poisoned: false,
1446            is_abducted: true,
1447        };
1448        let json = serde_json::to_string(&abducted).unwrap();
1449        assert!(json.contains(r#""is_abducted":true"#));
1450
1451        // Pre-v0.9.0 payloads deserialize cleanly with is_abducted=false.
1452        let incoming = r#"{"letter":"B","value":3,"has_gem":false}"#;
1453        let cell: GridCell = serde_json::from_str(incoming).unwrap();
1454        assert!(
1455            !cell.is_abducted,
1456            "is_abducted should default to false when absent"
1457        );
1458    }
1459
1460    #[test]
1461    fn test_news_notification_type_serde() {
1462        // Known variants round-trip through snake_case.
1463        let json = serde_json::to_string(&NewsNotificationType::Maintenance).unwrap();
1464        assert_eq!(json, r#""maintenance""#);
1465        assert_eq!(
1466            serde_json::from_str::<NewsNotificationType>(r#""announcement""#).unwrap(),
1467            NewsNotificationType::Announcement
1468        );
1469
1470        // #[serde(other)] catches future server-side variants — load-
1471        // bearing for forward compatibility with older clients.
1472        assert_eq!(
1473            serde_json::from_str::<NewsNotificationType>(r#""patch_notes""#).unwrap(),
1474            NewsNotificationType::Unknown
1475        );
1476
1477        // from_wire_str / From<&str> agree with serde.
1478        assert_eq!(
1479            NewsNotificationType::from_wire_str("maintenance"),
1480            NewsNotificationType::Maintenance
1481        );
1482        assert_eq!(
1483            NewsNotificationType::from("update"),
1484            NewsNotificationType::Update
1485        );
1486        assert_eq!(
1487            NewsNotificationType::from_wire_str("unknown_future_type"),
1488            NewsNotificationType::Unknown
1489        );
1490    }
1491
1492    #[test]
1493    fn bot_spec_round_trips_lowercase() {
1494        let spec = BotSpec {
1495            difficulty: BotDifficulty::Hard,
1496        };
1497        let json = serde_json::to_string(&spec).unwrap();
1498        assert_eq!(json, r#"{"difficulty":"hard"}"#);
1499        let back: BotSpec = serde_json::from_str(&json).unwrap();
1500        assert_eq!(back.difficulty, BotDifficulty::Hard);
1501    }
1502
1503    #[test]
1504    fn test_adventure_event_kind_serde() {
1505        // Known kinds round-trip through snake_case names.
1506        let json = serde_json::to_string(&AdventureEventKind::Bomb).unwrap();
1507        assert_eq!(json, r#""bomb""#);
1508        assert_eq!(
1509            serde_json::from_str::<AdventureEventKind>(r#""snake""#).unwrap(),
1510            AdventureEventKind::Snake
1511        );
1512        assert_eq!(
1513            serde_json::from_str::<AdventureEventKind>(r#""ufo""#).unwrap(),
1514            AdventureEventKind::Ufo
1515        );
1516
1517        // #[serde(other)] catches any future kind an older client
1518        // doesn't recognize — load-bearing for forward compatibility.
1519        assert_eq!(
1520            serde_json::from_str::<AdventureEventKind>(r#""earthquake""#).unwrap(),
1521            AdventureEventKind::Unknown
1522        );
1523    }
1524
1525    #[test]
1526    fn default_gameconfig_wire_unchanged() {
1527        let json = serde_json::to_string(&GameConfig::default()).unwrap();
1528        assert!(json.contains(r#""grid_size":5"#));
1529        assert!(!json.contains("num_rounds")); // skipped when None
1530        assert!(!json.contains(r#""bots""#) || json.contains(r#""bots":[]"#));
1531        assert!(!json.contains("custom")); // skipped when None
1532    }
1533
1534    #[test]
1535    fn sandbox_gameconfig_round_trips() {
1536        let cfg = GameConfig {
1537            num_rounds: Some(7),
1538            bots: vec![BotSpec {
1539                difficulty: BotDifficulty::Easy,
1540            }],
1541            custom: Some(CustomMeta {}),
1542            grid_size: 6,
1543            ..GameConfig::default()
1544        };
1545        let json = serde_json::to_string(&cfg).unwrap();
1546        let back: GameConfig = serde_json::from_str(&json).unwrap();
1547        assert_eq!(back.num_rounds, Some(7));
1548        assert_eq!(back.bots.len(), 1);
1549        assert!(back.custom.is_some());
1550        assert_eq!(back.grid_size, 6);
1551    }
1552
1553    #[test]
1554    fn legacy_gameconfig_json_still_parses() {
1555        let cfg: GameConfig =
1556            serde_json::from_str(r#"{"regenerate_board_each_round":true,"grid_size":4}"#).unwrap();
1557        assert!(cfg.regenerate_board_each_round);
1558        assert!(cfg.bots.is_empty());
1559        assert!(cfg.num_rounds.is_none());
1560        assert!(cfg.custom.is_none());
1561    }
1562
1563    #[test]
1564    fn event_config_round_trips() {
1565        let cfg = EventConfig {
1566            enabled_kinds: vec![AdventureEventKind::Bomb, AdventureEventKind::Ufo],
1567            frequency: 0.5,
1568        };
1569        let json = serde_json::to_string(&cfg).unwrap();
1570        let back: EventConfig = serde_json::from_str(&json).unwrap();
1571        assert_eq!(back.enabled_kinds.len(), 2);
1572        assert!((back.frequency - 0.5).abs() < 1e-9);
1573    }
1574
1575    #[test]
1576    fn gameconfig_without_events_is_back_compat() {
1577        let json = serde_json::to_string(&GameConfig::default()).unwrap();
1578        assert!(!json.contains("events"));
1579        let back: GameConfig = serde_json::from_str(&json).unwrap();
1580        assert!(back.events.is_none());
1581    }
1582
1583    #[test]
1584    fn lobby_game_info_game_type_round_trips() {
1585        // Construct a LobbyGameInfo with game_type: Sandbox, serialize,
1586        // assert the wire string, and deserialize back.
1587        let info = LobbyGameInfo {
1588            game_id: "game-42".to_string(),
1589            game_type: GameType::Sandbox,
1590            current_round: 2,
1591            max_rounds: 5,
1592            players: vec![],
1593        };
1594        let json = serde_json::to_string(&info).unwrap();
1595        assert!(
1596            json.contains(r#""game_type":"sandbox""#),
1597            r#"expected "game_type":"sandbox" in JSON, got: {json}"#
1598        );
1599        let back: LobbyGameInfo = serde_json::from_str(&json).unwrap();
1600        assert_eq!(back.game_type, GameType::Sandbox);
1601        assert_eq!(back.game_id, "game-42");
1602    }
1603
1604    #[test]
1605    fn game_type_sandbox_serializes_snake_case() {
1606        let gt = GameType::Sandbox;
1607        let json = serde_json::to_string(&gt).unwrap();
1608        assert_eq!(json, "\"sandbox\"");
1609        let back: GameType = serde_json::from_str("\"sandbox\"").unwrap();
1610        assert_eq!(back, GameType::Sandbox);
1611        assert_eq!(gt.to_string(), "sandbox");
1612    }
1613
1614    #[test]
1615    fn game_type_daily_serde_roundtrip() {
1616        let j = serde_json::to_string(&GameType::Daily).unwrap();
1617        assert_eq!(j, "\"daily\"");
1618        let back: GameType = serde_json::from_str("\"daily\"").unwrap();
1619        assert!(matches!(back, GameType::Daily));
1620        assert_eq!(GameType::Daily.to_string(), "daily");
1621    }
1622
1623    #[test]
1624    fn game_type_unknown_is_deserialize_fallback() {
1625        // Known strings still map correctly.
1626        assert_eq!(
1627            serde_json::from_str::<GameType>("\"open\"").unwrap(),
1628            GameType::Open
1629        );
1630        assert_eq!(
1631            serde_json::from_str::<GameType>("\"sandbox\"").unwrap(),
1632            GameType::Sandbox
1633        );
1634        // An unknown/future string degrades to Unknown instead of erroring.
1635        assert_eq!(
1636            serde_json::from_str::<GameType>("\"some_future_mode\"").unwrap(),
1637            GameType::Unknown
1638        );
1639    }
1640
1641    #[test]
1642    fn game_snapshot_custom_field_round_trips() {
1643        // Build a minimal GameSnapshot with custom = Some(CustomMeta {})
1644        let player = PlayerInfo {
1645            user_id: 1,
1646            username: "Player1".to_string(),
1647            name: None,
1648            avatar_url: None,
1649            score: 0,
1650            gems: 0,
1651            team: None,
1652            is_connected: true,
1653        };
1654        let base = GameSnapshot {
1655            game_id: "snap1".to_string(),
1656            game_type: GameType::Sandbox,
1657            state: GameState::InProgress,
1658            grid: vec![],
1659            players: vec![player],
1660            spectators: vec![],
1661            current_turn: 1,
1662            round: 1,
1663            max_rounds: 3,
1664            used_words: vec![],
1665            timer_vote_state: TimerVoteState::default(),
1666            your_player: None,
1667            timer_expiration_time: None,
1668            custom: Some(CustomMeta {}),
1669            time_remaining_ms: None,
1670            your_found_words: None,
1671            dictionary: "main".to_string(),
1672        };
1673
1674        // Serialized JSON must contain "custom"
1675        let json = serde_json::to_string(&base).unwrap();
1676        assert!(
1677            json.contains("\"custom\""),
1678            "expected \"custom\" in JSON, got: {json}"
1679        );
1680
1681        // Must round-trip to Some
1682        let back: GameSnapshot = serde_json::from_str(&json).unwrap();
1683        assert!(back.custom.is_some());
1684
1685        // None must be omitted from JSON
1686        let no_custom = GameSnapshot {
1687            custom: None,
1688            ..base
1689        };
1690        let json_none = serde_json::to_string(&no_custom).unwrap();
1691        assert!(
1692            !json_none.contains("\"custom\""),
1693            "expected no \"custom\" in JSON with None, got: {json_none}"
1694        );
1695        let back_none: GameSnapshot = serde_json::from_str(&json_none).unwrap();
1696        assert!(back_none.custom.is_none());
1697    }
1698
1699    #[test]
1700    fn game_snapshot_time_remaining_omitted_when_none_roundtrips_when_some() {
1701        let base = GameSnapshot {
1702            game_id: "g".to_string(),
1703            game_type: GameType::Daily,
1704            state: GameState::InProgress,
1705            grid: vec![],
1706            players: vec![],
1707            spectators: vec![],
1708            current_turn: 1,
1709            round: 1,
1710            max_rounds: 1,
1711            used_words: vec![],
1712            timer_vote_state: TimerVoteState::default(),
1713            your_player: None,
1714            timer_expiration_time: None,
1715            custom: None,
1716            time_remaining_ms: None,
1717            your_found_words: None,
1718            dictionary: "main".to_string(),
1719        };
1720        // Omitted when None.
1721        let json_none = serde_json::to_string(&base).unwrap();
1722        assert!(!json_none.contains("time_remaining_ms"));
1723        // Present + round-trips when Some.
1724        let with = GameSnapshot {
1725            time_remaining_ms: Some(45_000),
1726            ..base
1727        };
1728        let json = serde_json::to_string(&with).unwrap();
1729        assert!(json.contains("\"time_remaining_ms\":45000"));
1730        let back: GameSnapshot = serde_json::from_str(&json).unwrap();
1731        assert_eq!(back.time_remaining_ms, Some(45_000));
1732    }
1733
1734    #[test]
1735    fn game_type_runebox_round_trips_as_snake_case() {
1736        let json = serde_json::to_string(&GameType::RuneBox).unwrap();
1737        assert_eq!(json, "\"rune_box\"");
1738        let back: GameType = serde_json::from_str(&json).unwrap();
1739        assert_eq!(back, GameType::RuneBox);
1740        assert_eq!(GameType::RuneBox.to_string(), "rune_box");
1741    }
1742
1743    #[test]
1744    fn unknown_game_type_still_degrades_rather_than_failing() {
1745        // Adding a variant must not break the forward-compat fallback that lets
1746        // an older client survive a newer server.
1747        let back: GameType = serde_json::from_str("\"some_future_mode\"").unwrap();
1748        assert_eq!(back, GameType::Unknown);
1749    }
1750
1751    #[test]
1752    fn game_snapshot_found_words_omitted_when_none_roundtrips_when_some() {
1753        let base = GameSnapshot {
1754            game_id: "g".to_string(),
1755            game_type: GameType::RuneBox,
1756            state: GameState::InProgress,
1757            grid: vec![],
1758            players: vec![],
1759            spectators: vec![],
1760            current_turn: 1,
1761            round: 1,
1762            max_rounds: 1,
1763            used_words: vec![],
1764            timer_vote_state: TimerVoteState::default(),
1765            your_player: None,
1766            timer_expiration_time: None,
1767            custom: None,
1768            time_remaining_ms: None,
1769            your_found_words: None,
1770            dictionary: "main".to_string(),
1771        };
1772        // Every non-RuneBox mode must serialize exactly as it did before.
1773        let json_none = serde_json::to_string(&base).unwrap();
1774        assert!(!json_none.contains("your_found_words"));
1775
1776        let with = GameSnapshot {
1777            your_found_words: Some(vec!["RUNES".to_string()]),
1778            ..base
1779        };
1780        let json = serde_json::to_string(&with).unwrap();
1781        assert!(json.contains("\"your_found_words\":[\"RUNES\"]"));
1782        let back: GameSnapshot = serde_json::from_str(&json).unwrap();
1783        assert_eq!(back.your_found_words, Some(vec!["RUNES".to_string()]));
1784    }
1785
1786    /// Minimal snapshot for the `game_type` tests below.
1787    fn snapshot_of(game_type: GameType) -> GameSnapshot {
1788        GameSnapshot {
1789            game_id: "g".to_string(),
1790            game_type,
1791            state: GameState::InProgress,
1792            grid: vec![],
1793            players: vec![],
1794            spectators: vec![],
1795            current_turn: 1,
1796            round: 1,
1797            max_rounds: 1,
1798            used_words: vec![],
1799            timer_vote_state: TimerVoteState::default(),
1800            your_player: None,
1801            timer_expiration_time: None,
1802            custom: None,
1803            time_remaining_ms: None,
1804            your_found_words: None,
1805            dictionary: "main".to_string(),
1806        }
1807    }
1808
1809    /// The whole point of the field: a snapshot says what mode it is, on the
1810    /// wire, without the client inferring it from anything else.
1811    #[test]
1812    fn game_snapshot_carries_its_game_type_on_the_wire() {
1813        let json = serde_json::to_string(&snapshot_of(GameType::RuneBox)).unwrap();
1814        assert!(
1815            json.contains("\"game_type\":\"rune_box\""),
1816            "expected game_type on the snapshot, got: {json}"
1817        );
1818        let back: GameSnapshot = serde_json::from_str(&json).unwrap();
1819        assert_eq!(back.game_type, GameType::RuneBox);
1820    }
1821
1822    /// `game_type` is NOT `skip_serializing_if` — unlike `custom` /
1823    /// `time_remaining_ms` / `your_found_words`, it must be present for every
1824    /// mode. A client that has to ask "is this field missing, or is this an old
1825    /// server?" is back to inferring, which is what the field exists to end.
1826    #[test]
1827    fn game_type_is_emitted_for_every_mode_never_omitted() {
1828        for (game_type, tag) in [
1829            (GameType::Open, "open"),
1830            (GameType::Sandbox, "sandbox"),
1831            (GameType::Adventure, "adventure"),
1832            (GameType::Daily, "daily"),
1833            (GameType::RuneBox, "rune_box"),
1834        ] {
1835            let json = serde_json::to_string(&snapshot_of(game_type)).unwrap();
1836            assert!(
1837                json.contains(&format!("\"game_type\":\"{tag}\"")),
1838                "{game_type:?} must serialize its game_type, got: {json}"
1839            );
1840        }
1841    }
1842
1843    /// A snapshot written before this field existed must still decode — as
1844    /// `Unknown`, not as a plausible-looking `Open`. Guards the `#[serde(default)]`
1845    /// AND the `Default` impl: without either, this fails.
1846    #[test]
1847    fn snapshot_without_game_type_decodes_as_unknown() {
1848        // `timer_vote_state` is spliced in rather than hand-modelled: this test
1849        // is about the ABSENCE of game_type, and a hand-written literal for an
1850        // unrelated type would make it fail for the wrong reason.
1851        let votes = serde_json::to_string(&TimerVoteState::default()).unwrap();
1852        let legacy = format!(
1853            r#"{{
1854            "game_id": "g",
1855            "state": "in_progress",
1856            "grid": [],
1857            "players": [],
1858            "spectators": [],
1859            "current_turn": "1",
1860            "round": 1,
1861            "max_rounds": 1,
1862            "used_words": [],
1863            "timer_vote_state": {votes}
1864        }}"#
1865        );
1866        let back: GameSnapshot =
1867            serde_json::from_str(&legacy).expect("a pre-game_type snapshot must still decode");
1868        assert_eq!(back.game_type, GameType::Unknown);
1869    }
1870
1871    /// The property that makes ADDING a field to a snapshot safe, and so the
1872    /// direct counterpart to the test above.
1873    ///
1874    /// A snapshot carrying a field the reader has never heard of must decode,
1875    /// ignoring it. That is what lets a v0.18.0 server send `game_type` to a
1876    /// v0.17.0 reader — and what will let the next field be added the same way.
1877    /// It holds because no protocol type sets `deny_unknown_fields`; this test
1878    /// is what stops someone adding it.
1879    #[test]
1880    fn snapshot_ignores_fields_it_does_not_know() {
1881        let mut json = serde_json::to_string(&snapshot_of(GameType::Open)).unwrap();
1882        // Splice in a field from a hypothetical future version.
1883        json = json.replace('{', r#"{"a_field_from_the_future":[1,2,3],"#);
1884
1885        let back: GameSnapshot =
1886            serde_json::from_str(&json).expect("an unknown field must be ignored, not rejected");
1887        assert_eq!(back.game_type, GameType::Open);
1888    }
1889
1890    #[test]
1891    fn player_name_shows_the_runecast_nickname_unless_austere() {
1892        let name = PlayerName::new("Ada", Some("Rune Queen".to_string()));
1893        assert_eq!(name.shown(false), "Rune Queen");
1894        assert_eq!(name.shown(true), "Ada");
1895    }
1896
1897    #[test]
1898    fn player_name_without_a_runecast_nickname_shows_discord_either_way() {
1899        let name = PlayerName::new("Ada", None);
1900        assert_eq!(name.shown(false), "Ada");
1901        assert_eq!(name.shown(true), "Ada");
1902    }
1903
1904    #[test]
1905    fn player_name_with_an_empty_runecast_nickname_shows_discord() {
1906        assert_eq!(
1907            PlayerName::new("Ada", Some(String::new())).shown(false),
1908            "Ada"
1909        );
1910    }
1911
1912    #[test]
1913    fn player_name_omits_an_absent_runecast_nickname_on_the_wire() {
1914        let json = serde_json::to_string(&PlayerName::new("Ada", None)).unwrap();
1915        assert_eq!(json, r#"{"discord":"Ada"}"#);
1916        let json = serde_json::to_string(&PlayerName::new("Ada", Some("Q".into()))).unwrap();
1917        assert_eq!(json, r#"{"discord":"Ada","runecast":"Q"}"#);
1918        let back: PlayerName = serde_json::from_str(r#"{"discord":"Ada"}"#).unwrap();
1919        assert_eq!(back, PlayerName::new("Ada", None));
1920    }
1921
1922    #[test]
1923    fn a_player_struct_carries_its_name_beside_username() {
1924        let p = SpectatorInfo {
1925            user_id: 1_098_406_821_124_911_175,
1926            username: "ada_l".into(),
1927            name: Some(PlayerName::new("Ada", Some("Rune Queen".into()))),
1928            avatar_url: None,
1929        };
1930        let json = serde_json::to_string(&p).unwrap();
1931        assert!(json.contains(r#""username":"ada_l""#), "{json}");
1932        assert!(
1933            json.contains(r#""name":{"discord":"Ada","runecast":"Rune Queen"}"#),
1934            "{json}"
1935        );
1936    }
1937
1938    #[test]
1939    fn a_player_without_a_resolved_name_has_no_name_key() {
1940        let p = ScoreInfo {
1941            user_id: 1,
1942            username: "ada_l".into(),
1943            name: None,
1944            score: 3,
1945        };
1946        let json = serde_json::to_string(&p).unwrap();
1947        assert!(!json.contains("\"name\""), "{json}");
1948    }
1949
1950    /// A server older than 0.20 sends no `name`; a 0.20 client still parses it.
1951    #[test]
1952    fn json_from_an_older_server_parses_with_no_name() {
1953        let old = r#"{"user_id":"1","username":"ada_l","score":3}"#;
1954        let p: ScoreInfo = serde_json::from_str(old).unwrap();
1955        assert_eq!(p.username, "ada_l");
1956        assert!(p.name.is_none());
1957    }
1958
1959    #[test]
1960    fn opt_in_state_round_trips_with_string_ids() {
1961        let s = RematchCountdownState::OptIn {
1962            ready: vec![1],
1963            eligible: vec![1, 2],
1964            needed: 2,
1965            game_type: GameType::Open,
1966        };
1967        let json = serde_json::to_string(&s).unwrap();
1968        assert!(json.contains(r#""status":"opt_in""#), "{json}");
1969        assert!(json.contains(r#""ready":["1"]"#), "{json}");
1970        assert!(json.contains(r#""eligible":["1","2"]"#), "{json}");
1971        assert!(json.contains(r#""needed":2"#), "{json}");
1972        let back: RematchCountdownState = serde_json::from_str(&json).unwrap();
1973        assert!(
1974            matches!(&back, RematchCountdownState::OptIn { ready, eligible, needed: 2, game_type: GameType::Open }
1975                if ready == &[1] && eligible == &[1, 2]),
1976            "{back:?}"
1977        );
1978    }
1979
1980    #[test]
1981    fn auto_rematch_changed_round_trips() {
1982        let c = LobbyChange::AutoRematchChanged {
1983            enabled: false,
1984            changed_by: 42,
1985        };
1986        let json = serde_json::to_string(&c).unwrap();
1987        assert_eq!(
1988            json,
1989            r#"{"change_type":"auto_rematch_changed","enabled":false,"changed_by":"42"}"#
1990        );
1991        let back: LobbyChange = serde_json::from_str(&json).unwrap();
1992        assert!(matches!(
1993            back,
1994            LobbyChange::AutoRematchChanged {
1995                enabled: false,
1996                changed_by: 42
1997            }
1998        ));
1999    }
2000
2001    #[test]
2002    fn dictionary_changed_round_trips() {
2003        let c = LobbyChange::DictionaryChanged {
2004            dictionary: "urban".to_string(),
2005            changed_by: 42,
2006        };
2007        let json = serde_json::to_string(&c).unwrap();
2008        assert_eq!(
2009            json,
2010            r#"{"change_type":"dictionary_changed","dictionary":"urban","changed_by":"42"}"#
2011        );
2012        let back: LobbyChange = serde_json::from_str(&json).unwrap();
2013        assert!(matches!(
2014            back,
2015            LobbyChange::DictionaryChanged { dictionary, changed_by: 42 } if dictionary == "urban"
2016        ));
2017    }
2018
2019    #[test]
2020    fn default_dictionary_is_main() {
2021        assert_eq!(MAIN_DICTIONARY, "main");
2022        assert_eq!(default_dictionary(), "main");
2023    }
2024
2025    #[test]
2026    fn a_game_snapshot_without_dictionary_reads_as_main() {
2027        let json = r#"{"game_id":"g","state":"in_progress","grid":[],"players":[],"spectators":[],"current_turn":"1","round":1,"max_rounds":3,"used_words":[],"timer_vote_state":{"status":"idle"}}"#;
2028        let snap: GameSnapshot = serde_json::from_str(json).unwrap();
2029        assert_eq!(snap.dictionary, "main");
2030        let out = serde_json::to_string(&snap).unwrap();
2031        assert!(out.contains(r#""dictionary":"main""#), "{out}");
2032    }
2033
2034    #[test]
2035    fn lobby_delta_only_carries_the_two_live_changes() {
2036        // `player_joined` was a LobbyChange once; the server sends the separate
2037        // top-level `player_joined` message instead, so it must not parse here.
2038        let gone = r#"{"type":"lobby_delta","changes":[{"change_type":"player_joined","player":{"user_id":"1","username":"x"}}]}"#;
2039        assert!(serde_json::from_str::<crate::ServerMessage>(gone).is_err());
2040
2041        let live = r#"{"type":"lobby_delta","changes":[{"change_type":"auto_rematch_changed","enabled":true,"changed_by":"7"}]}"#;
2042        let crate::ServerMessage::LobbyDelta { changes } =
2043            serde_json::from_str::<crate::ServerMessage>(live).unwrap()
2044        else {
2045            panic!("expected LobbyDelta");
2046        };
2047        assert!(matches!(
2048            changes.as_slice(),
2049            [LobbyChange::AutoRematchChanged {
2050                enabled: true,
2051                changed_by: 7
2052            }]
2053        ));
2054    }
2055}