tnuctipun 0.2.0

The Tnuctipun of Ringworld — ancient, subversive, ingenious — or a type-safe MongoDB builder library
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
use crate::expr::Expr;
use crate::field_filters::FieldFilterBuilder;
use crate::field_witnesses::{FieldName, HasField};
use crate::mongo_comparable::{MongoComparable, MongoOrdered};
use crate::path::Path;
use bson;

/// A builder for constructing MongoDB filters with type safety.
///
/// This builder provides a fluent interface for creating complex MongoDB queries
/// while ensuring at compile time that fields exist and have compatible types.
///
/// The builder can be used to chain multiple filter conditions together,
/// and provides methods to combine them using MongoDB's `$and` semantics.
///
/// # Type Parameters
///
/// * `T` - The struct type that this filter builder operates on (e.g., `User`, `Product`)
pub struct FilterBuilder<T> {
    prefix: Vec<String>,
    clauses: Vec<bson::Document>,
    _marker: std::marker::PhantomData<T>,
}

impl<T> FilterBuilder<T> {
    /// Creates a new empty FilterBuilder instance.
    ///
    /// Notes: Prefer using the `the `empty` function.
    ///
    /// # Example
    ///
    /// ```rust
    /// use tnuctipun::filters::FilterBuilder;
    /// use tnuctipun::FieldWitnesses;
    /// use serde::{Serialize, Deserialize};
    ///
    /// #[derive(Debug, Clone, Serialize, Deserialize, FieldWitnesses)]
    /// struct User { pub Name: String }
    ///
    /// let builder = FilterBuilder::<User>::new();
    /// ```
    pub fn new() -> Self {
        Self {
            prefix: Vec::new(),
            clauses: Vec::new(),
            _marker: std::marker::PhantomData,
        }
    }

    /// Returns a fully qualified field path for the given field name marker type.
    fn field_path<F: FieldName>(&self) -> String {
        if self.prefix.is_empty() {
            F::field_name().to_string()
        } else {
            format!("{}.{}", self.prefix.join("."), F::field_name())
        }
    }

    /// Creates a type-safe equality filter (`$eq`) that checks at compile time if the field exists
    /// and has the correct type or a compatible type.
    ///
    /// # Type parameters:
    /// * `F` - The field name marker type (e.g., `user_fields::Name`)
    /// * `V` - The type of the field value or a compatible type
    ///
    /// # Example
    ///
    /// ```rust
    /// use tnuctipun::{FieldWitnesses, MongoComparable};
    /// use tnuctipun::filters::empty;
    /// use serde::{Serialize, Deserialize};
    ///
    /// #[derive(Debug, Clone, Serialize, Deserialize, FieldWitnesses, MongoComparable)]
    /// struct User { pub Name: String, pub Age: i32 }
    ///
    /// // Using builder pattern with efficient chaining:
    /// empty::<User>().eq::<user_fields::Name, _>("John".to_string());
    /// ```
    pub fn eq<F, V>(&mut self, value: V) -> &mut Self
    where
        F: FieldName,
        T: HasField<F> + MongoComparable<T::Value, V>,
        V: Into<bson::Bson> + Clone,
    {
        let path = self.field_path::<F>();

        self.clauses.push(bson::doc! { path: value.into() });

        self
    }

    /// Creates a type-safe version of MongoDB's regular expression (`$regex`) filter.
    ///
    /// This method allows you to filter documents based on pattern matching using regular expressions.
    /// It's particularly useful for text searches, partial matches, and complex string pattern filtering.
    ///
    /// # Type parameters:
    /// * `F` - The field name marker type (e.g., `user_fields::Name`)
    ///
    /// # Arguments
    /// * `expr` - The regular expression pattern as a string
    /// * `options` - Optional regex options (None for no options, Some("i") for case-insensitive, etc.)
    ///
    /// # MongoDB Regex Behavior
    ///
    /// The `$regex` operator provides regular expression capabilities for pattern matching strings in queries.
    /// MongoDB uses Perl Compatible Regular Expressions (PCRE) version 8.42 with UTF-8 support.
    ///
    /// # Common Use Cases
    ///
    /// - **Case-insensitive search**: Use regex options like `Some("i")`
    /// - **Partial matches**: Search for substrings within field values
    /// - **Pattern validation**: Match specific formats (emails, phone numbers, etc.)
    /// - **Wildcard searches**: Use `.*` for flexible matching
    ///
    /// # Example
    ///
    /// ```rust
    /// use tnuctipun::filters::empty;
    /// use tnuctipun::{FieldWitnesses, MongoComparable};
    /// use serde::{Serialize, Deserialize};
    ///
    /// #[derive(Debug, Clone, Serialize, Deserialize, FieldWitnesses, MongoComparable)]
    /// struct User {
    ///     pub name: String,
    ///     pub email: String,
    /// }
    ///
    /// // Case-insensitive search for names containing "john"
    /// empty::<User>().regex::<user_fields::Name>("john", Some("i"));
    /// // Resulting BSON: { "name": { "$regex": "john", "$options": "i" } }
    ///
    /// // Email validation pattern (no options)
    /// empty::<User>().regex::<user_fields::Email>(r"^[\w\.-]+@[\w\.-]+\.\w+$", None);
    /// // Resulting BSON: { "email": { "$regex": "^[\\w\\.-]+@[\\w\\.-]+\\.\\w+$" } }
    ///
    /// // Partial match for product names starting with "Laptop"
    /// empty::<User>().regex::<user_fields::Name>("^Laptop.*", None);
    /// // Resulting BSON: { "name": { "$regex": "^Laptop.*" } }
    /// ```
    ///
    /// # Advanced Regex Options
    ///
    /// For more complex regex queries with options, use the `Some()` wrapper:
    ///
    /// ```rust
    /// use tnuctipun::filters::empty;
    /// # use tnuctipun::{FieldWitnesses, MongoComparable};
    /// # use serde::{Serialize, Deserialize};
    /// # #[derive(Debug, Clone, Serialize, Deserialize, FieldWitnesses, MongoComparable)]
    /// # struct User { pub name: String }
    ///
    /// // Case-insensitive and multiline options
    /// empty::<User>().regex::<user_fields::Name>("pattern", Some("im"));
    /// // Resulting BSON: { "name": { "$regex": "pattern", "$options": "im" } }
    /// ```
    ///
    /// # Common Regex Patterns
    ///
    /// | Pattern | Description | Example |
    /// |---------|-------------|---------|
    /// | `^text` | Starts with "text" | `^Hello` matches "Hello World" |
    /// | `text$` | Ends with "text" | `World$` matches "Hello World" |
    /// | `.*text.*` | Contains "text" | `.*cat.*` matches "concatenate" |
    /// | `(?i)text` | Case-insensitive (inline) | `(?i)hello` matches "HELLO" |
    /// | `\d+` | One or more digits | `\d+` matches "123" |
    /// | `[a-zA-Z]+` | Letters only | Matches alphabetic strings |
    ///
    /// # Regex Options
    ///
    /// MongoDB supports these regex options (passed as Some("options")):
    /// - `i` - Case insensitive matching
    /// - `m` - Multiline mode (^ and $ match line boundaries)
    /// - `x` - Extended mode (ignore whitespace and allow comments)
    /// - `s` - Dotall mode (. matches newlines)
    ///
    /// Options can be combined: `Some("im")` for case-insensitive multiline.
    ///
    /// # Type Safety
    ///
    /// This method ensures compile-time verification that:
    /// - The field `F` exists in the struct `T`
    /// - The field is compatible with regex operations (typically String fields)
    pub fn regex<F: FieldName>(&mut self, expr: &str, options: Option<&str>) -> &mut Self
    where
        T: HasField<F>,
    {
        let path = self.field_path::<F>();
        let mut regex_doc = bson::doc! { "$regex": expr };

        if let Some(opts) = options
            && !opts.is_empty()
        {
            regex_doc.insert("$options", opts);
        }

        self.clauses.push(bson::doc! { path: regex_doc });

        self
    }

    /// Returns the current filter clauses as a vector of BSON documents.
    pub fn clauses(&self) -> &Vec<bson::Document> {
        &self.clauses
    }

    /// Creates a type-safe version of MongoDB's greater than (`$gt`) filter.
    ///
    /// # Type parameters:
    /// * `F` - The field name marker type (e.g., `product_fields::Price`)
    /// * `V` - The type of the field value or a compatible type
    ///
    /// The comparison requires both `MongoComparable` and `MongoOrdered`
    /// evidence for the field/value type pair.
    ///
    /// # Example
    ///
    /// ```rust
    /// use tnuctipun::filters::empty;
    /// use tnuctipun::{FieldWitnesses, MongoComparable};
    /// use serde::{Serialize, Deserialize};
    ///
    /// #[derive(Debug, Clone, Serialize, Deserialize, FieldWitnesses, MongoComparable)]
    /// struct Product { pub Price: f64 }
    ///
    /// // Filter for products with price > 500
    /// empty::<Product>().gt::<product_fields::Price, _>(500.0);
    /// // Resulting BSON: { "Price": { "$gt": 500.0 } }
    /// ```
    pub fn gt<F, V>(&mut self, value: V) -> &mut Self
    where
        F: FieldName,
        T: HasField<F> + MongoComparable<T::Value, V> + MongoOrdered<T::Value, V>,
        V: Into<bson::Bson> + Clone,
    {
        let path = self.field_path::<F>();

        self.clauses
            .push(bson::doc! { path: { "$gt": value.into() } });

        self
    }

    /// Creates a type-safe version of MongoDB's less (`$lt`) than filter.
    ///
    /// # Type parameters:
    /// * `F` - The field name marker type (e.g., `product_fields::Stock`)
    /// * `V` - The type of the field value or a compatible type
    ///
    /// The comparison requires both `MongoComparable` and `MongoOrdered`
    /// evidence for the field/value type pair.
    ///
    /// # Example
    ///
    /// ```rust
    /// use tnuctipun::filters::empty;
    /// use tnuctipun::{FieldWitnesses, MongoComparable};
    /// use serde::{Serialize, Deserialize};
    ///
    /// #[derive(Debug, Clone, Serialize, Deserialize, FieldWitnesses, MongoComparable)]
    /// struct Product { pub Stock: i32 }
    ///
    /// // Filter for products with stock < 10
    /// empty::<Product>().lt::<product_fields::Stock, _>(10);
    /// // Resulting BSON: { "Stock": { "$lt": 10 } }
    /// ```
    pub fn lt<F, V>(&mut self, value: V) -> &mut Self
    where
        F: FieldName,
        T: HasField<F> + MongoComparable<T::Value, V> + MongoOrdered<T::Value, V>,
        V: Into<bson::Bson> + Clone,
    {
        let path = self.field_path::<F>();

        self.clauses
            .push(bson::doc! { path: { "$lt": value.into() } });

        self
    }

    /// Type-safe version of "in" operator filter
    ///
    /// Creates a MongoDB filter that matches any of the values in the provided array.
    ///
    /// # Type parameters:
    /// * `F` - The field name marker type (e.g., `user_fields::Age`)
    /// * `V` - The type of the field value or a compatible type
    ///
    /// # Example
    ///
    /// ```rust
    /// use tnuctipun::filters::empty;
    /// use tnuctipun::{FieldWitnesses, MongoComparable};
    /// use serde::{Serialize, Deserialize};
    ///
    /// #[derive(Debug, Clone, Serialize, Deserialize, FieldWitnesses, MongoComparable)]
    /// struct User { pub Age: i32 }
    ///
    /// // Filter for users with age in [20, 30, 40]
    /// empty::<User>().r#in::<user_fields::Age, _>(vec![20, 30, 40]);
    /// // Resulting BSON: { "Age": { "$in": [20, 30, 40] } }
    /// ```
    pub fn r#in<F, V>(&mut self, values: Vec<V>) -> &mut Self
    where
        F: FieldName,
        T: HasField<F> + MongoComparable<T::Value, V>,
        V: Into<bson::Bson> + Clone,
    {
        let path = self.field_path::<F>();
        let bson_values: Vec<bson::Bson> = values.into_iter().map(|v| v.into()).collect();

        self.clauses
            .push(bson::doc! { path: { "$in": bson_values } });

        self
    }

    /// Creates a type-safe version of MongoDB's "not equal" (`$ne`) filter.
    ///
    /// # Type parameters:
    /// * `F` - The field name marker type (e.g., `order_fields::Status`)
    /// * `V` - The type of the field value or a compatible type
    ///
    /// # Example
    ///
    /// ```rust
    /// use tnuctipun::filters::empty;
    /// use tnuctipun::{FieldWitnesses, MongoComparable};
    /// use serde::{Serialize, Deserialize};
    ///
    /// #[derive(Debug, Clone, Serialize, Deserialize, FieldWitnesses, MongoComparable)]
    /// struct Order { pub Status: String }
    ///
    /// // Filter for orders with status not equal to "Delivered"
    /// empty::<Order>().ne::<order_fields::Status, _>("Delivered".to_string());
    /// // Resulting BSON: { "Status": { "$ne": "Delivered" } }
    /// ```
    pub fn ne<F, V>(&mut self, value: V) -> &mut Self
    where
        F: FieldName,
        T: HasField<F> + MongoComparable<T::Value, V>,
        V: Into<bson::Bson> + Clone,
    {
        let path = self.field_path::<F>();

        self.clauses
            .push(bson::doc! { path: { "$ne": value.into() } });

        self
    }

    /// Creates a type-safe version of MongoDB's "greater than or equal" (`$gte`) filter.
    ///
    /// # Type parameters:
    /// * `F` - The field name marker type (e.g., `product_fields::Rating`)
    /// * `V` - The type of the field value or a compatible type
    ///
    /// The comparison requires both `MongoComparable` and `MongoOrdered`
    /// evidence for the field/value type pair.
    ///
    /// # Example
    ///
    /// ```rust
    /// use tnuctipun::filters::empty;
    /// use tnuctipun::{FieldWitnesses, MongoComparable};
    /// use serde::{Serialize, Deserialize};
    ///
    /// #[derive(Debug, Clone, Serialize, Deserialize, FieldWitnesses, MongoComparable)]
    /// struct Product { pub Rating: f64 }
    ///
    /// // Filter for products with rating >= 4.5
    /// empty::<Product>().gte::<product_fields::Rating, _>(4.5);
    /// // Resulting BSON: { "Rating": { "$gte": 4.5 } }
    /// ```
    pub fn gte<F, V>(&mut self, value: V) -> &mut Self
    where
        F: FieldName,
        T: HasField<F> + MongoComparable<T::Value, V> + MongoOrdered<T::Value, V>,
        V: Into<bson::Bson> + Clone,
    {
        let path = self.field_path::<F>();

        self.clauses
            .push(bson::doc! { path: { "$gte": value.into() } });

        self
    }

    /// Creates a type-safe version of MongoDB's "less than or equal" (`$lte`) filter.
    ///
    /// # Type parameters:
    /// * `F` - The field name marker type (e.g., `product_fields::Price`)
    /// * `V` - The type of the field value or a compatible type
    ///
    /// The comparison requires both `MongoComparable` and `MongoOrdered`
    /// evidence for the field/value type pair.
    ///
    /// # Example
    ///
    /// ```rust
    /// use tnuctipun::filters::empty;
    /// use tnuctipun::{FieldWitnesses, MongoComparable};
    /// use serde::{Serialize, Deserialize};
    ///
    /// #[derive(Debug, Clone, Serialize, Deserialize, FieldWitnesses, MongoComparable)]
    /// struct Product { pub Price: f64 }
    ///
    /// // Filter for products with price <= 100.0
    /// empty::<Product>().lte::<product_fields::Price, _>(100.0);
    /// // Resulting BSON: { "Price": { "$lte": 100.0 } }
    /// ```
    pub fn lte<F, V>(&mut self, value: V) -> &mut Self
    where
        F: FieldName,
        T: HasField<F> + MongoComparable<T::Value, V> + MongoOrdered<T::Value, V>,
        V: Into<bson::Bson> + Clone,
    {
        let path = self.field_path::<F>();

        self.clauses
            .push(bson::doc! { path: { "$lte": value.into() } });

        self
    }

    /// Creates a type-safe version of "exists" filter, that checks if a field exists in the document.
    ///
    /// # Type parameters:
    /// * `F` - The field name marker type (e.g., `user_fields::OptionalField`)
    ///   (must implement `HasField<F>` to ensure compile-time field existence)
    ///
    /// # Example
    ///
    /// ```rust
    /// use tnuctipun::filters::empty;
    /// use tnuctipun::FieldWitnesses;
    /// use serde::{Serialize, Deserialize};
    ///
    /// #[derive(Debug, Clone, Serialize, Deserialize, FieldWitnesses)]
    /// struct User {
    ///     pub Name: String,
    ///     pub PhoneNumber: Option<String>
    /// }
    ///
    /// // Filter for users that have a phone number
    /// empty::<User>().exists::<user_fields::PhoneNumber>(true);
    /// // Resulting BSON: { "PhoneNumber": { "$exists": true } }
    ///
    /// // Filter for users without a phone number
    /// empty::<User>().exists::<user_fields::PhoneNumber>(false);
    /// // Resulting BSON: { "PhoneNumber": { "$exists": false } }
    /// ```
    pub fn exists<F>(&mut self, exists: bool) -> &mut Self
    where
        F: FieldName,
        T: HasField<F>,
    {
        let path = self.field_path::<F>();

        self.clauses
            .push(bson::doc! { path: { "$exists": exists } });

        self
    }

    /// Creates a type-safe version of MongoDB's "not in" (`$nin`) operator filter,
    /// that matches values NOT in the provided array.
    ///
    /// # Type parameters:
    /// * `F` - The field name marker type (e.g., `product_fields::Category`)
    /// * `V` - The type of the field value or a compatible type
    ///
    /// # Example
    ///
    /// ```rust
    /// use tnuctipun::filters::empty;
    /// use tnuctipun::{FieldWitnesses, MongoComparable};
    /// use serde::{Serialize, Deserialize};
    ///
    /// #[derive(Debug, Clone, Serialize, Deserialize, FieldWitnesses, MongoComparable)]
    /// struct Product { pub Category: String }
    ///
    /// // Filter for products NOT in the categories "Clothing", "Shoes", or "Accessories"
    /// empty::<Product>().nin::<product_fields::Category, _>(vec![
    ///     "Clothing".to_string(),
    ///     "Shoes".to_string(),
    ///     "Accessories".to_string()
    /// ]);
    /// // Resulting BSON: { "Category": { "$nin": ["Clothing", "Shoes", "Accessories"] } }
    /// ```
    pub fn nin<F, V>(&mut self, values: Vec<V>) -> &mut Self
    where
        F: FieldName,
        T: HasField<F> + MongoComparable<T::Value, V>,
        V: Into<bson::Bson> + Clone,
    {
        let path = self.field_path::<F>();
        let bson_values: Vec<bson::Bson> = values.into_iter().map(|v| v.into()).collect();

        self.clauses
            .push(bson::doc! { path: { "$nin": bson_values } });

        self
    }

    /// Creates an untyped filter for a field using a raw BSON document.
    ///
    /// This method allows you to partially bypass the type safety mechanisms for the sake of flexibility,
    /// and directly insert a BSON document as the filter condition for a specific field. While this provides
    /// maximum flexibility for complex queries, it should be used with caution as it
    /// sacrifices the compile-time type checking that other methods provide.
    ///
    /// # Type parameters:
    /// * `F` - The field name marker type (e.g., `product_fields::Price`)
    ///
    /// # Arguments
    /// * `value` - A BSON document containing the MongoDB operators and values to apply to the field
    ///
    /// # Use Cases
    ///
    /// This method is particularly useful for:
    ///
    /// - Advanced MongoDB operators not yet covered by typed methods
    /// - Complex nested conditions that require manual BSON construction
    /// - Migration scenarios where you need to use existing raw query fragments
    /// - Testing and experimentation with MongoDB features
    ///
    /// # Safety Considerations
    ///
    /// - No compile-time validation of field types or operator compatibility
    /// - Potential runtime errors if the BSON structure is invalid
    /// - Field existence is still verified at compile time through `HasField<F>`
    ///
    /// # Example
    ///
    /// ```rust
    /// use tnuctipun::filters::empty;
    /// use tnuctipun::{FieldWitnesses, MongoComparable};
    /// use serde::{Serialize, Deserialize};
    /// use bson::{doc, Document};
    ///
    /// #[derive(Debug, Clone, Serialize, Deserialize, FieldWitnesses, MongoComparable)]
    /// struct Product {
    ///     pub name: String,
    ///     pub price: f64,
    ///     pub tags: Vec<String>,
    /// }
    ///
    /// // Using advanced text search operators
    /// let text_search = doc! {
    ///     "$regex": "laptop",
    ///     "$options": "i"
    /// };
    /// empty::<Product>().untyped::<product_fields::Name>(text_search);
    /// // Resulting BSON: { "name": { "$regex": "laptop", "$options": "i" } }
    ///
    /// // Using complex array operators
    /// let array_condition = doc! {
    ///     "$elemMatch": {
    ///         "$regex": "electronics",
    ///         "$options": "i"
    ///     }
    /// };
    /// empty::<Product>().untyped::<product_fields::Tags>(array_condition);
    /// // Resulting BSON: { "tags": { "$elemMatch": { "$regex": "electronics", "$options": "i" } } }
    ///
    /// // Combining with typed methods
    /// empty::<Product>()
    ///     .gt::<product_fields::Price, _>(100.0)  // Type-safe
    ///     .untyped::<product_fields::Name>(doc! { "$exists": true });  // Untyped
    /// ```
    ///
    /// # MongoDB Expression Support
    ///
    /// This method can be used with any MongoDB query operator, including:
    /// - Text search: `$regex`, `$text`
    /// - Array operations: `$elemMatch`, `$size`, `$all`
    /// - Geospatial: `$near`, `$geoWithin`, `$geoIntersects`
    /// - Advanced comparison: `$mod`, `$type`
    /// - Custom aggregation expressions in `$expr`
    pub fn untyped<F: FieldName>(&mut self, value: bson::Document) -> &mut Self
    where
        T: HasField<F>,
    {
        let path = self.field_path::<F>();

        self.clauses.push(bson::doc! { path: value });

        self
    }

    /// Adds a MongoDB `$expr` clause built from a typed expression.
    pub fn expr(&mut self, expr: Expr<T, bool>) -> &mut Self {
        self.clauses.push(bson::doc! { "$expr": expr.into_bson() });

        self
    }

    /// Creates filters for nested fields within documents using a path-based lookup approach.
    /// This method provides explicit control over field path construction,
    /// allowing you to specify exactly which nested field to target through a lookup function.
    ///
    /// # Type parameters:
    /// * `F` - The field name marker type for the base field (e.g., `user_fields::HomeAddress`)
    /// * `L` - The lookup function type that resolves the field path
    /// * `G` - The field name marker type for the target nested field (e.g., `address_fields::City`)
    /// * `U` - The type of the nested structure containing the target field
    /// * `N` - The closure that builds filters on the nested FilterBuilder
    ///
    /// # Arguments
    /// * `lookup` - A function that takes a `Path<F, T, T>` and returns a `Path<G, U, T>` to specify the target field
    /// * `f` - A closure that builds filter conditions on the resolved nested field
    ///
    /// # Note
    /// For simpler cases where you want to filter on the field itself (identity lookup),
    /// consider using the `with_field` method instead, which is more concise.
    ///
    /// # Example
    ///
    /// ```rust
    /// use tnuctipun::filters::empty;
    /// use tnuctipun::{FieldWitnesses, MongoComparable};
    /// use serde::{Serialize, Deserialize};
    ///
    /// #[derive(Debug, Clone, Serialize, Deserialize, FieldWitnesses, MongoComparable)]
    /// struct Address {
    ///     pub Street: String,
    ///     pub City: String,
    ///     pub ZipCode: String,
    /// }
    ///
    /// #[derive(Debug, Clone, Serialize, Deserialize, FieldWitnesses, MongoComparable)]
    /// struct User {
    ///     pub Name: String,
    ///     pub HomeAddress: Address,
    /// }
    ///
    /// // Using field navigation for accessing nested fields (G≠F, U≠T)
    /// let mut builder = empty::<User>().with_lookup::<user_fields::HomeAddress, _, address_fields::City, Address, _>(
    ///     |path| path.field::<address_fields::City>(),
    ///     |nested| {
    ///         nested.eq::<address_fields::City, _>("New York".to_string())
    ///     }
    /// );
    /// // Resulting BSON: { "HomeAddress.City": "New York" }
    ///
    /// // For identity cases (filtering on the field itself), prefer with_field():
    /// // builder.with_field::<user_fields::HomeAddress, _>(|nested| {
    /// //     nested.exists::<user_fields::HomeAddress>(true)
    /// // });
    /// // Resulting BSON: { "HomeAddress": { "$exists": true } }
    /// ```
    pub fn with_lookup<F: FieldName, L, G: FieldName, U: HasField<G>, N>(
        &mut self,
        lookup: L,
        f: N,
    ) -> &mut Self
    where
        T: HasField<F>,
        L: FnOnce(&Path<F, T, T>) -> Path<G, U, T>,
        N: FnOnce(&mut FilterBuilder<U>) -> &mut FilterBuilder<U>,
    {
        // Create a base field path for the lookup
        let base_field: Path<F, T, T> = Path {
            prefix: self.prefix.clone(),
            _marker: std::marker::PhantomData,
        };

        // Resolve the field path using the provided lookup function
        let resolved_field = lookup(&base_field);

        // Create a new FilterBuilder for the nested field
        let mut nested_builder = FilterBuilder::<U> {
            prefix: resolved_field.prefix.clone(),
            clauses: vec![],
            _marker: std::marker::PhantomData,
        };

        f(&mut nested_builder);

        // Add the nested clauses individually to the main builder
        self.clauses.extend(nested_builder.clauses);

        self
    }

    /// Convenience method for filtering on a field directly (using identity lookup).
    ///
    /// Notes: This is a specialized version of `with_lookup` that uses `std::convert::identity`
    /// as the lookup function, making it easier to apply filters directly to a field
    /// without needing to specify the identity function explicitly.
    ///
    /// # Type parameters:
    /// * `F` - The field name marker type (e.g., `user_fields::HomeAddress`)
    /// * `N` - The closure that builds filters on the field
    ///
    /// # Arguments
    /// * `f` - A closure that builds filter conditions on the field
    ///
    /// # Example
    ///
    /// ```rust
    /// use tnuctipun::filters::empty;
    /// use tnuctipun::{FieldWitnesses, MongoComparable};
    /// use serde::{Serialize, Deserialize};
    ///
    /// #[derive(Debug, Clone, Serialize, Deserialize, FieldWitnesses, MongoComparable)]
    /// struct User {
    ///     pub Name: String,
    ///     pub HomeAddress: String,
    /// }
    ///
    /// let mut builder = empty::<User>().with_field::<user_fields::HomeAddress, _>(|nested| {
    ///     nested.exists::<user_fields::HomeAddress>(true)
    /// });
    /// // Resulting BSON: { "HomeAddress": { "$exists": true } }
    /// ```
    pub fn with_field<F: FieldName, N>(&mut self, f: N) -> &mut Self
    where
        T: HasField<F>,
        N: FnOnce(&mut FilterBuilder<T>) -> &mut FilterBuilder<T>,
    {
        self.with_lookup::<F, _, F, T, _>(
            |path| Path {
                prefix: path.prefix.clone(),
                _marker: std::marker::PhantomData,
            },
            f,
        )
    }

    /// Create a type-safe version of MongoDB's "$or" operator,
    /// where each clause is generated by applying a closure to each item in the input iterable.
    ///
    /// # Type parameters:
    /// * `F` - The field name marker type (e.g., `product_fields::Category`)
    /// * `V` - An iterable type containing values to process
    /// * `N` - A closure that takes a FilterBuilder and an item from V, and returns the FilterBuilder
    ///
    /// # Arguments
    ///
    /// * `input` - An iterable collection of values to process
    /// * `f` - A closure that builds filter conditions for each value in the input
    ///
    /// # Example
    ///
    /// ```rust
    /// use tnuctipun::filters::empty;
    /// use tnuctipun::{FieldWitnesses, MongoComparable};
    /// use serde::{Serialize, Deserialize};
    ///
    /// #[derive(Debug, Clone, Serialize, Deserialize, FieldWitnesses, MongoComparable)]
    /// struct Product {
    ///     pub name: String,
    ///     pub category: String,
    ///     pub price: f64,
    /// }
    ///
    /// // Filter for products that match any of the given names
    /// let names = vec!["Laptop", "Smartphone", "Tablet"];
    ///
    /// empty::<Product>().or::<product_fields::Name, _, _>(names, |filter, name| {
    ///     filter.eq::<product_fields::Name, _>(name.to_string())
    /// });
    ///
    /// // Resulting BSON:
    /// // { "$or": [
    /// //     { "name": "Laptop" },
    /// //     { "name": "Smartphone" },
    /// //     { "name": "Tablet" }
    /// // ]}
    /// ```
    ///
    /// # Complex Example with Multiple Conditions
    ///
    /// ```rust
    /// use tnuctipun::filters::empty;
    /// use tnuctipun::{FieldWitnesses, MongoComparable};
    /// use serde::{Serialize, Deserialize};
    ///
    /// #[derive(Debug, Clone, Serialize, Deserialize, FieldWitnesses, MongoComparable)]
    /// struct Product {
    ///     pub name: String,
    ///     pub category: String,
    ///     pub price: f64,
    /// }
    ///
    /// // Filter for products in specific price ranges
    /// let price_ranges = vec![(0.0, 100.0), (500.0, 1000.0), (2000.0, 5000.0)];
    ///
    /// empty::<Product>().or::<product_fields::Price, _, _>(price_ranges, |filter, (min, max)| {
    ///     filter.gte::<product_fields::Price, _>(min)
    ///           .lte::<product_fields::Price, _>(max)
    /// });
    ///
    /// // Resulting BSON (note: multiple clauses from each iteration are flattened):
    /// // { "$or": [
    /// //     { "price": { "$gte": 0.0 } },
    /// //     { "price": { "$lte": 100.0 } },
    /// //     { "price": { "$gte": 500.0 } },
    /// //     { "price": { "$lte": 1000.0 } },
    /// //     { "price": { "$gte": 2000.0 } },
    /// //     { "price": { "$lte": 5000.0 } }
    /// // ]}
    /// ```
    pub fn or<F, V: IntoIterator, N>(&mut self, input: V, f: N) -> &mut Self
    where
        F: FieldName,
        T: HasField<F>,
        N: Fn(&mut FilterBuilder<T>, V::Item) -> &mut FilterBuilder<T>,
    {
        let mut nested = empty::<T>();
        let mut or_clauses: Vec<bson::Document> = vec![];

        for value in input {
            f(&mut nested, value);

            match nested.clauses.len() {
                0 => continue, // Skip empty nested clauses
                1 => or_clauses.push(nested.clauses.clone().into_iter().next().unwrap()),
                _ => or_clauses.extend(nested.clauses.clone()),
            }

            nested.clauses.clear(); // Clear for next iteration
        }

        self.clauses.push(bson::doc! { "$or": or_clauses });

        self
    }

    /// Create a type-safe version of MongoDB's "$not" operator.
    ///
    /// Such MongoDB filter negates operations on a specific field.
    /// This method uses a `FieldFilterBuilder` to construct the operations to be negated.
    ///
    /// # Type parameters:
    /// * `F` - The field name marker type (e.g., `product_fields::Price`)
    /// * `B` - A closure that takes a `FieldFilterBuilder` and returns it with configured operations
    ///
    /// # Arguments
    /// * `f` - A closure that builds the operations to be negated using the `FieldFilterBuilder`
    ///
    /// # Example
    ///
    /// ```rust
    /// use tnuctipun::filters::empty;
    /// use tnuctipun::{FieldWitnesses, MongoComparable};
    /// use serde::{Serialize, Deserialize};
    ///
    /// #[derive(Debug, Clone, Serialize, Deserialize, FieldWitnesses, MongoComparable)]
    /// struct Product {
    ///     pub name: String,
    ///     pub price: f64,
    ///     pub category: String,
    /// }
    ///
    /// // Filter for products where the name is NOT "Smartphone"
    /// empty::<Product>().not::<product_fields::Name, _>(|op| {
    ///     op.eq("Smartphone".to_string())
    /// });
    /// // Resulting BSON: { "name": { "$not": { "$eq": "Smartphone" } } }
    ///
    /// // Filter for products where the price is NOT equal to 500.0
    /// empty::<Product>().not::<product_fields::Price, _>(|op| {
    ///     op.eq(500.0)
    /// });
    /// // Resulting BSON: { "price": { "$not": { "$eq": 500.0 } } }
    /// ```
    ///
    /// # MongoDB Behavior
    ///
    /// The `$not` operator in MongoDB performs logical NOT operation on the specified expression.
    /// It can be used to negate the result of any MongoDB expression, including:
    ///
    /// - Equality checks
    /// - Range queries  
    /// - Pattern matching
    /// - Other conditional expressions
    ///
    /// Note that `$not` affects the semantics of the query and can behave differently than
    /// using `$ne` (not equal) for simple equality checks, especially with missing fields.
    pub fn not<F, B>(&mut self, f: B) -> &mut Self
    where
        F: FieldName,
        T: HasField<F>,
        B: FnOnce(FieldFilterBuilder<F, T>) -> FieldFilterBuilder<F, T>,
    {
        let prepared_ops = f(FieldFilterBuilder::new()).build();
        let bson_path = self.field_path::<F>();

        if let Ok(ops) = prepared_ops.get_document(F::field_name()) {
            self.clauses
                .push(bson::doc! { bson_path: bson::doc! { "$not": ops.clone() } });
        }

        self
    }

    /// Combines all clauses into a single BSON document,
    /// according to the MongoDB `$and` semantics.
    ///
    /// - If no clauses exist, returns an empty document `{}`
    /// - If only one clause exists, returns that clause directly
    /// - If multiple clauses exist, wraps them in a `$and` array
    ///
    /// This method borrows the builder, allowing you to continue using it afterwards.
    ///
    /// # Example
    ///
    /// ```rust
    /// use tnuctipun::filters::empty;
    /// use tnuctipun::{FieldWitnesses, MongoComparable};
    /// use serde::{Serialize, Deserialize};
    ///
    /// #[derive(Debug, Clone, Serialize, Deserialize, FieldWitnesses, MongoComparable)]
    /// struct User {
    ///     pub name: String,
    ///     pub age: i32,
    ///     pub email: String,
    /// }
    ///
    /// let filter = empty::<User>()
    ///     .eq::<user_fields::Name, _>("John Doe".to_string())
    ///     .gt::<user_fields::Age, _>(18)
    ///     .exists::<user_fields::Email>(true)
    ///     .and();
    /// // builder can still be used here
    /// ```
    ///
    /// Resulting BSON:
    /// ```text
    /// { "$and": [{ "name": "John Doe" }, { "age": { "$gt": 18 } }, { "email": { "$exists": true } }] }
    /// ```
    pub fn and(&self) -> bson::Document {
        if self.clauses.is_empty() {
            bson::doc! {}
        } else if self.clauses.len() == 1 {
            self.clauses[0].clone()
        } else {
            bson::doc! { "$and": self.clauses.clone() }
        }
    }
}

impl<T> Default for FilterBuilder<T> {
    fn default() -> Self {
        Self::new()
    }
}

/// Converts a FilterBuilder into a BSON document using MongoDB's `$and` semantics.
///
/// This implementation allows FilterBuilder to be automatically converted to a BSON document
/// in contexts where `Into<bson::Document>` is expected, providing a convenient way to use
/// the builder directly with MongoDB operations.
///
/// The conversion follows the same logic as the `and()` method:
/// - If no clauses exist, returns an empty document `{}`
/// - If only one clause exists, returns that clause directly
/// - If multiple clauses exist, wraps them in a `$and` array
///
/// # Example
///
/// ```rust
/// use tnuctipun::filters::empty;
/// use serde::{Serialize, Deserialize};
/// use bson;
///
/// // Self-contained example with manual trait implementations
/// # use tnuctipun::field_witnesses::{FieldName, HasField};
/// # use tnuctipun::mongo_comparable::{MongoComparable, MongoOrdered};
/// # struct Name;
/// # impl FieldName for Name {
/// #     fn field_name() -> &'static str { "name" }
/// # }
/// # struct Age;
/// # impl FieldName for Age {
/// #     fn field_name() -> &'static str { "age" }
/// # }
/// # struct User { name: String, age: i32 }
/// # impl HasField<Name> for User {
/// #     type Value = String;
/// #     fn get_field(&self) -> &Self::Value { &self.name }
/// # }
/// # impl HasField<Age> for User {
/// #     type Value = i32;
/// #     fn get_field(&self) -> &Self::Value { &self.age }
/// # }
/// # impl MongoComparable<String, String> for User {}
/// # impl MongoComparable<i32, i32> for User {}
/// # impl MongoOrdered<i32, i32> for User {}
///
/// // The builder can be automatically converted to bson::Document
/// let mut builder = empty::<User>();
/// builder.eq::<Name, _>("John".to_string())
///        .gt::<Age, _>(18);
/// let filter: bson::Document = builder.into();
///
/// // Or use directly in function calls expecting Into<bson::Document>
/// fn process_filter(filter: impl Into<bson::Document>) {
///     let doc = filter.into();
///     // ... use doc for MongoDB query
/// }
///
/// let mut builder2 = empty::<User>();
/// builder2.eq::<Name, _>("Alice".to_string());
/// process_filter(builder2);
/// ```
impl<T> From<FilterBuilder<T>> for bson::Document {
    fn from(val: FilterBuilder<T>) -> Self {
        val.and()
    }
}

/// Creates an empty FilterBuilder instance.
///
/// This is a convenience function that creates a new FilterBuilder.
/// It's equivalent to `FilterBuilder::<T>::new()` but with less typing.
///
/// # Example
///
/// ```rust
/// use tnuctipun::filters::empty;
/// use tnuctipun::{FieldWitnesses, MongoComparable};
/// use serde::{Serialize, Deserialize};
///
/// #[derive(Debug, Clone, Serialize, Deserialize, FieldWitnesses, MongoComparable)]
/// struct User { pub Name: String }
///
/// // Create and use a filter builder in one chain
/// empty::<User>().eq::<user_fields::Name, _>("John".to_string());
/// ```
pub fn empty<T>() -> FilterBuilder<T> {
    FilterBuilder::new()
}

// Testing internal/private functions

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

    // Test field marker types
    struct Name;
    impl FieldName for Name {
        fn field_name() -> &'static str {
            "Name"
        }
    }

    struct Category;
    impl FieldName for Category {
        fn field_name() -> &'static str {
            "Category"
        }
    }

    struct TestStruct;

    #[test]
    fn test_field_path_empty_prefix() {
        let builder = FilterBuilder::<TestStruct>::new();
        let path = builder.field_path::<Name>();

        assert_eq!(path, "Name");
    }

    #[test]
    fn test_field_path_single_prefix() {
        let mut builder = FilterBuilder::<TestStruct>::new();

        builder.prefix = vec!["user".to_string()];

        let path = builder.field_path::<Name>();

        assert_eq!(path, "user.Name");
    }

    #[test]
    fn test_field_path_multiple_prefix() {
        let mut builder = FilterBuilder::<TestStruct>::new();

        builder.prefix = vec!["profile".to_string(), "details".to_string()];

        let path = builder.field_path::<Category>();

        assert_eq!(path, "profile.details.Category");
    }

    #[test]
    fn test_field_path_nested_deep() {
        let mut builder = FilterBuilder::<TestStruct>::new();

        builder.prefix = vec![
            "root".to_string(),
            "level1".to_string(),
            "level2".to_string(),
            "level3".to_string(),
        ];

        let path = builder.field_path::<Name>();

        assert_eq!(path, "root.level1.level2.level3.Name");
    }
}