sockudo-protocol 4.5.2

Pusher protocol message types and constants for Sockudo
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
use sockudo_protocol::messages::{MessageData, PusherMessage};
use sonic_rs::prelude::*;
use sonic_rs::{Value, json};

// Helper function to serialize message and parse as JSON for testing
fn message_to_json(message: &PusherMessage) -> Value {
    sonic_rs::to_value(message).expect("Failed to serialize message")
}

#[test]
fn test_connection_established_format() {
    // According to spec: data should be a String (JSON-encoded object)
    let message = PusherMessage::connection_established("test-socket-123".to_string(), 120);
    let json = message_to_json(&message);

    // Assert event field exists and has correct value
    assert!(json.get("event").is_some(), "Should have 'event' field");
    assert!(json["event"].is_str(), "Event field should be a string");
    assert_eq!(json["event"], "pusher:connection_established");

    // Assert data field exists and is a string (per Pusher spec)
    assert!(json.get("data").is_some(), "Should have 'data' field");
    assert!(
        json["data"].is_str(),
        "Data field should be a String (JSON-encoded)"
    );

    // Verify the string contains valid JSON
    let data_str = json["data"].as_str().expect("Data should be a string");
    let parsed_data: Value =
        sonic_rs::from_str(data_str).expect("Data string should contain valid JSON");

    // Assert parsed data has correct structure
    assert!(parsed_data.is_object(), "Parsed data should be an object");
    assert!(
        parsed_data.get("socket_id").is_some(),
        "Should have socket_id field"
    );
    assert!(
        parsed_data["socket_id"].is_str(),
        "socket_id should be a string"
    );
    assert_eq!(parsed_data["socket_id"], "test-socket-123");

    assert!(
        parsed_data.get("activity_timeout").is_some(),
        "Should have activity_timeout field"
    );
    assert!(
        parsed_data["activity_timeout"].is_number(),
        "activity_timeout should be a number"
    );
    assert_eq!(parsed_data["activity_timeout"], 120);
}

#[test]
fn test_error_format() {
    // According to spec: data should be an Object with message and code
    let message = PusherMessage::error(4001, "Application does not exist".to_string(), None);
    let json = message_to_json(&message);

    // Assert event field exists and has correct value
    assert!(json.get("event").is_some(), "Should have 'event' field");
    assert!(json["event"].is_str(), "Event field should be a string");
    assert_eq!(json["event"], "pusher:error");

    // Assert data field exists and is an object (per Pusher spec)
    assert!(json.get("data").is_some(), "Should have 'data' field");
    assert!(json["data"].is_object(), "Data field should be an Object");

    let data = json["data"].as_object().expect("Data should be an object");

    // Assert data object has correct structure
    assert!(data.get(&"code").is_some(), "Should have 'code' field");
    assert!(data["code"].is_number(), "Code should be a number");
    assert_eq!(data["code"], 4001);

    assert!(
        data.get(&"message").is_some(),
        "Should have 'message' field"
    );
    assert!(data["message"].is_str(), "Message should be a string");
    assert_eq!(data["message"], "Application does not exist");
}

#[test]
fn test_signin_success_format() {
    // According to spec: data should be an Object with only user_data field
    let user_data = r#"{"id":"123","name":"John"}"#.to_string();

    let message = PusherMessage::signin_success(user_data);

    let json = message_to_json(&message);

    // Assert event field exists and has correct value
    assert!(json.get("event").is_some(), "Should have 'event' field");
    assert!(json["event"].is_str(), "Event field should be a string");
    assert_eq!(json["event"], "pusher:signin_success");

    // Assert data field exists and is an object (per Pusher spec)
    assert!(json.get("data").is_some(), "Should have 'data' field");
    assert!(json["data"].is_object(), "Data field should be an Object");

    let data = json["data"].as_object().expect("Data should be an object");

    // Assert data object has correct structure
    assert!(
        data.contains_key(&"user_data"),
        "Should have user_data field"
    );
    assert!(!data.contains_key(&"auth"), "Should NOT have auth field");
    assert!(data["user_data"].is_str(), "user_data should be a string");
    assert_eq!(data["user_data"], r#"{"id":"123","name":"John"}"#);
}

#[test]
fn test_ping_format() {
    // According to spec: should have NO data field at all
    let message = PusherMessage::ping();
    let json = message_to_json(&message);

    // Assert event field exists and has correct value
    assert!(json.get("event").is_some(), "Should have 'event' field");
    assert!(json["event"].is_str(), "Event field should be a string");
    assert_eq!(json["event"], "pusher:ping");

    // Assert no data field exists (per Pusher spec)
    assert!(
        json.get("data").is_none(),
        "Ping should not have 'data' field"
    );
}

#[test]
fn test_pong_format() {
    // According to spec: should have NO data field at all
    let message = PusherMessage::pong();
    let json = message_to_json(&message);

    // Assert event field exists and has correct value
    assert!(json.get("event").is_some(), "Should have 'event' field");
    assert!(json["event"].is_str(), "Event field should be a string");
    assert_eq!(json["event"], "pusher:pong");

    // Assert no data field exists (per Pusher spec)
    assert!(
        json.get("data").is_none(),
        "Pong should not have 'data' field"
    );
}

#[test]
fn test_subscription_succeeded_format() {
    // According to spec: data should be a String (JSON-encoded object)
    // For presence channels, it contains presence data
    use ahash::AHashMap;
    use sockudo_protocol::messages::PresenceData;

    let mut hash = AHashMap::new();
    hash.insert("user1".to_string(), Some(json!({"name": "Alice"})));
    hash.insert("user2".to_string(), Some(json!({"name": "Bob"})));

    let presence_data = PresenceData {
        ids: vec!["user1".to_string(), "user2".to_string()],
        hash: hash.clone(),
        count: 2,
    };

    let message =
        PusherMessage::subscription_succeeded("presence-room".to_string(), Some(presence_data));
    let json = message_to_json(&message);

    // Assert event and channel fields exist and have correct values
    assert!(json.get("event").is_some(), "Should have 'event' field");
    assert!(json["event"].is_str(), "Event field should be a string");
    assert_eq!(json["event"], "pusher_internal:subscription_succeeded");

    assert!(json.get("channel").is_some(), "Should have 'channel' field");
    assert!(json["channel"].is_str(), "Channel field should be a string");
    assert_eq!(json["channel"], "presence-room");

    // Assert data field exists and is a string (per Pusher spec)
    assert!(json.get("data").is_some(), "Should have 'data' field");
    assert!(
        json["data"].is_str(),
        "Data field should be a String (JSON-encoded)"
    );

    // Verify the string contains valid JSON with presence data
    let data_str = json["data"].as_str().expect("Data should be a string");
    let parsed_data: Value =
        sonic_rs::from_str(data_str).expect("Data string should contain valid JSON");

    // Assert parsed data has correct structure
    assert!(parsed_data.is_object(), "Parsed data should be an object");
    assert!(
        parsed_data.get("presence").is_some(),
        "Should have 'presence' field"
    );

    // Verify the presence data structure (not double-wrapped)
    let presence = &parsed_data["presence"];
    assert_eq!(presence["count"], 2);
    assert_eq!(presence["ids"], json!(["user1", "user2"]));
    assert_eq!(presence["hash"]["user1"], json!({"name": "Alice"}));
    assert_eq!(presence["hash"]["user2"], json!({"name": "Bob"}));
}

#[test]
fn test_subscription_succeeded_non_presence_format() {
    // For non-presence channels, data should be empty object as string
    let message = PusherMessage::subscription_succeeded("private-channel".to_string(), None);
    let json = message_to_json(&message);

    // Assert event and channel fields exist and have correct values
    assert!(json.get("event").is_some(), "Should have 'event' field");
    assert!(json["event"].is_str(), "Event field should be a string");
    assert_eq!(json["event"], "pusher_internal:subscription_succeeded");

    assert!(json.get("channel").is_some(), "Should have 'channel' field");
    assert!(json["channel"].is_str(), "Channel field should be a string");
    assert_eq!(json["channel"], "private-channel");

    // Assert data field exists and is a string (per Pusher spec)
    assert!(json.get("data").is_some(), "Should have 'data' field");
    assert!(
        json["data"].is_str(),
        "Data field should be a String (JSON-encoded)"
    );

    // Verify the string contains empty JSON object
    let data_str = json["data"].as_str().expect("Data should be a string");
    let parsed_data: Value =
        sonic_rs::from_str(data_str).expect("Data string should contain valid JSON");

    // Assert parsed data is an empty object
    assert!(parsed_data.is_object(), "Parsed data should be an object");
    assert_eq!(parsed_data, json!({}));
}

#[test]
fn test_member_added_format() {
    // According to spec: data should be a String (JSON-encoded object)
    let user_info = json!({"name": "Alice", "email": "alice@example.com"});

    let message = PusherMessage::member_added(
        "presence-room".to_string(),
        "user123".to_string(),
        Some(user_info.clone()),
    );
    let json = message_to_json(&message);

    // Assert event and channel fields exist and have correct values
    assert!(json.get("event").is_some(), "Should have 'event' field");
    assert!(json["event"].is_str(), "Event field should be a string");
    assert_eq!(json["event"], "pusher_internal:member_added");

    assert!(json.get("channel").is_some(), "Should have 'channel' field");
    assert!(json["channel"].is_str(), "Channel field should be a string");
    assert_eq!(json["channel"], "presence-room");

    // Assert data field exists and is a string (per Pusher spec)
    assert!(json.get("data").is_some(), "Should have 'data' field");
    assert!(
        json["data"].is_str(),
        "Data field should be a String (JSON-encoded)"
    );

    // Verify the string contains valid JSON
    let data_str = json["data"].as_str().expect("Data should be a string");
    let parsed_data: Value =
        sonic_rs::from_str(data_str).expect("Data string should contain valid JSON");

    // Assert parsed data has correct structure
    assert!(parsed_data.is_object(), "Parsed data should be an object");
    assert!(
        parsed_data.get("user_id").is_some(),
        "Should have 'user_id' field"
    );
    assert!(
        parsed_data["user_id"].is_str(),
        "user_id should be a string"
    );
    assert_eq!(parsed_data["user_id"], "user123");

    assert!(
        parsed_data.get("user_info").is_some(),
        "Should have 'user_info' field"
    );
    assert_eq!(parsed_data["user_info"], user_info);
}

#[test]
fn test_member_removed_format() {
    // According to spec: data should be a String (JSON-encoded object)
    let message = PusherMessage::member_removed("presence-room".to_string(), "user123".to_string());
    let json = message_to_json(&message);

    // Assert event and channel fields exist and have correct values
    assert!(json.get("event").is_some(), "Should have 'event' field");
    assert!(json["event"].is_str(), "Event field should be a string");
    assert_eq!(json["event"], "pusher_internal:member_removed");

    assert!(json.get("channel").is_some(), "Should have 'channel' field");
    assert!(json["channel"].is_str(), "Channel field should be a string");
    assert_eq!(json["channel"], "presence-room");

    // Assert data field exists and is a string (per Pusher spec)
    assert!(json.get("data").is_some(), "Should have 'data' field");
    assert!(
        json["data"].is_str(),
        "Data field should be a String (JSON-encoded)"
    );

    // Verify the string contains valid JSON
    let data_str = json["data"].as_str().expect("Data should be a string");
    let parsed_data: Value =
        sonic_rs::from_str(data_str).expect("Data string should contain valid JSON");

    // Assert parsed data has correct structure
    assert!(parsed_data.is_object(), "Parsed data should be an object");
    assert!(
        parsed_data.get("user_id").is_some(),
        "Should have 'user_id' field"
    );
    assert!(
        parsed_data["user_id"].is_str(),
        "user_id should be a string"
    );
    assert_eq!(parsed_data["user_id"], "user123");

    assert!(
        parsed_data.get("user_info").is_none(),
        "Should not have user_info"
    );
}

#[test]
fn test_channel_event_format() {
    // According to spec: data should be a String for channel events
    let event_data = json!({"message": "Hello", "timestamp": 1234567890});

    let message = PusherMessage::channel_event("my-event", "my-channel", event_data.clone());
    let json = message_to_json(&message);

    // Assert event and channel fields exist and have correct values
    assert!(json.get("event").is_some(), "Should have 'event' field");
    assert!(json["event"].is_str(), "Event field should be a string");
    assert_eq!(json["event"], "my-event");

    assert!(json.get("channel").is_some(), "Should have 'channel' field");
    assert!(json["channel"].is_str(), "Channel field should be a string");
    assert_eq!(json["channel"], "my-channel");

    // Assert data field exists and is a string (per Pusher spec)
    assert!(json.get("data").is_some(), "Should have 'data' field");
    assert!(json["data"].is_str(), "Data field should be a String");

    // Verify the string contains the JSON data
    let data_str = json["data"].as_str().expect("Data should be a string");
    let parsed_data: Value =
        sonic_rs::from_str(data_str).expect("Data string should contain valid JSON");

    // Assert parsed data matches expected event data
    assert_eq!(parsed_data, event_data);
}

#[test]
fn test_channel_event_with_user_id() {
    // Test that channel events can include optional user_id field (per Pusher spec)
    let event_data = json!({"message": "Hello from Alice"});

    let message = PusherMessage {
        event: Some("my-event".to_string()),
        channel: Some("presence-room".to_string()),
        data: Some(MessageData::String(event_data.to_string())),
        name: None,
        user_id: Some("user123".to_string()),
        tags: None,
        sequence: None,
        conflation_key: None,
        message_id: None,
        stream_id: None,
        serial: None,
        idempotency_key: None,
        extras: None,
        delta_sequence: None,
        delta_conflation_key: None,
    };
    let json = message_to_json(&message);

    // Assert event and channel fields exist and have correct values
    assert!(json.get("event").is_some(), "Should have 'event' field");
    assert!(json["event"].is_str(), "Event field should be a string");
    assert_eq!(json["event"], "my-event");

    assert!(json.get("channel").is_some(), "Should have 'channel' field");
    assert!(json["channel"].is_str(), "Channel field should be a string");
    assert_eq!(json["channel"], "presence-room");

    // Assert data field exists and is a string (per Pusher spec)
    assert!(json.get("data").is_some(), "Should have 'data' field");
    assert!(json["data"].is_str(), "Data field should be a String");

    // Assert user_id field exists and has correct value (per Pusher spec)
    assert!(json.get("user_id").is_some(), "Should have 'user_id' field");
    assert!(json["user_id"].is_str(), "user_id should be a string");
    assert_eq!(json["user_id"], "user123");
}

#[test]
fn test_encrypted_channel_event_format() {
    // According to spec: data should be a String containing JSON with ciphertext and nonce
    // This tests that our format can handle encrypted data properly
    let encrypted_data = json!({
        "ciphertext": "encrypted_content_here",
        "nonce": "random_nonce_value"
    });

    let message = PusherMessage::channel_event(
        "my-event",
        "private-encrypted-channel",
        encrypted_data.clone(),
    );
    let json = message_to_json(&message);

    // Assert event and channel fields exist and have correct values
    assert!(json.get("event").is_some(), "Should have 'event' field");
    assert!(json["event"].is_str(), "Event field should be a string");
    assert_eq!(json["event"], "my-event");

    assert!(json.get("channel").is_some(), "Should have 'channel' field");
    assert!(json["channel"].is_str(), "Channel field should be a string");
    assert_eq!(json["channel"], "private-encrypted-channel");

    // Assert data field exists and is a string (per Pusher spec)
    assert!(json.get("data").is_some(), "Should have 'data' field");
    assert!(
        json["data"].is_str(),
        "Data field should be a String (JSON-encoded)"
    );

    // Verify the string contains the encrypted data JSON
    let data_str = json["data"].as_str().expect("Data should be a string");
    let parsed_data: Value =
        sonic_rs::from_str(data_str).expect("Data string should contain valid JSON");

    // Assert parsed data has correct encrypted structure
    assert!(parsed_data.is_object(), "Parsed data should be an object");
    assert!(
        parsed_data.get("ciphertext").is_some(),
        "Should have 'ciphertext' field"
    );
    assert!(
        parsed_data["ciphertext"].is_str(),
        "ciphertext should be a string"
    );
    assert_eq!(parsed_data["ciphertext"], "encrypted_content_here");

    assert!(
        parsed_data.get("nonce").is_some(),
        "Should have 'nonce' field"
    );
    assert!(parsed_data["nonce"].is_str(), "nonce should be a string");
    assert_eq!(parsed_data["nonce"], "random_nonce_value");
}

#[test]
fn test_client_event_accepts_string() {
    // Client events should accept String data
    let message = PusherMessage {
        channel: Some("private-channel".to_string()),
        event: Some("client-typing".to_string()),
        data: Some(MessageData::String("user is typing...".to_string())),
        name: None,
        user_id: None,
        tags: None,
        sequence: None,
        conflation_key: None,
        message_id: None,
        stream_id: None,
        serial: None,
        idempotency_key: None,
        extras: None,
        delta_sequence: None,
        delta_conflation_key: None,
    };

    let json = message_to_json(&message);

    // Assert event and channel fields exist and have correct values
    assert!(json.get("event").is_some(), "Should have 'event' field");
    assert!(json["event"].is_str(), "Event field should be a string");
    assert_eq!(json["event"], "client-typing");

    assert!(json.get("channel").is_some(), "Should have 'channel' field");
    assert!(json["channel"].is_str(), "Channel field should be a string");
    assert_eq!(json["channel"], "private-channel");

    // Assert data field exists and is a string
    assert!(json.get("data").is_some(), "Should have 'data' field");
    assert!(json["data"].is_str(), "Data should be a string");
    assert_eq!(json["data"], "user is typing...");
}

#[test]
fn test_client_event_accepts_json() {
    // Client events should also accept JSON object data
    let message = PusherMessage {
        channel: Some("private-channel".to_string()),
        event: Some("client-typing".to_string()),
        data: Some(MessageData::Json(
            json!({"user": "alice", "status": "typing"}),
        )),
        name: None,
        user_id: None,
        tags: None,
        sequence: None,
        conflation_key: None,
        message_id: None,
        stream_id: None,
        serial: None,
        idempotency_key: None,
        extras: None,
        delta_sequence: None,
        delta_conflation_key: None,
    };

    let json = message_to_json(&message);

    // Assert event and channel fields exist and have correct values
    assert!(json.get("event").is_some(), "Should have 'event' field");
    assert!(json["event"].is_str(), "Event field should be a string");
    assert_eq!(json["event"], "client-typing");

    assert!(json.get("channel").is_some(), "Should have 'channel' field");
    assert!(json["channel"].is_str(), "Channel field should be a string");
    assert_eq!(json["channel"], "private-channel");

    // Assert data field exists and is an object
    assert!(json.get("data").is_some(), "Should have 'data' field");
    assert!(json["data"].is_object(), "Data should be an object");

    // Assert data object has correct structure
    assert!(
        json["data"].get("user").is_some(),
        "Should have 'user' field in data"
    );
    assert!(json["data"]["user"].is_str(), "User should be a string");
    assert_eq!(json["data"]["user"], "alice");

    assert!(
        json["data"].get("status").is_some(),
        "Should have 'status' field in data"
    );
    assert!(json["data"]["status"].is_str(), "Status should be a string");
    assert_eq!(json["data"]["status"], "typing");
}

#[test]
fn test_cache_miss_event_format() {
    // According to spec: cache_miss event should send an empty JSON object as a string
    let message = PusherMessage::cache_miss_event("cache-channel".to_string());
    let json = message_to_json(&message);

    // Assert event field exists and has correct value
    assert!(json.get("event").is_some(), "Should have 'event' field");
    assert!(json["event"].is_str(), "Event field should be a string");
    assert_eq!(json["event"], "pusher:cache_miss");

    // Assert channel field exists and has correct value
    assert!(json.get("channel").is_some(), "Should have 'channel' field");
    assert!(json["channel"].is_str(), "Channel field should be a string");
    assert_eq!(json["channel"], "cache-channel");

    // Assert data field exists and is a string containing empty JSON object
    assert!(json.get("data").is_some(), "Should have 'data' field");
    assert!(
        json["data"].is_str(),
        "Data field should be a String (empty JSON object)"
    );

    // Verify the string is exactly "{}"
    let data_str = json["data"].as_str().expect("Data should be a string");
    assert_eq!(data_str, "{}", "Data should be exactly '{{}}'");

    // Also verify it parses to an empty JSON object
    let parsed_data: Value =
        sonic_rs::from_str(data_str).expect("Data string should contain valid JSON");
    assert!(parsed_data.is_object(), "Parsed data should be an object");
    assert_eq!(
        parsed_data,
        json!({}),
        "Parsed data should be an empty object"
    );
}

#[test]
fn test_channel_info_minimal_format() {
    // Test channel_info with only occupied field (minimal case)
    let response = PusherMessage::channel_info(false, None, None, None);

    // Assert response is a valid JSON object
    assert!(response.is_object(), "Response should be an object");

    // Assert occupied field exists and is correct type
    assert!(
        response.get("occupied").is_some(),
        "Should have 'occupied' field"
    );
    assert!(
        response["occupied"].is_boolean(),
        "'occupied' should be a boolean"
    );
    assert_eq!(response["occupied"], false);

    // Assert no optional fields are present
    assert!(
        response.get("subscription_count").is_none(),
        "Should not have 'subscription_count' when None"
    );
    assert!(
        response.get("user_count").is_none(),
        "Should not have 'user_count' when None"
    );
    assert!(
        response.get("cache").is_none(),
        "Should not have 'cache' when None"
    );

    // Assert exactly 1 field
    let obj = response.as_object().expect("Response should be an object");
    assert_eq!(obj.len(), 1, "Should have exactly 1 field when minimal");
}

#[test]
fn test_channel_info_with_subscription_count() {
    // Test channel_info with subscription_count
    let response = PusherMessage::channel_info(true, Some(42), None, None);

    // Assert response is a valid JSON object
    assert!(response.is_object(), "Response should be an object");

    // Assert occupied field
    assert!(
        response.get("occupied").is_some(),
        "Should have 'occupied' field"
    );
    assert!(
        response["occupied"].is_boolean(),
        "'occupied' should be a boolean"
    );
    assert_eq!(response["occupied"], true);

    // Assert subscription_count field
    assert!(
        response.get("subscription_count").is_some(),
        "Should have 'subscription_count' field"
    );
    assert!(
        response["subscription_count"].is_u64(),
        "'subscription_count' should be a number"
    );
    assert_eq!(response["subscription_count"], 42);

    // Assert other optional fields are not present
    assert!(
        response.get("user_count").is_none(),
        "Should not have 'user_count' when None"
    );
    assert!(
        response.get("cache").is_none(),
        "Should not have 'cache' when None"
    );
}

#[test]
fn test_channel_info_with_user_count() {
    // Test channel_info with user_count (for presence channels)
    let response = PusherMessage::channel_info(true, Some(10), Some(8), None);

    // Assert response is a valid JSON object
    assert!(response.is_object(), "Response should be an object");

    // Assert all fields
    assert_eq!(response["occupied"], true);
    assert_eq!(response["subscription_count"], 10);
    assert_eq!(response["user_count"], 8);

    // Verify types
    assert!(
        response["occupied"].is_boolean(),
        "'occupied' should be a boolean"
    );
    assert!(
        response["subscription_count"].is_u64(),
        "'subscription_count' should be a number"
    );
    assert!(
        response["user_count"].is_u64(),
        "'user_count' should be a number"
    );

    // Assert cache is not present
    assert!(
        response.get("cache").is_none(),
        "Should not have 'cache' when None"
    );
}

#[test]
fn test_channel_info_with_cache_data() {
    use std::time::Duration;

    // Test channel_info with cache data
    let cache_content = r#"{"event":"test","data":"cached"}"#.to_string();
    let ttl = Duration::from_secs(3600); // 1 hour

    let response =
        PusherMessage::channel_info(true, Some(5), None, Some((cache_content.clone(), ttl)));

    // Assert response is a valid JSON object
    assert!(response.is_object(), "Response should be an object");

    // Assert basic fields
    assert_eq!(response["occupied"], true);
    assert_eq!(response["subscription_count"], 5);

    // Assert cache field exists and has correct structure
    assert!(response.get("cache").is_some(), "Should have 'cache' field");
    assert!(response["cache"].is_object(), "'cache' should be an object");

    // Assert cache subfields
    let cache_obj = response["cache"]
        .as_object()
        .expect("Cache should be an object");
    assert!(
        cache_obj.contains_key(&"data"),
        "Cache should have 'data' field"
    );
    assert!(
        cache_obj.contains_key(&"ttl"),
        "Cache should have 'ttl' field"
    );

    // Verify cache data field
    assert!(
        response["cache"]["data"].is_str(),
        "Cache data should be a string"
    );
    assert_eq!(response["cache"]["data"], cache_content);

    // Verify cache ttl field
    assert!(
        response["cache"]["ttl"].is_u64(),
        "Cache ttl should be a number"
    );
    assert_eq!(response["cache"]["ttl"], 3600);

    // Assert user_count is not present
    assert!(
        response.get("user_count").is_none(),
        "Should not have 'user_count' when None"
    );
}

#[test]
fn test_channel_info_full_format() {
    use std::time::Duration;

    // Test channel_info with all fields populated
    let cache_content = r#"{"message":"Hello from cache"}"#.to_string();
    let ttl = Duration::from_secs(7200); // 2 hours

    let response = PusherMessage::channel_info(
        true,
        Some(100),
        Some(75),
        Some((cache_content.clone(), ttl)),
    );

    // Assert response is a valid JSON object
    assert!(response.is_object(), "Response should be an object");

    // Assert all fields are present and have correct values
    assert_eq!(response["occupied"], true);
    assert_eq!(response["subscription_count"], 100);
    assert_eq!(response["user_count"], 75);

    // Assert cache structure
    assert!(response["cache"].is_object(), "'cache' should be an object");
    assert_eq!(response["cache"]["data"], cache_content);
    assert_eq!(response["cache"]["ttl"], 7200);

    // Verify exact field count
    let obj = response.as_object().expect("Response should be an object");
    assert_eq!(
        obj.len(),
        4,
        "Should have exactly 4 fields when all are populated"
    );

    // Verify field types
    assert!(
        response["occupied"].is_boolean(),
        "'occupied' should be a boolean"
    );
    assert!(
        response["subscription_count"].is_u64(),
        "'subscription_count' should be a number"
    );
    assert!(
        response["user_count"].is_u64(),
        "'user_count' should be a number"
    );
    assert!(
        response["cache"]["data"].is_str(),
        "Cache data should be a string"
    );
    assert!(
        response["cache"]["ttl"].is_u64(),
        "Cache ttl should be a number"
    );
}

#[test]
fn test_channel_info_zero_values() {
    // Test that zero values are properly included (not filtered out)
    let response = PusherMessage::channel_info(false, Some(0), Some(0), None);

    // Assert response is a valid JSON object
    assert!(response.is_object(), "Response should be an object");

    // Assert all fields with zero values are present
    assert_eq!(response["occupied"], false);
    assert_eq!(response["subscription_count"], 0);
    assert_eq!(response["user_count"], 0);

    // Verify that zero counts are included (not filtered)
    assert!(
        response.get("subscription_count").is_some(),
        "Should include subscription_count even when 0"
    );
    assert!(
        response.get("user_count").is_some(),
        "Should include user_count even when 0"
    );
}

#[test]
fn test_watchlist_events_format() {
    // Watchlist events are custom Sockudo extensions, not in Pusher spec
    // They can keep their current format
    let message =
        PusherMessage::watchlist_online_event(vec!["user1".to_string(), "user2".to_string()]);
    let json = message_to_json(&message);

    // Assert event field exists and has correct value
    assert!(json.get("event").is_some(), "Should have 'event' field");
    assert!(json["event"].is_str(), "Event field should be a string");
    assert_eq!(json["event"], "online");

    // Assert channel field is omitted for watchlist events (due to skip_serializing_if)
    assert!(
        json.get("channel").is_none(),
        "Channel field should be omitted for watchlist events"
    );

    // Watchlist events can remain as JSON objects since they're custom
    assert!(json.get("data").is_some(), "Should have 'data' field");
    assert!(json["data"].is_object(), "Data should be an object");

    // Assert data object has correct structure
    assert!(
        json["data"].get("user_ids").is_some(),
        "Should have 'user_ids' field in data"
    );
    assert!(
        json["data"]["user_ids"].is_array(),
        "user_ids should be an array"
    );
    assert_eq!(json["data"]["user_ids"], json!(["user1", "user2"]));
}

// ── MessageExtras tests ──────────────────────────────────────────────

use sockudo_protocol::messages::{ExtrasValue, MessageExtras};
use std::collections::HashMap;

#[test]
fn test_extras_round_trip_serialize_deserialize() {
    let mut headers = HashMap::new();
    headers.insert(
        "x-region".to_string(),
        ExtrasValue::String("us-east".to_string()),
    );
    headers.insert("priority".to_string(), ExtrasValue::Number(1.0));
    headers.insert("urgent".to_string(), ExtrasValue::Bool(true));

    let extras = MessageExtras {
        headers: Some(headers),
        ephemeral: Some(true),
        idempotency_key: Some("abc-123".to_string()),
        push: None,
        echo: Some(false),
    };

    let json_str = sonic_rs::to_string(&extras).expect("serialize");
    let round_tripped: MessageExtras = sonic_rs::from_str(&json_str).expect("deserialize");

    assert_eq!(round_tripped.ephemeral, Some(true));
    assert_eq!(round_tripped.idempotency_key.as_deref(), Some("abc-123"));
    assert_eq!(round_tripped.echo, Some(false));
    let h = round_tripped.headers.unwrap();
    assert_eq!(
        h.get("x-region"),
        Some(&ExtrasValue::String("us-east".to_string()))
    );
    assert_eq!(h.get("priority"), Some(&ExtrasValue::Number(1.0)));
    assert_eq!(h.get("urgent"), Some(&ExtrasValue::Bool(true)));
}

#[test]
fn test_extras_default_is_all_none() {
    let extras = MessageExtras::default();
    assert!(extras.headers.is_none());
    assert!(extras.ephemeral.is_none());
    assert!(extras.idempotency_key.is_none());
    assert!(extras.push.is_none());
    assert!(extras.echo.is_none());
}

#[test]
fn test_is_ephemeral_false_when_extras_none() {
    let msg = PusherMessage::channel_event("test", "ch", json!({}));
    assert!(!msg.is_ephemeral());
}

#[test]
fn test_is_ephemeral_true_when_set() {
    let mut msg = PusherMessage::channel_event("test", "ch", json!({}));
    msg.extras = Some(MessageExtras {
        ephemeral: Some(true),
        ..Default::default()
    });
    assert!(msg.is_ephemeral());
}

#[test]
fn test_is_ephemeral_false_when_extras_present_but_not_set() {
    let mut msg = PusherMessage::channel_event("test", "ch", json!({}));
    msg.extras = Some(MessageExtras::default());
    assert!(!msg.is_ephemeral());
}

#[test]
fn test_should_echo_returns_connection_default_when_extras_none() {
    let msg = PusherMessage::channel_event("test", "ch", json!({}));
    assert!(msg.should_echo(true));
    assert!(!msg.should_echo(false));
}

#[test]
fn test_should_echo_true_overrides_connection_default() {
    let mut msg = PusherMessage::channel_event("test", "ch", json!({}));
    msg.extras = Some(MessageExtras {
        echo: Some(true),
        ..Default::default()
    });
    assert!(msg.should_echo(false));
    assert!(msg.should_echo(true));
}

#[test]
fn test_should_echo_false_overrides_connection_default() {
    let mut msg = PusherMessage::channel_event("test", "ch", json!({}));
    msg.extras = Some(MessageExtras {
        echo: Some(false),
        ..Default::default()
    });
    assert!(!msg.should_echo(true));
    assert!(!msg.should_echo(false));
}

#[test]
fn test_filter_headers_returns_none_when_extras_none() {
    let msg = PusherMessage::channel_event("test", "ch", json!({}));
    assert!(msg.filter_headers().is_none());
}

#[test]
fn test_filter_headers_returns_headers_when_set() {
    let mut headers = HashMap::new();
    headers.insert("env".to_string(), ExtrasValue::String("prod".to_string()));

    let mut msg = PusherMessage::channel_event("test", "ch", json!({}));
    msg.extras = Some(MessageExtras {
        headers: Some(headers),
        ..Default::default()
    });

    let h = msg.filter_headers().unwrap();
    assert_eq!(h.get("env"), Some(&ExtrasValue::String("prod".to_string())));
}

#[test]
fn test_v1_delivery_strips_extras() {
    let mut msg =
        PusherMessage::channel_event("test-event", "test-channel", json!({"hello": "world"}));
    msg.extras = Some(MessageExtras {
        ephemeral: Some(true),
        echo: Some(false),
        ..Default::default()
    });
    msg.serial = Some(42);
    msg.message_id = Some("msg-123".to_string());

    // Simulate V1 stripping (same as send_to_v1_sockets)
    msg.serial = None;
    msg.message_id = None;
    msg.extras = None;

    let json = message_to_json(&msg);
    assert!(
        json.get("extras").is_none(),
        "V1 delivery must not include extras"
    );
    assert!(
        json.get("serial").is_none(),
        "V1 delivery must not include serial"
    );
    assert!(
        json.get("messageId").is_none(),
        "V1 delivery must not include message_id"
    );
}

#[test]
fn test_v2_delivery_includes_extras() {
    let mut msg =
        PusherMessage::channel_event("test-event", "test-channel", json!({"hello": "world"}));
    msg.extras = Some(MessageExtras {
        ephemeral: Some(true),
        echo: Some(false),
        ..Default::default()
    });

    let json = message_to_json(&msg);
    assert!(
        json.get("extras").is_some(),
        "V2 delivery must include extras"
    );
    let extras = json.get("extras").unwrap();
    assert_eq!(extras["ephemeral"], true);
    assert_eq!(extras["echo"], false);
}

#[test]
fn test_v2_extras_push_is_serialized_inside_extras() {
    let mut msg =
        PusherMessage::channel_event("test-event", "test-channel", json!({"hello": "world"}));
    msg.extras = Some(MessageExtras {
        push: Some(json!({
            "title": "Hello",
            "body": "Push body",
            "templateData": {"id": "42"}
        })),
        ..Default::default()
    });

    let json = message_to_json(&msg);
    assert_eq!(json["extras"]["push"]["title"], "Hello");
    assert_eq!(json["extras"]["push"]["templateData"]["id"], "42");
}

#[test]
fn test_should_include_extras_by_protocol() {
    use sockudo_protocol::ProtocolVersion;
    assert!(!PusherMessage::should_include_extras(&ProtocolVersion::V1));
    assert!(PusherMessage::should_include_extras(&ProtocolVersion::V2));
}

#[test]
fn test_validate_headers_rejects_nested_objects() {
    let raw = json!({
        "extras": {
            "headers": {
                "valid_key": "string_value",
                "bad_key": {"nested": true}
            }
        }
    });
    let result = MessageExtras::validate_headers_from_json(&raw);
    assert!(result.is_err());
    assert!(
        result
            .unwrap_err()
            .contains("nested objects and arrays are not allowed")
    );
}

#[test]
fn test_validate_headers_rejects_arrays() {
    let raw = json!({
        "extras": {
            "headers": {
                "bad_key": [1, 2, 3]
            }
        }
    });
    let result = MessageExtras::validate_headers_from_json(&raw);
    assert!(result.is_err());
}

#[test]
fn test_validate_headers_accepts_flat_scalars() {
    let raw = json!({
        "extras": {
            "headers": {
                "str_key": "hello",
                "num_key": 42,
                "bool_key": true
            }
        }
    });
    let result = MessageExtras::validate_headers_from_json(&raw);
    assert!(result.is_ok());
}

#[test]
fn test_validate_headers_ok_when_no_extras() {
    let raw = json!({"name": "test-event"});
    let result = MessageExtras::validate_headers_from_json(&raw);
    assert!(result.is_ok());
}

#[test]
fn test_extras_skipped_in_serialization_when_none() {
    let msg = PusherMessage::channel_event("test", "ch", json!({}));
    let json = message_to_json(&msg);
    assert!(
        json.get("extras").is_none(),
        "extras should be omitted when None"
    );
}

#[test]
fn test_extras_idempotency_key() {
    let mut msg = PusherMessage::channel_event("test", "ch", json!({}));
    assert!(msg.extras_idempotency_key().is_none());

    msg.extras = Some(MessageExtras {
        idempotency_key: Some("dedup-key-1".to_string()),
        ..Default::default()
    });
    assert_eq!(msg.extras_idempotency_key(), Some("dedup-key-1"));
}