1use serde::{Deserialize, Serialize};
7
8#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
14#[serde(rename_all = "snake_case")]
15pub enum TurnPassReason {
16 Voluntary,
18 Timer,
20 Disconnected,
22 Left,
24}
25
26#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
28#[serde(rename_all = "snake_case")]
29pub enum ConnectKind {
30 Fresh,
32 Reconnect,
34 TakeOver,
36}
37
38#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
40pub struct ConnectParams {
41 #[serde(default, skip_serializing_if = "Option::is_none")]
43 pub tab: Option<String>,
44 #[serde(default, skip_serializing_if = "Option::is_none")]
46 pub kind: Option<ConnectKind>,
47}
48
49#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
51pub struct ModeCap {
52 pub game_type: GameType,
54 pub max_players: u8,
56}
57
58#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
60pub struct Position {
61 pub row: usize,
62 pub col: usize,
63}
64
65#[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#[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 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
89 pub is_hole: bool,
90 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
97 pub is_poisoned: bool,
98 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
104 pub is_abducted: bool,
105}
106
107pub type Grid = Vec<Vec<GridCell>>;
109
110#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
117#[serde(rename_all = "snake_case")]
118pub enum AdventureEventKind {
119 Bomb,
121 Snake,
123 Ufo,
125 #[serde(other)]
128 Unknown,
129}
130
131#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
137#[serde(rename_all = "snake_case")]
138pub enum LobbyType {
139 Channel,
141 Custom,
143}
144
145#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
150#[serde(rename_all = "snake_case")]
151pub enum GameType {
152 Open,
154 TwoVTwo,
156 Adventure,
158 Sandbox,
160 Daily,
162 RuneBox,
166 #[serde(other)]
168 Unknown,
169}
170
171impl 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
213pub struct PlayerName {
214 pub discord: String,
218 #[serde(default, skip_serializing_if = "Option::is_none")]
220 pub runecast: Option<String>,
221}
222
223impl PlayerName {
224 #[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 #[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#[serde_with::serde_as]
245#[derive(Debug, Clone, Serialize, Deserialize)]
246pub struct LobbyPlayerInfo {
247 #[serde_as(as = "serde_with::DisplayFromStr")]
249 pub user_id: i64,
250 pub username: String,
253 #[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 #[serde(skip_serializing_if = "Option::is_none")]
261 pub banner_url: Option<String>,
262 #[serde(skip_serializing_if = "Option::is_none")]
264 pub accent_color: Option<i32>,
265 #[serde(skip_serializing_if = "Option::is_none")]
267 pub current_game_pool: Option<GameType>,
268 pub active_game_id: Option<String>,
270 pub spectate_game_id: Option<String>,
272}
273
274#[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#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
287#[serde(rename_all = "snake_case")]
288pub enum GameState {
289 Idle,
291 Queueing,
293 Starting,
295 InProgress,
297 Finished,
299 Cancelled,
301}
302
303#[serde_with::serde_as]
309#[derive(Debug, Clone, Serialize, Deserialize)]
310pub struct PlayerInfo {
311 #[serde_as(as = "serde_with::DisplayFromStr")]
313 pub user_id: i64,
314 pub username: String,
317 #[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 #[serde(default)]
326 pub gems: i32,
327 #[serde(skip_serializing_if = "Option::is_none")]
329 pub team: Option<i32>,
330 #[serde(default = "default_true")]
332 pub is_connected: bool,
333}
334
335fn default_true() -> bool {
336 true
337}
338
339pub const MAIN_DICTIONARY: &str = "main";
341
342#[must_use]
345pub fn default_dictionary() -> String {
346 MAIN_DICTIONARY.to_string()
347}
348
349#[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 pub username: String,
358 #[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#[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 pub username: String,
381 #[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#[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 pub username: String,
398 #[serde(default, skip_serializing_if = "Option::is_none")]
401 pub name: Option<PlayerName>,
402 pub score: i32,
403}
404
405#[serde_with::serde_as]
416#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
417pub struct RuneBoxStanding {
418 #[serde_as(as = "serde_with::DisplayFromStr")]
421 pub player_id: i64,
422 pub username: String,
425 #[serde(default, skip_serializing_if = "Option::is_none")]
428 pub name: Option<PlayerName>,
429 pub round_wins: u8,
436 pub total_score: i32,
438 pub eliminated: bool,
440}
441
442#[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 pub username: String,
451 #[serde(default, skip_serializing_if = "Option::is_none")]
454 pub name: Option<PlayerName>,
455 pub score: i32,
456}
457
458#[derive(Debug, Clone, Serialize, Deserialize)]
460pub struct LobbyGameInfo {
461 pub game_id: String,
462 pub game_type: GameType,
465 pub current_round: i32,
466 pub max_rounds: i32,
467 pub players: Vec<LobbyGamePlayerInfo>,
468}
469
470#[serde_with::serde_as]
476#[derive(Debug, Clone, Serialize, Deserialize)]
477pub struct GameSnapshot {
478 pub game_id: String,
479 #[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 #[serde(skip_serializing_if = "Option::is_none")]
504 pub your_player: Option<PlayerInfo>,
505 #[serde(skip_serializing_if = "Option::is_none")]
507 pub timer_expiration_time: Option<chrono::DateTime<chrono::Utc>>,
508 #[serde(default, skip_serializing_if = "Option::is_none")]
511 pub custom: Option<CustomMeta>,
512 #[serde(default, skip_serializing_if = "Option::is_none")]
516 pub time_remaining_ms: Option<u64>,
517 #[serde(default, skip_serializing_if = "Option::is_none")]
525 pub your_found_words: Option<Vec<String>>,
526 #[serde(default = "default_dictionary")]
530 pub dictionary: String,
531}
532
533#[serde_with::serde_as]
542#[derive(Debug, Clone, Serialize, Deserialize, Default)]
543#[serde(tag = "status", rename_all = "snake_case")]
544pub enum TimerVoteState {
545 #[default]
547 Idle,
548
549 VoteInProgress {
551 #[serde_as(as = "serde_with::DisplayFromStr")]
553 initiator_id: i64,
554 #[serde_as(as = "Vec<serde_with::DisplayFromStr>")]
556 voters: Vec<i64>,
557 votes_needed: u32,
559 expires_at: chrono::DateTime<chrono::Utc>,
561 },
562
563 TimerActive {
565 expires_at: chrono::DateTime<chrono::Utc>,
567 #[serde_as(as = "serde_with::DisplayFromStr")]
569 target_player_id: i64,
570 },
571
572 Cooldown {
574 expires_at: chrono::DateTime<chrono::Utc>,
576 },
577
578 Disabled,
580}
581
582#[serde_with::serde_as]
591#[derive(Debug, Clone, Serialize, Deserialize, Default)]
592#[serde(tag = "status", rename_all = "snake_case")]
593pub enum RematchCountdownState {
594 #[default]
596 Idle,
597
598 Active {
600 expires_at: chrono::DateTime<chrono::Utc>,
602 seconds_remaining: u32,
604 #[serde_as(as = "Vec<serde_with::DisplayFromStr>")]
606 player_ids: Vec<i64>,
607 game_type: GameType,
609 },
610
611 OptIn {
616 #[serde_as(as = "Vec<serde_with::DisplayFromStr>")]
618 ready: Vec<i64>,
619 #[serde_as(as = "Vec<serde_with::DisplayFromStr>")]
621 eligible: Vec<i64>,
622 needed: u8,
624 game_type: GameType,
626 },
627
628 Starting {
630 #[serde(skip_serializing_if = "Option::is_none")]
632 #[serde_as(as = "Option<serde_with::DisplayFromStr>")]
633 triggered_by: Option<i64>,
634 },
635}
636
637#[serde_with::serde_as]
643#[derive(Debug, Clone, Serialize, Deserialize)]
644#[serde(tag = "change_type", rename_all = "snake_case")]
645pub enum LobbyChange {
646 AutoRematchChanged {
648 enabled: bool,
649 #[serde_as(as = "serde_with::DisplayFromStr")]
650 changed_by: i64,
651 },
652
653 DictionaryChanged {
655 dictionary: String,
656 #[serde_as(as = "serde_with::DisplayFromStr")]
657 changed_by: i64,
658 },
659}
660
661#[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#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
682#[serde(rename_all = "snake_case")]
683pub enum ErrorCode {
684 LobbyNotFound,
686 LobbyFull,
687 NotInLobby,
688 AlreadyInLobby,
689
690 GameNotFound,
692 GameInProgress,
693 GameNotActive,
694 NotInGame,
695 AlreadyInGame,
696
697 NotYourTurn,
699 InvalidAction,
700
701 InvalidPath,
703 PathTooShort,
704 WordNotInDictionary,
705 WordAlreadyUsed,
706
707 NotHost,
709 NotEnoughPlayers,
710 TooManyPlayers,
711 NotAuthorized,
715
716 InsufficientGems,
718
719 InvalidRequest,
721 InternalError,
722}
723
724impl ErrorCode {
725 #[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#[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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
777pub struct BotSpec {
778 pub difficulty: BotDifficulty,
779}
780
781#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
787pub struct EventConfig {
788 #[serde(default)]
790 pub enabled_kinds: Vec<AdventureEventKind>,
791 #[serde(default)]
793 pub frequency: f64,
794}
795
796#[derive(Debug, Clone, Serialize, Deserialize)]
800pub struct GameConfig {
801 #[serde(default)]
804 pub regenerate_board_each_round: bool,
805
806 #[serde(default = "default_grid_size")]
809 pub grid_size: u8,
810
811 #[serde(default, skip_serializing_if = "Option::is_none")]
815 pub adventure_level: Option<u32>,
816
817 #[serde(default, skip_serializing_if = "Option::is_none")]
821 pub level_targets: Option<LevelTargets>,
822
823 #[serde(default, skip_serializing_if = "Option::is_none")]
826 pub num_rounds: Option<u8>,
827
828 #[serde(default, skip_serializing_if = "Vec::is_empty")]
830 pub bots: Vec<BotSpec>,
831
832 #[serde(default, skip_serializing_if = "Option::is_none")]
835 pub custom: Option<CustomMeta>,
836
837 #[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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
865pub struct CustomMeta {}
866
867#[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#[derive(Debug, Clone, Serialize, Deserialize)]
884pub struct DebugPlayerInfo {
885 pub user_id: i64,
886 pub username: String,
887}
888
889#[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#[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#[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#[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#[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 #[serde(other)]
962 Unknown,
963}
964
965impl NewsNotificationType {
966 #[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#[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 pub auto_hide_seconds: u32,
1012 pub refresh_on_every_login: bool,
1015 pub priority: i32,
1017}
1018
1019#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1025pub struct BuildInfo {
1026 pub version: String,
1028 pub git_sha: String,
1030 pub git_describe: String,
1033 pub git_branch: String,
1035 pub dirty: bool,
1037 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 assert_eq!(
1473 serde_json::from_str::<NewsNotificationType>(r#""patch_notes""#).unwrap(),
1474 NewsNotificationType::Unknown
1475 );
1476
1477 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 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 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")); assert!(!json.contains(r#""bots""#) || json.contains(r#""bots":[]"#));
1531 assert!(!json.contains("custom")); }
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 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(>).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 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 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 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 let json = serde_json::to_string(&base).unwrap();
1676 assert!(
1677 json.contains("\"custom\""),
1678 "expected \"custom\" in JSON, got: {json}"
1679 );
1680
1681 let back: GameSnapshot = serde_json::from_str(&json).unwrap();
1683 assert!(back.custom.is_some());
1684
1685 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 let json_none = serde_json::to_string(&base).unwrap();
1722 assert!(!json_none.contains("time_remaining_ms"));
1723 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 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 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 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 #[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 #[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 #[test]
1847 fn snapshot_without_game_type_decodes_as_unknown() {
1848 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 #[test]
1880 fn snapshot_ignores_fields_it_does_not_know() {
1881 let mut json = serde_json::to_string(&snapshot_of(GameType::Open)).unwrap();
1882 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 #[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 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}