peat-mesh 0.8.2

Peat mesh networking library with CRDT sync, transport security, and topology management
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
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
//! Supporting types for data synchronization abstraction
//!
//! This module defines common types used across all sync backend implementations,
//! providing a unified interface regardless of underlying CRDT engine (Ditto, Automerge, etc).

use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::PathBuf;
use std::time::SystemTime;

/// Unique identifier for a document
pub type DocumentId = String;

/// Unique identifier for a peer
pub type PeerId = String;

/// Timestamp for ordering and versioning
pub type Timestamp = SystemTime;

/// Generic value type for document fields
pub use serde_json::Value;

/// Unified document representation across backends
///
/// This provides a backend-agnostic view of documents, abstracting away
/// differences between Ditto's CBOR documents and Automerge's columnar storage.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Document {
    /// Optional document ID (None for new documents)
    pub id: Option<DocumentId>,

    /// Document fields as key-value pairs
    pub fields: HashMap<String, Value>,

    /// Last update timestamp
    pub updated_at: Timestamp,
}

impl Document {
    /// Create a new document with given fields
    pub fn new(fields: HashMap<String, Value>) -> Self {
        Self {
            id: None,
            fields,
            updated_at: SystemTime::now(),
        }
    }

    /// Create a document with a specific ID
    pub fn with_id(id: impl Into<String>, fields: HashMap<String, Value>) -> Self {
        Self {
            id: Some(id.into()),
            fields,
            updated_at: SystemTime::now(),
        }
    }

    /// Get a field value by name
    pub fn get(&self, field: &str) -> Option<&Value> {
        self.fields.get(field)
    }

    /// Set a field value
    pub fn set(&mut self, field: impl Into<String>, value: Value) {
        self.fields.insert(field.into(), value);
        self.updated_at = SystemTime::now();
    }
}

/// Geographic point for spatial queries (Issue #356)
///
/// Represents a WGS84 coordinate for spatial filtering.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub struct GeoPoint {
    /// Latitude in degrees (-90 to 90)
    pub lat: f64,
    /// Longitude in degrees (-180 to 180)
    pub lon: f64,
}

impl GeoPoint {
    /// Create a new GeoPoint
    pub fn new(lat: f64, lon: f64) -> Self {
        Self { lat, lon }
    }

    /// Calculate haversine distance to another point in meters
    ///
    /// Uses the haversine formula for great-circle distance on a sphere.
    pub fn distance_to(&self, other: &GeoPoint) -> f64 {
        haversine_distance(self.lat, self.lon, other.lat, other.lon)
    }

    /// Check if this point is within a bounding box
    pub fn within_bounds(&self, min: &GeoPoint, max: &GeoPoint) -> bool {
        self.lat >= min.lat && self.lat <= max.lat && self.lon >= min.lon && self.lon <= max.lon
    }

    /// Check if this point is within a radius of another point
    pub fn within_radius(&self, center: &GeoPoint, radius_meters: f64) -> bool {
        self.distance_to(center) <= radius_meters
    }
}

/// Haversine distance calculation between two coordinates
///
/// Returns distance in meters using WGS84 Earth radius.
pub fn haversine_distance(lat1: f64, lon1: f64, lat2: f64, lon2: f64) -> f64 {
    const EARTH_RADIUS_METERS: f64 = 6_371_000.0; // WGS84 mean radius

    let lat1_rad = lat1.to_radians();
    let lat2_rad = lat2.to_radians();
    let delta_lat = (lat2 - lat1).to_radians();
    let delta_lon = (lon2 - lon1).to_radians();

    let a = (delta_lat / 2.0).sin().powi(2)
        + lat1_rad.cos() * lat2_rad.cos() * (delta_lon / 2.0).sin().powi(2);

    let c = 2.0 * a.sqrt().asin();

    EARTH_RADIUS_METERS * c
}

/// Query abstraction that works across backends
///
/// Provides a simple query language that can be translated to backend-specific
/// query formats (Ditto DQL, Automerge queries, etc).
///
/// # Spatial Queries (Issue #356)
///
/// Spatial queries filter documents by geographic location:
/// - `WithinRadius`: Documents within a specified distance of a center point
/// - `WithinBounds`: Documents within a rectangular bounding box
///
/// Documents must have `lat` and `lon` fields (or configurable field names) for
/// spatial queries to match.
#[derive(Debug, Clone)]
pub enum Query {
    /// Simple equality match: field == value
    Eq { field: String, value: Value },

    /// Less than: field < value
    Lt { field: String, value: Value },

    /// Greater than: field > value
    Gt { field: String, value: Value },

    /// Multiple conditions combined with AND
    And(Vec<Query>),

    /// Multiple conditions combined with OR
    Or(Vec<Query>),

    /// Negation of a query (Issue #357)
    ///
    /// Matches documents that do NOT match the inner query.
    Not(Box<Query>),

    /// All documents in collection (no filter)
    All,

    /// Custom backend-specific query string
    /// Use sparingly - limits backend portability
    Custom(String),

    // === Deletion-aware queries (ADR-034, Issue #369) ===
    /// Include soft-deleted documents in query results
    ///
    /// By default, queries exclude documents with `_deleted=true` (soft-deleted).
    /// This modifier includes those documents in the results.
    ///
    /// # Example
    ///
    /// ```ignore
    /// // Default: excludes deleted documents
    /// let query = Query::All;
    ///
    /// // Include deleted documents
    /// let query_with_deleted = Query::IncludeDeleted(Box::new(Query::All));
    ///
    /// // With a filter
    /// let filtered_with_deleted = Query::IncludeDeleted(Box::new(Query::Eq {
    ///     field: "type".to_string(),
    ///     value: Value::String("contact_report".to_string()),
    /// }));
    /// ```
    IncludeDeleted(Box<Query>),

    /// Only return soft-deleted documents
    ///
    /// Matches only documents where `_deleted=true`.
    /// Useful for auditing or restoring deleted records.
    DeletedOnly,

    // === Spatial queries (Issue #356) ===
    /// Documents within a radius of a center point
    ///
    /// Requires documents to have `lat` and `lon` fields (or fields specified
    /// by `lat_field` and `lon_field`).
    WithinRadius {
        /// Center point for the radius search
        center: GeoPoint,
        /// Radius in meters
        radius_meters: f64,
        /// Field name for latitude (default: "lat")
        lat_field: Option<String>,
        /// Field name for longitude (default: "lon")
        lon_field: Option<String>,
    },

    /// Documents within a rectangular bounding box
    ///
    /// Requires documents to have `lat` and `lon` fields (or fields specified
    /// by `lat_field` and `lon_field`).
    WithinBounds {
        /// Southwest corner (minimum lat/lon)
        min: GeoPoint,
        /// Northeast corner (maximum lat/lon)
        max: GeoPoint,
        /// Field name for latitude (default: "lat")
        lat_field: Option<String>,
        /// Field name for longitude (default: "lon")
        lon_field: Option<String>,
    },
}

impl Query {
    /// Check if this query includes deleted documents
    ///
    /// Returns true if the query is `IncludeDeleted` or `DeletedOnly`.
    pub fn includes_deleted(&self) -> bool {
        matches!(self, Query::IncludeDeleted(_) | Query::DeletedOnly)
    }

    /// Check if this query only matches deleted documents
    pub fn is_deleted_only(&self) -> bool {
        matches!(self, Query::DeletedOnly)
    }

    /// Wrap this query to include deleted documents
    ///
    /// If already `IncludeDeleted` or `DeletedOnly`, returns self unchanged.
    pub fn with_deleted(self) -> Self {
        if self.includes_deleted() {
            self
        } else {
            Query::IncludeDeleted(Box::new(self))
        }
    }

    /// Get the inner query if this is an IncludeDeleted wrapper
    pub fn inner_query(&self) -> &Query {
        match self {
            Query::IncludeDeleted(inner) => inner.as_ref(),
            other => other,
        }
    }

    /// Check if a document matches the soft-delete filter
    ///
    /// - For normal queries: document must NOT have `_deleted=true`
    /// - For `IncludeDeleted`: document can have any `_deleted` value
    /// - For `DeletedOnly`: document MUST have `_deleted=true`
    pub fn matches_deletion_state(&self, doc: &Document) -> bool {
        let is_deleted = doc
            .fields
            .get("_deleted")
            .and_then(|v| v.as_bool())
            .unwrap_or(false);

        match self {
            Query::DeletedOnly => is_deleted,
            Query::IncludeDeleted(_) => true, // Include all
            _ => !is_deleted,                 // Exclude deleted
        }
    }
}

/// Stream of document changes for live queries
///
/// Returned by `DocumentStore::observe()` to receive real-time updates.
pub struct ChangeStream {
    /// Channel receiver for change events
    pub receiver: tokio::sync::mpsc::UnboundedReceiver<ChangeEvent>,
}

/// Event representing a document change
#[derive(Debug, Clone)]
pub enum ChangeEvent {
    /// Document was inserted or updated
    Updated {
        collection: String,
        document: Document,
    },

    /// Document was removed
    Removed {
        collection: String,
        doc_id: DocumentId,
    },

    /// Initial snapshot of all matching documents
    Initial { documents: Vec<Document> },
}

/// Information about a discovered peer
#[derive(Debug, Clone)]
pub struct PeerInfo {
    /// Unique peer identifier
    pub peer_id: PeerId,

    /// Network address (if known)
    pub address: Option<String>,

    /// Transport type used for connection
    pub transport: TransportType,

    /// Whether peer is currently connected
    pub connected: bool,

    /// Last time this peer was seen
    pub last_seen: Timestamp,

    /// Additional peer metadata
    pub metadata: HashMap<String, String>,
}

/// Transport types for peer connections
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum TransportType {
    /// TCP/IP connection
    Tcp,

    /// Bluetooth connection
    Bluetooth,

    /// mDNS local network discovery
    #[serde(rename = "mdns")]
    Mdns,

    /// WebSocket connection
    WebSocket,

    /// Custom transport
    Custom,
}

/// Events related to peer lifecycle
#[derive(Debug, Clone)]
pub enum PeerEvent {
    /// New peer discovered
    Discovered(PeerInfo),

    /// Peer connected
    Connected(PeerInfo),

    /// Peer disconnected
    Disconnected {
        peer_id: PeerId,
        reason: Option<String>,
    },

    /// Peer lost (no longer discoverable)
    Lost(PeerId),
}

/// Configuration for a sync backend
#[derive(Debug, Clone)]
pub struct BackendConfig {
    /// Application ID (used for peer discovery and sync groups)
    pub app_id: String,

    /// Directory for persistent storage
    pub persistence_dir: PathBuf,

    /// Optional shared secret for authentication
    pub shared_key: Option<String>,

    /// Transport configuration
    pub transport: TransportConfig,

    /// Additional backend-specific configuration
    pub extra: HashMap<String, String>,
}

/// Transport-specific configuration
#[derive(Debug, Clone)]
pub struct TransportConfig {
    /// TCP listening port (None = auto-assign)
    pub tcp_listen_port: Option<u16>,

    /// TCP address to connect to (for client mode)
    pub tcp_connect_address: Option<String>,

    /// Enable mDNS local discovery
    pub enable_mdns: bool,

    /// Enable Bluetooth discovery
    pub enable_bluetooth: bool,

    /// Enable WebSocket transport
    pub enable_websocket: bool,

    /// Custom transport configuration
    pub custom: HashMap<String, String>,
}

impl Default for TransportConfig {
    fn default() -> Self {
        Self {
            tcp_listen_port: None,
            tcp_connect_address: None,
            enable_mdns: true,
            enable_bluetooth: false,
            enable_websocket: false,
            custom: HashMap::new(),
        }
    }
}

/// Subscription handle for sync operations
///
/// Keeps sync active for a collection while alive.
/// Drop to unsubscribe.
pub struct SyncSubscription {
    collection: String,
    _handle: Box<dyn std::any::Any + Send + Sync>,
}

impl SyncSubscription {
    /// Create a new subscription
    pub fn new(collection: impl Into<String>, handle: impl std::any::Any + Send + Sync) -> Self {
        eprintln!("SyncSubscription::new() - Creating subscription wrapper");
        Self {
            collection: collection.into(),
            _handle: Box::new(handle),
        }
    }

    /// Get the collection this subscription is for
    pub fn collection(&self) -> &str {
        &self.collection
    }
}

impl Drop for SyncSubscription {
    fn drop(&mut self) {
        eprintln!(
            "SyncSubscription::drop() - Subscription for '{}' is being dropped!",
            self.collection
        );
    }
}

impl std::fmt::Debug for SyncSubscription {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("SyncSubscription")
            .field("collection", &self.collection)
            .finish_non_exhaustive()
    }
}

// === QoS-aware subscriptions (Issue #356) ===

/// Subscription configuration with QoS policy
///
/// Combines a collection, query filter, and QoS settings for fine-grained
/// control over what data syncs and how it syncs.
///
/// # Example
///
/// ```
/// use peat_mesh::sync::types::{Subscription, Query, GeoPoint, SubscriptionQoS};
/// use peat_mesh::qos::SyncMode;
///
/// // Subscribe to nearby beacons with LatestOnly sync
/// let subscription = Subscription {
///     collection: "beacons".to_string(),
///     query: Query::WithinRadius {
///         center: GeoPoint::new(37.7749, -122.4194),
///         radius_meters: 5000.0,
///         lat_field: None,
///         lon_field: None,
///     },
///     qos: SubscriptionQoS {
///         sync_mode: SyncMode::LatestOnly,
///         max_documents: Some(100),
///         update_rate_ms: Some(1000),
///     },
/// };
/// ```
#[derive(Debug, Clone)]
pub struct Subscription {
    /// Collection to subscribe to
    pub collection: String,
    /// Query filter for documents
    pub query: Query,
    /// QoS settings for this subscription
    pub qos: SubscriptionQoS,
}

impl Subscription {
    /// Create a subscription for all documents in a collection
    pub fn all(collection: impl Into<String>) -> Self {
        Self {
            collection: collection.into(),
            query: Query::All,
            qos: SubscriptionQoS::default(),
        }
    }

    /// Create a subscription with a query
    pub fn with_query(collection: impl Into<String>, query: Query) -> Self {
        Self {
            collection: collection.into(),
            query,
            qos: SubscriptionQoS::default(),
        }
    }

    /// Create a subscription with query and QoS
    pub fn with_qos(collection: impl Into<String>, query: Query, qos: SubscriptionQoS) -> Self {
        Self {
            collection: collection.into(),
            query,
            qos,
        }
    }

    /// Create a spatial radius subscription
    pub fn within_radius(
        collection: impl Into<String>,
        center: GeoPoint,
        radius_meters: f64,
    ) -> Self {
        Self {
            collection: collection.into(),
            query: Query::WithinRadius {
                center,
                radius_meters,
                lat_field: None,
                lon_field: None,
            },
            qos: SubscriptionQoS::default(),
        }
    }

    /// Create a spatial bounds subscription
    pub fn within_bounds(collection: impl Into<String>, min: GeoPoint, max: GeoPoint) -> Self {
        Self {
            collection: collection.into(),
            query: Query::WithinBounds {
                min,
                max,
                lat_field: None,
                lon_field: None,
            },
            qos: SubscriptionQoS::default(),
        }
    }

    /// Set sync mode for this subscription
    pub fn with_sync_mode(mut self, sync_mode: crate::qos::SyncMode) -> Self {
        self.qos.sync_mode = sync_mode;
        self
    }

    // === Dynamic subscription updates (Issue #357) ===

    /// Update the query for this subscription
    ///
    /// Allows modifying the subscription filter without recreating it.
    /// Useful for dynamic spatial queries that follow user position.
    pub fn update_query(&mut self, query: Query) {
        self.query = query;
    }

    /// Update the QoS settings for this subscription
    ///
    /// Allows adjusting sync behavior based on runtime conditions
    /// (e.g., switching to LatestOnly when bandwidth is constrained).
    pub fn update_qos(&mut self, qos: SubscriptionQoS) {
        self.qos = qos;
    }

    /// Update just the sync mode
    pub fn update_sync_mode(&mut self, sync_mode: crate::qos::SyncMode) {
        self.qos.sync_mode = sync_mode;
    }

    /// Update the spatial center point (for radius queries)
    ///
    /// If the current query is a `WithinRadius`, updates the center point.
    /// Otherwise, this is a no-op.
    pub fn update_center(&mut self, new_center: GeoPoint) {
        if let Query::WithinRadius { center, .. } = &mut self.query {
            *center = new_center;
        }
    }

    /// Update the spatial radius (for radius queries)
    ///
    /// If the current query is a `WithinRadius`, updates the radius.
    /// Otherwise, this is a no-op.
    pub fn update_radius(&mut self, new_radius: f64) {
        if let Query::WithinRadius { radius_meters, .. } = &mut self.query {
            *radius_meters = new_radius;
        }
    }
}

/// QoS settings for a subscription (Issue #356)
///
/// Controls sync behavior including sync mode, rate limiting, and document limits.
#[derive(Debug, Clone, Default)]
pub struct SubscriptionQoS {
    /// Sync mode (FullHistory, LatestOnly, WindowedHistory)
    pub sync_mode: crate::qos::SyncMode,
    /// Maximum number of documents to sync (None = unlimited)
    pub max_documents: Option<usize>,
    /// Minimum time between updates in ms (rate limiting)
    pub update_rate_ms: Option<u64>,
}

impl SubscriptionQoS {
    /// Create QoS with LatestOnly mode (no history)
    pub fn latest_only() -> Self {
        Self {
            sync_mode: crate::qos::SyncMode::LatestOnly,
            ..Default::default()
        }
    }

    /// Create QoS with FullHistory mode (all deltas)
    pub fn full_history() -> Self {
        Self {
            sync_mode: crate::qos::SyncMode::FullHistory,
            ..Default::default()
        }
    }

    /// Create QoS with WindowedHistory mode
    pub fn windowed(window_seconds: u64) -> Self {
        Self {
            sync_mode: crate::qos::SyncMode::WindowedHistory { window_seconds },
            ..Default::default()
        }
    }

    /// Set max documents
    pub fn with_max_documents(mut self, max: usize) -> Self {
        self.max_documents = Some(max);
        self
    }

    /// Set update rate limit
    pub fn with_rate_limit(mut self, rate_ms: u64) -> Self {
        self.update_rate_ms = Some(rate_ms);
        self
    }
}

/// Priority level for sync operations
///
/// Used by backends that support priority-based synchronization
/// (e.g., prioritize critical updates over metadata changes).
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Default)]
pub enum Priority {
    /// Critical updates (e.g., capability loss, safety-critical)
    Critical = 0,

    /// High priority (e.g., cell membership changes)
    High = 1,

    /// Medium priority (e.g., leader election)
    #[default]
    Medium = 2,

    /// Low priority (e.g., capability additions, metadata)
    Low = 3,
}

// === Sync Mode Metrics (Issue #357) ===

/// Metrics for sync mode performance tracking
///
/// Provides statistics on sync operations by mode, enabling analysis
/// of the ~300× reconnection improvement from LatestOnly mode.
///
/// # Example
///
/// ```
/// use peat_mesh::sync::types::SyncModeMetrics;
/// use peat_mesh::qos::SyncMode;
///
/// let mut metrics = SyncModeMetrics::new();
/// metrics.record_sync("beacons", SyncMode::LatestOnly, 1024, std::time::Duration::from_millis(5));
/// assert_eq!(metrics.total_syncs, 1);
/// assert_eq!(metrics.latest_only_syncs, 1);
/// ```
#[derive(Debug, Clone, Default)]
pub struct SyncModeMetrics {
    /// Total number of sync operations
    pub total_syncs: u64,
    /// Number of syncs using FullHistory mode
    pub full_history_syncs: u64,
    /// Number of syncs using LatestOnly mode
    pub latest_only_syncs: u64,
    /// Number of syncs using WindowedHistory mode
    pub windowed_syncs: u64,
    /// Total bytes synced with FullHistory mode
    pub full_history_bytes: u64,
    /// Total bytes synced with LatestOnly mode
    pub latest_only_bytes: u64,
    /// Total bytes synced with WindowedHistory mode
    pub windowed_bytes: u64,
    /// Total sync duration (in milliseconds) for FullHistory
    pub full_history_duration_ms: u64,
    /// Total sync duration (in milliseconds) for LatestOnly
    pub latest_only_duration_ms: u64,
    /// Total sync duration (in milliseconds) for WindowedHistory
    pub windowed_duration_ms: u64,
}

impl SyncModeMetrics {
    /// Create new empty metrics
    pub fn new() -> Self {
        Self::default()
    }

    /// Record a sync operation
    pub fn record_sync(
        &mut self,
        _collection: &str,
        mode: crate::qos::SyncMode,
        bytes: u64,
        duration: std::time::Duration,
    ) {
        self.total_syncs += 1;
        let duration_ms = duration.as_millis() as u64;

        match mode {
            crate::qos::SyncMode::FullHistory => {
                self.full_history_syncs += 1;
                self.full_history_bytes += bytes;
                self.full_history_duration_ms += duration_ms;
            }
            crate::qos::SyncMode::LatestOnly => {
                self.latest_only_syncs += 1;
                self.latest_only_bytes += bytes;
                self.latest_only_duration_ms += duration_ms;
            }
            crate::qos::SyncMode::WindowedHistory { .. } => {
                self.windowed_syncs += 1;
                self.windowed_bytes += bytes;
                self.windowed_duration_ms += duration_ms;
            }
        }
    }

    /// Average bytes per sync for FullHistory mode
    pub fn avg_full_history_bytes(&self) -> f64 {
        if self.full_history_syncs == 0 {
            0.0
        } else {
            self.full_history_bytes as f64 / self.full_history_syncs as f64
        }
    }

    /// Average bytes per sync for LatestOnly mode
    pub fn avg_latest_only_bytes(&self) -> f64 {
        if self.latest_only_syncs == 0 {
            0.0
        } else {
            self.latest_only_bytes as f64 / self.latest_only_syncs as f64
        }
    }

    /// Bandwidth savings ratio (LatestOnly vs FullHistory)
    ///
    /// Returns the ratio of FullHistory bytes to LatestOnly bytes.
    /// A ratio of 300.0 means LatestOnly uses 300× less bandwidth.
    pub fn bandwidth_savings_ratio(&self) -> Option<f64> {
        let fh_avg = self.avg_full_history_bytes();
        let lo_avg = self.avg_latest_only_bytes();

        if lo_avg == 0.0 || fh_avg == 0.0 {
            None
        } else {
            Some(fh_avg / lo_avg)
        }
    }

    /// Reset all metrics
    pub fn reset(&mut self) {
        *self = Self::default();
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_document_creation() {
        let mut fields = HashMap::new();
        fields.insert("name".to_string(), Value::String("test".to_string()));

        let doc = Document::new(fields.clone());
        assert!(doc.id.is_none());
        assert_eq!(doc.get("name"), Some(&Value::String("test".to_string())));

        let doc_with_id = Document::with_id("doc1", fields);
        assert_eq!(doc_with_id.id, Some("doc1".to_string()));
    }

    #[test]
    fn test_document_field_access() {
        let mut doc = Document::new(HashMap::new());
        doc.set("key", Value::String("value".to_string()));

        assert_eq!(doc.get("key"), Some(&Value::String("value".to_string())));
        assert_eq!(doc.get("missing"), None);
    }

    #[test]
    fn test_priority_ordering() {
        assert!(Priority::Critical < Priority::High);
        assert!(Priority::High < Priority::Medium);
        assert!(Priority::Medium < Priority::Low);
    }

    // === Spatial query tests (Issue #356) ===

    #[test]
    fn test_geopoint_creation() {
        let point = GeoPoint::new(37.7749, -122.4194); // San Francisco
        assert_eq!(point.lat, 37.7749);
        assert_eq!(point.lon, -122.4194);
    }

    #[test]
    fn test_haversine_distance_same_point() {
        let sf = GeoPoint::new(37.7749, -122.4194);
        let distance = sf.distance_to(&sf);
        assert!(
            distance < 1.0,
            "Distance to self should be ~0, got {}",
            distance
        );
    }

    #[test]
    fn test_haversine_distance_known_values() {
        // San Francisco to Los Angeles: approximately 559 km
        let sf = GeoPoint::new(37.7749, -122.4194);
        let la = GeoPoint::new(34.0522, -118.2437);
        let distance = sf.distance_to(&la);

        // Allow 1% tolerance
        let expected = 559_000.0;
        let tolerance = expected * 0.01;
        assert!(
            (distance - expected).abs() < tolerance,
            "SF to LA should be ~559km, got {}m",
            distance
        );
    }

    #[test]
    fn test_haversine_distance_across_equator() {
        // Quito, Ecuador (near equator) to Buenos Aires, Argentina
        let quito = GeoPoint::new(-0.1807, -78.4678);
        let buenos_aires = GeoPoint::new(-34.6037, -58.3816);
        let distance = quito.distance_to(&buenos_aires);

        // Approximately 4,360 km
        assert!(
            distance > 4_300_000.0 && distance < 4_500_000.0,
            "Quito to Buenos Aires should be ~4,360km, got {}m",
            distance
        );
    }

    #[test]
    fn test_geopoint_within_bounds() {
        let point = GeoPoint::new(37.7749, -122.4194); // San Francisco
        let min = GeoPoint::new(37.0, -123.0);
        let max = GeoPoint::new(38.0, -122.0);

        assert!(point.within_bounds(&min, &max));

        // Outside bounds
        let outside = GeoPoint::new(40.0, -122.0);
        assert!(!outside.within_bounds(&min, &max));
    }

    #[test]
    fn test_geopoint_within_radius() {
        let center = GeoPoint::new(37.7749, -122.4194); // San Francisco

        // Point 1km away (approximately)
        let nearby = GeoPoint::new(37.7839, -122.4194); // ~1km north
        assert!(nearby.within_radius(&center, 2000.0)); // Within 2km
        assert!(!nearby.within_radius(&center, 500.0)); // Not within 500m

        // Point far away
        let la = GeoPoint::new(34.0522, -118.2437);
        assert!(!la.within_radius(&center, 100_000.0)); // Not within 100km
        assert!(la.within_radius(&center, 600_000.0)); // Within 600km
    }

    #[test]
    fn test_spatial_query_within_radius() {
        let query = Query::WithinRadius {
            center: GeoPoint::new(37.7749, -122.4194),
            radius_meters: 5000.0,
            lat_field: None,
            lon_field: None,
        };

        match query {
            Query::WithinRadius {
                center,
                radius_meters,
                ..
            } => {
                assert_eq!(center.lat, 37.7749);
                assert_eq!(radius_meters, 5000.0);
            }
            _ => panic!("Expected WithinRadius query"),
        }
    }

    #[test]
    fn test_spatial_query_within_bounds() {
        let query = Query::WithinBounds {
            min: GeoPoint::new(37.0, -123.0),
            max: GeoPoint::new(38.0, -122.0),
            lat_field: Some("latitude".to_string()),
            lon_field: Some("longitude".to_string()),
        };

        match query {
            Query::WithinBounds {
                min,
                max,
                lat_field,
                lon_field,
            } => {
                assert_eq!(min.lat, 37.0);
                assert_eq!(max.lon, -122.0);
                assert_eq!(lat_field, Some("latitude".to_string()));
                assert_eq!(lon_field, Some("longitude".to_string()));
            }
            _ => panic!("Expected WithinBounds query"),
        }
    }

    #[test]
    fn test_geopoint_serialization() {
        let point = GeoPoint::new(37.7749, -122.4194);
        let json = serde_json::to_string(&point).unwrap();
        let deserialized: GeoPoint = serde_json::from_str(&json).unwrap();
        assert_eq!(point, deserialized);
    }

    // === Subscription tests (Issue #356) ===

    #[test]
    fn test_subscription_all() {
        let sub = Subscription::all("beacons");
        assert_eq!(sub.collection, "beacons");
        assert!(matches!(sub.query, Query::All));
    }

    #[test]
    fn test_subscription_with_query() {
        let query = Query::Eq {
            field: "type".to_string(),
            value: Value::String("soldier".to_string()),
        };
        let sub = Subscription::with_query("platforms", query);
        assert_eq!(sub.collection, "platforms");
    }

    #[test]
    fn test_subscription_within_radius() {
        let center = GeoPoint::new(37.7749, -122.4194);
        let sub = Subscription::within_radius("beacons", center, 5000.0);

        assert_eq!(sub.collection, "beacons");
        match sub.query {
            Query::WithinRadius {
                center: c,
                radius_meters,
                ..
            } => {
                assert_eq!(c.lat, 37.7749);
                assert_eq!(radius_meters, 5000.0);
            }
            _ => panic!("Expected WithinRadius query"),
        }
    }

    #[test]
    fn test_subscription_within_bounds() {
        let min = GeoPoint::new(37.0, -123.0);
        let max = GeoPoint::new(38.0, -122.0);
        let sub = Subscription::within_bounds("beacons", min, max);

        assert_eq!(sub.collection, "beacons");
        match sub.query {
            Query::WithinBounds {
                min: m, max: mx, ..
            } => {
                assert_eq!(m.lat, 37.0);
                assert_eq!(mx.lon, -122.0);
            }
            _ => panic!("Expected WithinBounds query"),
        }
    }

    #[test]
    fn test_subscription_with_sync_mode() {
        let sub = Subscription::all("beacons").with_sync_mode(crate::qos::SyncMode::LatestOnly);
        assert!(sub.qos.sync_mode.is_latest_only());
    }

    #[test]
    fn test_subscription_qos_defaults() {
        let qos = SubscriptionQoS::default();
        assert!(qos.sync_mode.is_full_history());
        assert!(qos.max_documents.is_none());
        assert!(qos.update_rate_ms.is_none());
    }

    #[test]
    fn test_subscription_qos_latest_only() {
        let qos = SubscriptionQoS::latest_only();
        assert!(qos.sync_mode.is_latest_only());
    }

    #[test]
    fn test_subscription_qos_windowed() {
        let qos = SubscriptionQoS::windowed(300);
        assert!(qos.sync_mode.is_windowed());
        assert_eq!(qos.sync_mode.window_seconds(), Some(300));
    }

    #[test]
    fn test_subscription_qos_with_limits() {
        let qos = SubscriptionQoS::latest_only()
            .with_max_documents(100)
            .with_rate_limit(1000);
        assert_eq!(qos.max_documents, Some(100));
        assert_eq!(qos.update_rate_ms, Some(1000));
    }

    // === Compound query tests (Issue #357) ===

    #[test]
    fn test_query_not() {
        // Create a NOT query
        let inner = Query::Eq {
            field: "type".to_string(),
            value: Value::String("hidden".to_string()),
        };
        let not_query = Query::Not(Box::new(inner));

        match not_query {
            Query::Not(inner) => match inner.as_ref() {
                Query::Eq { field, value } => {
                    assert_eq!(field, "type");
                    assert_eq!(value, &Value::String("hidden".to_string()));
                }
                _ => panic!("Expected Eq query inside Not"),
            },
            _ => panic!("Expected Not query"),
        }
    }

    #[test]
    fn test_compound_query_not_and() {
        // NOT (type == "hidden" AND status == "deleted")
        let and_query = Query::And(vec![
            Query::Eq {
                field: "type".to_string(),
                value: Value::String("hidden".to_string()),
            },
            Query::Eq {
                field: "status".to_string(),
                value: Value::String("deleted".to_string()),
            },
        ]);
        let not_and = Query::Not(Box::new(and_query));

        match not_and {
            Query::Not(inner) => match inner.as_ref() {
                Query::And(queries) => {
                    assert_eq!(queries.len(), 2);
                }
                _ => panic!("Expected And query inside Not"),
            },
            _ => panic!("Expected Not query"),
        }
    }

    // === Dynamic subscription update tests (Issue #357) ===

    #[test]
    fn test_subscription_update_query() {
        let mut sub = Subscription::all("beacons");

        // Update to a spatial query
        sub.update_query(Query::WithinRadius {
            center: GeoPoint::new(37.7749, -122.4194),
            radius_meters: 5000.0,
            lat_field: None,
            lon_field: None,
        });

        match &sub.query {
            Query::WithinRadius { radius_meters, .. } => {
                assert_eq!(*radius_meters, 5000.0);
            }
            _ => panic!("Expected WithinRadius query"),
        }
    }

    #[test]
    fn test_subscription_update_qos() {
        let mut sub = Subscription::all("beacons");
        assert!(sub.qos.sync_mode.is_full_history());

        // Update QoS
        sub.update_qos(SubscriptionQoS::latest_only().with_max_documents(50));
        assert!(sub.qos.sync_mode.is_latest_only());
        assert_eq!(sub.qos.max_documents, Some(50));
    }

    #[test]
    fn test_subscription_update_sync_mode() {
        let mut sub = Subscription::all("beacons");
        sub.update_sync_mode(crate::qos::SyncMode::LatestOnly);
        assert!(sub.qos.sync_mode.is_latest_only());
    }

    #[test]
    fn test_subscription_update_center() {
        let mut sub =
            Subscription::within_radius("beacons", GeoPoint::new(37.7749, -122.4194), 5000.0);

        // Move center to new location
        sub.update_center(GeoPoint::new(34.0522, -118.2437)); // LA

        match &sub.query {
            Query::WithinRadius { center, .. } => {
                assert_eq!(center.lat, 34.0522);
                assert_eq!(center.lon, -118.2437);
            }
            _ => panic!("Expected WithinRadius query"),
        }
    }

    #[test]
    fn test_subscription_update_radius() {
        let mut sub =
            Subscription::within_radius("beacons", GeoPoint::new(37.7749, -122.4194), 5000.0);

        // Expand radius
        sub.update_radius(10000.0);

        match &sub.query {
            Query::WithinRadius { radius_meters, .. } => {
                assert_eq!(*radius_meters, 10000.0);
            }
            _ => panic!("Expected WithinRadius query"),
        }
    }

    #[test]
    fn test_subscription_update_center_noop_on_non_radius() {
        let mut sub = Subscription::all("beacons");

        // Should be a no-op since this isn't a radius query
        sub.update_center(GeoPoint::new(34.0522, -118.2437));

        assert!(matches!(sub.query, Query::All));
    }

    // === SyncModeMetrics tests (Issue #357) ===

    #[test]
    fn test_sync_mode_metrics_new() {
        let metrics = SyncModeMetrics::new();
        assert_eq!(metrics.total_syncs, 0);
        assert_eq!(metrics.full_history_syncs, 0);
        assert_eq!(metrics.latest_only_syncs, 0);
    }

    #[test]
    fn test_sync_mode_metrics_record_full_history() {
        let mut metrics = SyncModeMetrics::new();
        metrics.record_sync(
            "beacons",
            crate::qos::SyncMode::FullHistory,
            10000,
            std::time::Duration::from_millis(50),
        );

        assert_eq!(metrics.total_syncs, 1);
        assert_eq!(metrics.full_history_syncs, 1);
        assert_eq!(metrics.full_history_bytes, 10000);
        assert_eq!(metrics.full_history_duration_ms, 50);
    }

    #[test]
    fn test_sync_mode_metrics_record_latest_only() {
        let mut metrics = SyncModeMetrics::new();
        metrics.record_sync(
            "beacons",
            crate::qos::SyncMode::LatestOnly,
            500,
            std::time::Duration::from_millis(5),
        );

        assert_eq!(metrics.total_syncs, 1);
        assert_eq!(metrics.latest_only_syncs, 1);
        assert_eq!(metrics.latest_only_bytes, 500);
        assert_eq!(metrics.latest_only_duration_ms, 5);
    }

    #[test]
    fn test_sync_mode_metrics_bandwidth_savings() {
        let mut metrics = SyncModeMetrics::new();

        // Simulate full history sync: 30,000 bytes
        metrics.record_sync(
            "beacons",
            crate::qos::SyncMode::FullHistory,
            30000,
            std::time::Duration::from_millis(100),
        );

        // Simulate latest only sync: 100 bytes
        metrics.record_sync(
            "beacons",
            crate::qos::SyncMode::LatestOnly,
            100,
            std::time::Duration::from_millis(2),
        );

        assert_eq!(metrics.avg_full_history_bytes(), 30000.0);
        assert_eq!(metrics.avg_latest_only_bytes(), 100.0);

        // Bandwidth savings ratio should be 300x
        let ratio = metrics.bandwidth_savings_ratio().unwrap();
        assert_eq!(ratio, 300.0);
    }

    #[test]
    fn test_sync_mode_metrics_reset() {
        let mut metrics = SyncModeMetrics::new();
        metrics.record_sync(
            "beacons",
            crate::qos::SyncMode::LatestOnly,
            500,
            std::time::Duration::from_millis(5),
        );

        assert_eq!(metrics.total_syncs, 1);

        metrics.reset();

        assert_eq!(metrics.total_syncs, 0);
        assert_eq!(metrics.latest_only_syncs, 0);
    }

    #[test]
    fn test_sync_mode_metrics_windowed() {
        let mut metrics = SyncModeMetrics::new();
        metrics.record_sync(
            "track_history",
            crate::qos::SyncMode::WindowedHistory {
                window_seconds: 300,
            },
            5000,
            std::time::Duration::from_millis(20),
        );

        assert_eq!(metrics.total_syncs, 1);
        assert_eq!(metrics.windowed_syncs, 1);
        assert_eq!(metrics.windowed_bytes, 5000);
    }

    // === Deletion-aware query tests (ADR-034, Issue #369) ===

    #[test]
    fn test_query_include_deleted() {
        let inner = Query::All;
        let query = Query::IncludeDeleted(Box::new(inner));

        assert!(query.includes_deleted());
        assert!(!query.is_deleted_only());

        match query.inner_query() {
            Query::All => {}
            _ => panic!("Expected All query inside IncludeDeleted"),
        }
    }

    #[test]
    fn test_query_deleted_only() {
        let query = Query::DeletedOnly;

        assert!(query.includes_deleted());
        assert!(query.is_deleted_only());
    }

    #[test]
    fn test_query_with_deleted() {
        // Normal query should be wrapped
        let query = Query::All;
        let wrapped = query.with_deleted();
        assert!(matches!(wrapped, Query::IncludeDeleted(_)));

        // Already wrapped should stay the same
        let already_wrapped = Query::IncludeDeleted(Box::new(Query::All));
        let still_wrapped = already_wrapped.with_deleted();
        assert!(matches!(still_wrapped, Query::IncludeDeleted(_)));

        // DeletedOnly should stay the same
        let deleted_only = Query::DeletedOnly;
        let still_deleted_only = deleted_only.with_deleted();
        assert!(matches!(still_deleted_only, Query::DeletedOnly));
    }

    #[test]
    fn test_query_matches_deletion_state_normal() {
        let query = Query::All;

        // Non-deleted document should match
        let mut non_deleted = Document::new(HashMap::new());
        non_deleted.set("name", Value::String("test".to_string()));
        assert!(query.matches_deletion_state(&non_deleted));

        // Deleted document should NOT match
        let mut deleted = Document::new(HashMap::new());
        deleted.set("name", Value::String("test".to_string()));
        deleted.set("_deleted", Value::Bool(true));
        assert!(!query.matches_deletion_state(&deleted));

        // _deleted=false should match
        let mut not_deleted = Document::new(HashMap::new());
        not_deleted.set("_deleted", Value::Bool(false));
        assert!(query.matches_deletion_state(&not_deleted));
    }

    #[test]
    fn test_query_matches_deletion_state_include_deleted() {
        let query = Query::IncludeDeleted(Box::new(Query::All));

        // Non-deleted document should match
        let non_deleted = Document::new(HashMap::new());
        assert!(query.matches_deletion_state(&non_deleted));

        // Deleted document should also match
        let mut deleted = Document::new(HashMap::new());
        deleted.set("_deleted", Value::Bool(true));
        assert!(query.matches_deletion_state(&deleted));
    }

    #[test]
    fn test_query_matches_deletion_state_deleted_only() {
        let query = Query::DeletedOnly;

        // Non-deleted document should NOT match
        let non_deleted = Document::new(HashMap::new());
        assert!(!query.matches_deletion_state(&non_deleted));

        // Deleted document should match
        let mut deleted = Document::new(HashMap::new());
        deleted.set("_deleted", Value::Bool(true));
        assert!(query.matches_deletion_state(&deleted));

        // _deleted=false should NOT match
        let mut not_deleted = Document::new(HashMap::new());
        not_deleted.set("_deleted", Value::Bool(false));
        assert!(!query.matches_deletion_state(&not_deleted));
    }

    #[test]
    fn test_query_include_deleted_with_filter() {
        // IncludeDeleted wrapping a more complex query
        let inner = Query::Eq {
            field: "type".to_string(),
            value: Value::String("contact_report".to_string()),
        };
        let query = Query::IncludeDeleted(Box::new(inner));

        assert!(query.includes_deleted());

        match query.inner_query() {
            Query::Eq { field, value } => {
                assert_eq!(field, "type");
                assert_eq!(value, &Value::String("contact_report".to_string()));
            }
            _ => panic!("Expected Eq query inside IncludeDeleted"),
        }
    }

    #[test]
    fn test_query_normal_excludes_deleted() {
        // All query variants (except IncludeDeleted/DeletedOnly) should exclude deleted docs
        let queries = vec![
            Query::All,
            Query::Eq {
                field: "x".to_string(),
                value: Value::Null,
            },
            Query::And(vec![Query::All]),
            Query::Or(vec![Query::All]),
            Query::Not(Box::new(Query::All)),
        ];

        let mut deleted_doc = Document::new(HashMap::new());
        deleted_doc.set("_deleted", Value::Bool(true));

        for query in queries {
            assert!(
                !query.matches_deletion_state(&deleted_doc),
                "Query {:?} should exclude deleted docs",
                query
            );
        }
    }
}