things3-core 2.0.0

Core library for Things 3 database access and data models
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
1439
1440
//! Data models for Things 3 entities

use std::fmt;
use std::str::FromStr;

use chrono::{DateTime, NaiveDate, Utc};
use serde::{Deserialize, Serialize};
use uuid::Uuid;

use crate::error::ThingsError;

/// Identifier for any Things 3 entity (task, project, area, tag, heading).
///
/// Things 3 uses two distinct identifier formats in the wild:
///
/// 1. **Native Things IDs** — 21- or 22-character base62 strings the Things
///    app itself produces (e.g. `R4t2G8Q63aGZq4epMHNeCr`). These appear on
///    every entity created via the Things UI or via `osascript`.
/// 2. **RFC-4122 UUIDs** — 36-character hyphenated hex strings that the
///    `SqlxBackend` generates for entities created through rust-things3
///    (e.g. `9d3f1e44-5c2a-4b8e-9c1f-7e2d8a4b3c5e`).
///
/// Both formats coexist in the same SQLite `uuid` column. This type stores
/// whichever format the entity was created with — never lossy conversion,
/// always round-trip-safe through `osascript`, the database, and JSON wire
/// format.
///
/// `#[serde(transparent)]` means the JSON shape is unchanged from when the
/// type was `Uuid`: a bare string field, no enum tagging.
///
/// # Validation boundary
///
/// `serde` deserialization (via `#[serde(transparent)]`) accepts **any** string
/// and does **not** call `from_str` — it calls `from_trusted` semantics. This is
/// intentional: request structs deserialized from the DB or from AppleScript output
/// already contain trusted values. If you add a new code path that deserializes a
/// request struct containing `ThingsId` fields directly from untrusted JSON (e.g. a
/// new HTTP handler), call `ThingsId::from_str` explicitly on each ID field before
/// acting on it rather than relying on serde to validate.
///
/// # Construction
///
/// - [`ThingsId::new_v4`] — fresh hyphenated UUID, used by `SqlxBackend`
/// - [`ThingsId::from_str`] — strict parse, rejects anything that isn't one
///   of the two known formats; used at MCP boundaries
/// - [`From<Uuid>`] — infallible, wraps a UUID's hyphenated form
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(transparent)]
pub struct ThingsId(String);

impl ThingsId {
    /// Generate a fresh hyphenated UUID, suitable for `SqlxBackend`-created
    /// entities.
    #[must_use]
    pub fn new_v4() -> Self {
        Self(Uuid::new_v4().to_string())
    }

    /// Generate a fresh Things-native 22-char Base62 ID. Use this for any
    /// new entity that may be referenced via AppleScript — Things 3's
    /// AppleScript dictionary only accepts this format in `to do id "..."`
    /// references, so a hyphenated UUID would fail with `-1728` (#148).
    ///
    /// Internally derived from a v4 UUID's 16 random bytes, base62-encoded
    /// (a 16-byte / 128-bit value fits in 22 base62 characters).
    #[must_use]
    pub fn new_things_native() -> Self {
        let bytes = *Uuid::new_v4().as_bytes();
        Self(base62_encode_22(&bytes))
    }

    /// Borrow the underlying string (for SQL parameter binding, AppleScript
    /// interpolation, logging, etc.).
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// Consume into the owned `String`.
    #[must_use]
    pub fn into_string(self) -> String {
        self.0
    }

    /// Construct without validation. Reserved for trusted sources only —
    /// values read directly from the SQLite `uuid` column or returned by
    /// `osascript`. Public input must go through [`FromStr`].
    pub(crate) fn from_trusted(s: String) -> Self {
        Self(s)
    }

    /// Returns true if `s` matches the native 21–22-char base62 Things format.
    fn is_things_native(s: &str) -> bool {
        let len = s.len();
        (len == 21 || len == 22) && s.chars().all(|c| c.is_ascii_alphanumeric())
    }

    /// Borrow the underlying string if it's already in Things native format
    /// (21–22-char Base62), or return a `Validation` error pointing the
    /// caller at the recreate-the-entity remediation.
    ///
    /// AppleScript-driving call sites use this to fail fast with a useful
    /// message instead of letting a hyphenated UUID reach `osascript`
    /// (which returns the opaque error `-1728` "Can't get to do id ...").
    #[cfg(target_os = "macos")]
    pub(crate) fn as_things_native(&self) -> Result<&str, ThingsError> {
        if Self::is_things_native(&self.0) {
            Ok(&self.0)
        } else {
            Err(ThingsError::validation(format!(
                "ID {:?} is not in Things native format (21–22-char Base62) \
                 and cannot be referenced via AppleScript. This entity was \
                 likely created on Linux/CI or with --unsafe-direct-db. \
                 Recreate it in Things 3, or set THINGS_UNSAFE_DIRECT_DB=1 \
                 to mutate via direct SQLite writes.",
                self.0
            )))
        }
    }
}

/// Encode 16 bytes into a fixed 22-char Base62 string (alphabet:
/// `0-9A-Za-z`). 16 bytes = 128 bits; 22 base62 chars hold ~131 bits, so
/// the encoding is fixed-length with leading-zero padding.
fn base62_encode_22(bytes: &[u8; 16]) -> String {
    // Alphabet is 0-9A-Za-z (digits, uppercase, lowercase). Arbitrary but
    // stable — Things 3's native-ID check only requires length 21-22 and
    // ASCII alphanumeric, not a specific ordering.
    const ALPHABET: &[u8; 62] = b"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
    let mut n = u128::from_be_bytes(*bytes);
    let mut out = [b'0'; 22];
    for slot in out.iter_mut().rev() {
        *slot = ALPHABET[(n % 62) as usize];
        n /= 62;
    }
    String::from_utf8(out.to_vec()).expect("alphabet is ASCII")
}

impl fmt::Display for ThingsId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.0)
    }
}

impl FromStr for ThingsId {
    type Err = ThingsError;

    /// Strict parse. Accepts:
    /// - Hyphenated RFC-4122 UUIDs (36 chars)
    /// - Things native IDs (21 or 22 base62 chars)
    ///
    /// Anything else returns a `ThingsError::Validation` so MCP callers see a
    /// clear error before the request hits the database.
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        if Uuid::parse_str(s).is_ok() {
            return Ok(Self(s.to_string()));
        }
        if Self::is_things_native(s) {
            return Ok(Self(s.to_string()));
        }
        Err(ThingsError::validation(format!(
            "invalid Things 3 identifier {s:?}: expected RFC-4122 UUID \
             (36 chars, hex+hyphens) or Things native ID (21–22 base62 chars)"
        )))
    }
}

impl From<Uuid> for ThingsId {
    fn from(uuid: Uuid) -> Self {
        Self(uuid.to_string())
    }
}

impl AsRef<str> for ThingsId {
    fn as_ref(&self) -> &str {
        &self.0
    }
}

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

    #[test]
    fn new_v4_produces_hyphenated_uuid_string() {
        let id = ThingsId::new_v4();
        let s = id.as_str();
        assert_eq!(s.len(), 36);
        assert!(Uuid::parse_str(s).is_ok());
    }

    #[test]
    fn new_things_native_produces_22_char_base62() {
        let id = ThingsId::new_things_native();
        let s = id.as_str();
        assert_eq!(s.len(), 22);
        assert!(s.chars().all(|c| c.is_ascii_alphanumeric()));
        assert!(ThingsId::is_things_native(s));
    }

    #[test]
    fn new_things_native_round_trips_through_from_str() {
        let original = ThingsId::new_things_native();
        let parsed: ThingsId = original.as_str().parse().unwrap();
        assert_eq!(original, parsed);
    }

    #[test]
    fn new_things_native_yields_unique_ids() {
        use std::collections::HashSet;
        let ids: HashSet<_> = (0..1000).map(|_| ThingsId::new_things_native()).collect();
        assert_eq!(ids.len(), 1000);
    }

    #[cfg(target_os = "macos")]
    #[test]
    fn as_things_native_accepts_native_id() {
        let id: ThingsId = "R4t2G8Q63aGZq4epMHNeCr".parse().unwrap();
        assert_eq!(id.as_things_native().unwrap(), "R4t2G8Q63aGZq4epMHNeCr");
    }

    #[cfg(target_os = "macos")]
    #[test]
    fn as_things_native_accepts_21_char_native_id() {
        let id: ThingsId = "19KLMeA2ULbixtvNbXsDK".parse().unwrap();
        assert_eq!(id.as_things_native().unwrap(), "19KLMeA2ULbixtvNbXsDK");
    }

    #[cfg(target_os = "macos")]
    #[test]
    fn as_things_native_rejects_hyphenated_uuid() {
        let id: ThingsId = "9d3f1e44-5c2a-4b8e-9c1f-7e2d8a4b3c5e".parse().unwrap();
        let err = id.as_things_native().unwrap_err();
        let msg = err.to_string();
        assert!(
            msg.contains("not in Things native format"),
            "missing format hint, got: {msg}"
        );
        assert!(msg.contains("Recreate"), "missing remediation, got: {msg}");
    }

    #[test]
    fn base62_encode_22_pads_zero_input() {
        // All-zero input → 22 leading-zero alphabet chars (i.e. all '0').
        let s = base62_encode_22(&[0u8; 16]);
        assert_eq!(s, "0".repeat(22));
    }

    #[test]
    fn base62_encode_22_handles_max_input() {
        // All-0xFF input is the largest u128, which maps to "7n42DGM5Tflk9n8mt7Fhc7"
        // (21 non-zero chars). Just verify length + alphabet, not the exact value.
        let s = base62_encode_22(&[0xFFu8; 16]);
        assert_eq!(s.len(), 22);
        assert!(s.chars().all(|c| c.is_ascii_alphanumeric()));
    }

    #[test]
    fn from_str_accepts_hyphenated_uuid() {
        let s = "9d3f1e44-5c2a-4b8e-9c1f-7e2d8a4b3c5e";
        let id: ThingsId = s.parse().unwrap();
        assert_eq!(id.as_str(), s);
    }

    #[test]
    fn from_str_accepts_22_char_native_id() {
        let s = "R4t2G8Q63aGZq4epMHNeCr";
        assert_eq!(s.len(), 22);
        let id: ThingsId = s.parse().unwrap();
        assert_eq!(id.as_str(), s);
    }

    #[test]
    fn from_str_accepts_21_char_native_id() {
        // Real example pulled from a Things 3 database.
        let s = "19KLMeA2ULbixtvNbXsDK";
        assert_eq!(s.len(), 21);
        let id: ThingsId = s.parse().unwrap();
        assert_eq!(id.as_str(), s);
    }

    #[test]
    fn from_str_rejects_short_garbage() {
        let err = "abc".parse::<ThingsId>().unwrap_err();
        assert!(matches!(err, ThingsError::Validation { .. }));
    }

    #[test]
    fn from_str_rejects_long_garbage() {
        // 23 chars — wrong length for native, wrong format for UUID
        let err = "ZZZZZZZZZZZZZZZZZZZZZZZ".parse::<ThingsId>().unwrap_err();
        assert!(matches!(err, ThingsError::Validation { .. }));
    }

    #[test]
    fn from_str_rejects_native_with_special_chars() {
        // 22 chars, but contains `-` (which is fine for UUIDs but not native)
        let err = "R4t2G8Q63aGZq4epMHN-Cr".parse::<ThingsId>().unwrap_err();
        assert!(matches!(err, ThingsError::Validation { .. }));
    }

    #[test]
    fn from_str_rejects_empty() {
        let err = "".parse::<ThingsId>().unwrap_err();
        assert!(matches!(err, ThingsError::Validation { .. }));
    }

    #[test]
    fn from_str_rejects_uuid_with_extra_chars() {
        // Valid UUID prefix + extra chars
        let err = "9d3f1e44-5c2a-4b8e-9c1f-7e2d8a4b3c5e-XYZ"
            .parse::<ThingsId>()
            .unwrap_err();
        assert!(matches!(err, ThingsError::Validation { .. }));
    }

    #[test]
    fn display_is_the_inner_string() {
        let id: ThingsId = "R4t2G8Q63aGZq4epMHNeCr".parse().unwrap();
        assert_eq!(format!("{id}"), "R4t2G8Q63aGZq4epMHNeCr");
    }

    #[test]
    fn from_uuid_wraps_hyphenated_form() {
        let uuid = Uuid::parse_str("9d3f1e44-5c2a-4b8e-9c1f-7e2d8a4b3c5e").unwrap();
        let id: ThingsId = uuid.into();
        assert_eq!(id.as_str(), "9d3f1e44-5c2a-4b8e-9c1f-7e2d8a4b3c5e");
    }

    #[test]
    fn serde_roundtrips_as_bare_string() {
        let id: ThingsId = "R4t2G8Q63aGZq4epMHNeCr".parse().unwrap();
        let json = serde_json::to_string(&id).unwrap();
        assert_eq!(json, "\"R4t2G8Q63aGZq4epMHNeCr\"");
        let back: ThingsId = serde_json::from_str(&json).unwrap();
        assert_eq!(back, id);
    }

    #[test]
    fn equality_is_string_equality() {
        let a: ThingsId = "R4t2G8Q63aGZq4epMHNeCr".parse().unwrap();
        let b: ThingsId = "R4t2G8Q63aGZq4epMHNeCr".parse().unwrap();
        assert_eq!(a, b);
    }

    #[test]
    fn from_trusted_skips_validation() {
        // Confirms the internal escape hatch works for DB/AS-sourced strings.
        // Deliberately weird value to prove no validation happens.
        let id = ThingsId::from_trusted("anything-goes-here".to_string());
        assert_eq!(id.as_str(), "anything-goes-here");
    }
}

/// Task status enumeration
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum TaskStatus {
    #[serde(rename = "incomplete")]
    Incomplete,
    #[serde(rename = "completed")]
    Completed,
    #[serde(rename = "canceled")]
    Canceled,
    /// Filter-input only. Trashed tasks are surfaced by the `trashed` column predicate,
    /// not by a status value — this variant is never returned from any read path.
    #[serde(rename = "trashed")]
    Trashed,
}

/// Task type enumeration
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum TaskType {
    #[serde(rename = "to-do")]
    Todo,
    #[serde(rename = "project")]
    Project,
    #[serde(rename = "heading")]
    Heading,
    #[serde(rename = "area")]
    Area,
}

/// How to handle child tasks when deleting a parent
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum DeleteChildHandling {
    /// Return error if task has children (default)
    #[serde(rename = "error")]
    Error,
    /// Delete parent and all children
    #[serde(rename = "cascade")]
    Cascade,
    /// Delete parent only, orphan children
    #[serde(rename = "orphan")]
    Orphan,
}

/// Main task entity
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Task {
    /// Unique identifier
    pub uuid: ThingsId,
    /// Task title
    pub title: String,
    /// Task type
    pub task_type: TaskType,
    /// Task status
    pub status: TaskStatus,
    /// Optional notes
    pub notes: Option<String>,
    /// Start date
    pub start_date: Option<NaiveDate>,
    /// Deadline
    pub deadline: Option<NaiveDate>,
    /// Creation timestamp
    pub created: DateTime<Utc>,
    /// Last modification timestamp
    pub modified: DateTime<Utc>,
    /// Completion timestamp (when status changed to completed)
    pub stop_date: Option<DateTime<Utc>>,
    /// Parent project UUID
    pub project_uuid: Option<ThingsId>,
    /// Parent area UUID
    pub area_uuid: Option<ThingsId>,
    /// Parent task UUID
    pub parent_uuid: Option<ThingsId>,
    /// Associated tags
    pub tags: Vec<String>,
    /// Child tasks
    pub children: Vec<Task>,
}

/// Project entity
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Project {
    /// Unique identifier
    pub uuid: ThingsId,
    /// Project title
    pub title: String,
    /// Optional notes
    pub notes: Option<String>,
    /// Start date
    pub start_date: Option<NaiveDate>,
    /// Deadline
    pub deadline: Option<NaiveDate>,
    /// Creation timestamp
    pub created: DateTime<Utc>,
    /// Last modification timestamp
    pub modified: DateTime<Utc>,
    /// Parent area UUID
    pub area_uuid: Option<ThingsId>,
    /// Associated tags
    pub tags: Vec<String>,
    /// Project status
    pub status: TaskStatus,
    /// Child tasks
    pub tasks: Vec<Task>,
}

/// Area entity
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Area {
    /// Unique identifier
    pub uuid: ThingsId,
    /// Area title
    pub title: String,
    /// Optional notes
    pub notes: Option<String>,
    /// Creation timestamp
    pub created: DateTime<Utc>,
    /// Last modification timestamp
    pub modified: DateTime<Utc>,
    /// Associated tags
    pub tags: Vec<String>,
    /// Child projects
    pub projects: Vec<Project>,
}

/// Tag entity (enhanced with duplicate prevention support)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Tag {
    /// Unique identifier
    pub uuid: ThingsId,
    /// Tag title (display form, preserves case)
    pub title: String,
    /// Keyboard shortcut
    pub shortcut: Option<String>,
    /// Parent tag UUID (for nested tags)
    pub parent_uuid: Option<ThingsId>,
    /// How many tasks use this tag
    pub usage_count: u32,
    /// Last time this tag was used
    pub last_used: Option<DateTime<Utc>>,
}

/// Tag creation request
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CreateTagRequest {
    /// Tag title (required)
    pub title: String,
    /// Keyboard shortcut
    pub shortcut: Option<String>,
    /// Parent tag UUID (for nested tags)
    pub parent_uuid: Option<ThingsId>,
}

/// Tag update request
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UpdateTagRequest {
    /// Tag UUID
    pub uuid: ThingsId,
    /// New title
    pub title: Option<String>,
    /// New shortcut
    pub shortcut: Option<String>,
    /// New parent UUID
    pub parent_uuid: Option<ThingsId>,
}

/// Tag match type classification
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum TagMatchType {
    /// Exact match (case-insensitive)
    #[serde(rename = "exact")]
    Exact,
    /// Same text, different case
    #[serde(rename = "case_mismatch")]
    CaseMismatch,
    /// Fuzzy match (high similarity via Levenshtein distance)
    #[serde(rename = "similar")]
    Similar,
    /// Substring/contains match
    #[serde(rename = "partial")]
    PartialMatch,
}

/// Tag search result with similarity scoring
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TagMatch {
    /// The matched tag
    pub tag: Tag,
    /// Similarity score (0.0 to 1.0, higher is better)
    pub similarity_score: f32,
    /// Type of match
    pub match_type: TagMatchType,
}

/// Result of tag creation with duplicate checking
#[non_exhaustive]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum TagCreationResult {
    /// New tag was created
    #[serde(rename = "created")]
    Created {
        /// UUID of created tag
        uuid: ThingsId,
        /// Always true for this variant
        is_new: bool,
    },
    /// Existing exact match found
    #[serde(rename = "existing")]
    Existing {
        /// The existing tag
        tag: Tag,
        /// Always false for this variant
        is_new: bool,
    },
    /// Similar tags found (user decision needed)
    #[serde(rename = "similar_found")]
    SimilarFound {
        /// Tags similar to requested title
        similar_tags: Vec<TagMatch>,
        /// The title user requested
        requested_title: String,
    },
}

/// Result of tag assignment to task
#[non_exhaustive]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum TagAssignmentResult {
    /// Tag assigned successfully
    #[serde(rename = "assigned")]
    Assigned {
        /// UUID of the tag that was assigned
        tag_uuid: ThingsId,
    },
    /// Similar tags found (user decision needed)
    #[serde(rename = "suggestions")]
    Suggestions {
        /// Suggested alternative tags
        similar_tags: Vec<TagMatch>,
    },
}

/// Tag auto-completion suggestion
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TagCompletion {
    /// The tag
    pub tag: Tag,
    /// Priority score (based on usage, recency, match quality)
    pub score: f32,
}

/// Tag statistics for analytics
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TagStatistics {
    /// Tag UUID
    pub uuid: ThingsId,
    /// Tag title
    pub title: String,
    /// Total usage count
    pub usage_count: u32,
    /// Task UUIDs using this tag
    pub task_uuids: Vec<ThingsId>,
    /// Related tags (frequently used together)
    pub related_tags: Vec<(String, u32)>, // (tag_title, co_occurrence_count)
}

/// Pair of similar tags (for duplicate detection)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TagPair {
    /// First tag
    pub tag1: Tag,
    /// Second tag
    pub tag2: Tag,
    /// Similarity score between them
    pub similarity: f32,
}

/// Task creation request
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CreateTaskRequest {
    /// Task title (required)
    pub title: String,
    /// Task type (defaults to Todo)
    pub task_type: Option<TaskType>,
    /// Optional notes
    pub notes: Option<String>,
    /// Start date
    pub start_date: Option<NaiveDate>,
    /// Deadline
    pub deadline: Option<NaiveDate>,
    /// Project UUID (validated if provided)
    pub project_uuid: Option<ThingsId>,
    /// Area UUID (validated if provided)
    pub area_uuid: Option<ThingsId>,
    /// Parent task UUID (for subtasks)
    pub parent_uuid: Option<ThingsId>,
    /// Tags (as string names)
    pub tags: Option<Vec<String>>,
    /// Initial status (defaults to Incomplete)
    pub status: Option<TaskStatus>,
}

/// Task update request
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UpdateTaskRequest {
    /// Task UUID
    pub uuid: ThingsId,
    /// New title
    pub title: Option<String>,
    /// New notes
    pub notes: Option<String>,
    /// New start date
    pub start_date: Option<NaiveDate>,
    /// New deadline
    pub deadline: Option<NaiveDate>,
    /// New status
    pub status: Option<TaskStatus>,
    /// New project UUID
    pub project_uuid: Option<ThingsId>,
    /// New area UUID
    pub area_uuid: Option<ThingsId>,
    /// New tags
    pub tags: Option<Vec<String>>,
}

/// Task filters for queries
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct TaskFilters {
    /// Filter by status
    pub status: Option<TaskStatus>,
    /// Filter by task type
    pub task_type: Option<TaskType>,
    /// Filter by project UUID
    pub project_uuid: Option<ThingsId>,
    /// Filter by area UUID
    pub area_uuid: Option<ThingsId>,
    /// Filter by tags (AND semantics — task must contain every listed tag).
    pub tags: Option<Vec<String>>,
    /// Filter by start date range
    pub start_date_from: Option<NaiveDate>,
    pub start_date_to: Option<NaiveDate>,
    /// Filter by deadline range
    pub deadline_from: Option<NaiveDate>,
    pub deadline_to: Option<NaiveDate>,
    /// Search query
    pub search_query: Option<String>,
    /// Limit results
    pub limit: Option<usize>,
    /// Offset for pagination
    pub offset: Option<usize>,
}

/// A task paired with its fuzzy-match relevance score.
///
/// Returned by [`crate::query::TaskQueryBuilder::execute_ranked`].
///
/// Requires the `advanced-queries` feature flag.
#[cfg(feature = "advanced-queries")]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RankedTask {
    /// The matched task.
    pub task: Task,
    /// Relevance score in `[0.0, 1.0]`; higher is a better match.
    pub score: f32,
}

/// Project creation request
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CreateProjectRequest {
    /// Project title (required)
    pub title: String,
    /// Optional notes
    pub notes: Option<String>,
    /// Area UUID (validated if provided)
    pub area_uuid: Option<ThingsId>,
    /// Start date
    pub start_date: Option<NaiveDate>,
    /// Deadline
    pub deadline: Option<NaiveDate>,
    /// Tags (as string names)
    pub tags: Option<Vec<String>>,
}

/// Project update request
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UpdateProjectRequest {
    /// Project UUID
    pub uuid: ThingsId,
    /// New title
    pub title: Option<String>,
    /// New notes
    pub notes: Option<String>,
    /// New area UUID
    pub area_uuid: Option<ThingsId>,
    /// New start date
    pub start_date: Option<NaiveDate>,
    /// New deadline
    pub deadline: Option<NaiveDate>,
    /// New tags
    pub tags: Option<Vec<String>>,
}

/// Area creation request
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CreateAreaRequest {
    /// Area title (required)
    pub title: String,
}

/// Area update request
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UpdateAreaRequest {
    /// Area UUID
    pub uuid: ThingsId,
    /// New title
    pub title: String,
}

/// How to handle child tasks when completing/deleting a project
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
pub enum ProjectChildHandling {
    /// Return error if project has child tasks (default, safest)
    #[serde(rename = "error")]
    #[default]
    Error,
    /// Complete/delete all child tasks
    #[serde(rename = "cascade")]
    Cascade,
    /// Move child tasks to inbox (orphan them)
    #[serde(rename = "orphan")]
    Orphan,
}

// ============================================================================
// Bulk Operation Models
// ============================================================================

/// Request to move multiple tasks to a project or area
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BulkMoveRequest {
    /// Task UUIDs to move
    pub task_uuids: Vec<ThingsId>,
    /// Target project UUID (optional)
    pub project_uuid: Option<ThingsId>,
    /// Target area UUID (optional)
    pub area_uuid: Option<ThingsId>,
}

/// Request to update dates for multiple tasks
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BulkUpdateDatesRequest {
    /// Task UUIDs to update
    pub task_uuids: Vec<ThingsId>,
    /// New start date (None means don't update)
    pub start_date: Option<NaiveDate>,
    /// New deadline (None means don't update)
    pub deadline: Option<NaiveDate>,
    /// Clear start date (set to NULL)
    pub clear_start_date: bool,
    /// Clear deadline (set to NULL)
    pub clear_deadline: bool,
}

/// Request to complete multiple tasks
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BulkCompleteRequest {
    /// Task UUIDs to complete
    pub task_uuids: Vec<ThingsId>,
}

/// Request to delete multiple tasks
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BulkDeleteRequest {
    /// Task UUIDs to delete
    pub task_uuids: Vec<ThingsId>,
}

/// Request to create multiple tasks in one call.
///
/// Bulk creation is atomic — if any task fails, all tasks created so far are
/// rolled back and the caller receives an error with no partial state left.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BulkCreateTasksRequest {
    /// Tasks to create
    pub tasks: Vec<CreateTaskRequest>,
}

/// Result of a bulk operation
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BulkOperationResult {
    /// Whether the operation succeeded
    pub success: bool,
    /// Number of tasks processed
    pub processed_count: usize,
    /// Result message
    pub message: String,
}

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

    #[test]
    fn test_task_status_serialization() {
        let status = TaskStatus::Incomplete;
        let serialized = serde_json::to_string(&status).unwrap();
        assert_eq!(serialized, "\"incomplete\"");

        let status = TaskStatus::Completed;
        let serialized = serde_json::to_string(&status).unwrap();
        assert_eq!(serialized, "\"completed\"");

        let status = TaskStatus::Canceled;
        let serialized = serde_json::to_string(&status).unwrap();
        assert_eq!(serialized, "\"canceled\"");

        let status = TaskStatus::Trashed;
        let serialized = serde_json::to_string(&status).unwrap();
        assert_eq!(serialized, "\"trashed\"");
    }

    #[test]
    fn test_task_status_deserialization() {
        let deserialized: TaskStatus = serde_json::from_str("\"incomplete\"").unwrap();
        assert_eq!(deserialized, TaskStatus::Incomplete);

        let deserialized: TaskStatus = serde_json::from_str("\"completed\"").unwrap();
        assert_eq!(deserialized, TaskStatus::Completed);

        let deserialized: TaskStatus = serde_json::from_str("\"canceled\"").unwrap();
        assert_eq!(deserialized, TaskStatus::Canceled);

        let deserialized: TaskStatus = serde_json::from_str("\"trashed\"").unwrap();
        assert_eq!(deserialized, TaskStatus::Trashed);
    }

    #[test]
    fn test_task_type_serialization() {
        let task_type = TaskType::Todo;
        let serialized = serde_json::to_string(&task_type).unwrap();
        assert_eq!(serialized, "\"to-do\"");

        let task_type = TaskType::Project;
        let serialized = serde_json::to_string(&task_type).unwrap();
        assert_eq!(serialized, "\"project\"");

        let task_type = TaskType::Heading;
        let serialized = serde_json::to_string(&task_type).unwrap();
        assert_eq!(serialized, "\"heading\"");

        let task_type = TaskType::Area;
        let serialized = serde_json::to_string(&task_type).unwrap();
        assert_eq!(serialized, "\"area\"");
    }

    #[test]
    fn test_task_type_deserialization() {
        let deserialized: TaskType = serde_json::from_str("\"to-do\"").unwrap();
        assert_eq!(deserialized, TaskType::Todo);

        let deserialized: TaskType = serde_json::from_str("\"project\"").unwrap();
        assert_eq!(deserialized, TaskType::Project);

        let deserialized: TaskType = serde_json::from_str("\"heading\"").unwrap();
        assert_eq!(deserialized, TaskType::Heading);

        let deserialized: TaskType = serde_json::from_str("\"area\"").unwrap();
        assert_eq!(deserialized, TaskType::Area);
    }

    #[test]
    fn test_task_creation() {
        let uuid = ThingsId::new_v4();
        let now = Utc::now();
        let start_date = NaiveDate::from_ymd_opt(2024, 1, 1).unwrap();
        let deadline = NaiveDate::from_ymd_opt(2024, 12, 31).unwrap();

        let task = Task {
            uuid: uuid.clone(),
            title: "Test Task".to_string(),
            task_type: TaskType::Todo,
            status: TaskStatus::Incomplete,
            notes: Some("Test notes".to_string()),
            start_date: Some(start_date),
            deadline: Some(deadline),
            created: now,
            modified: now,
            stop_date: None,
            project_uuid: None,
            area_uuid: None,
            parent_uuid: None,
            tags: vec!["work".to_string(), "urgent".to_string()],
            children: vec![],
        };

        assert_eq!(task.uuid, uuid);
        assert_eq!(task.title, "Test Task");
        assert_eq!(task.task_type, TaskType::Todo);
        assert_eq!(task.status, TaskStatus::Incomplete);
        assert_eq!(task.notes, Some("Test notes".to_string()));
        assert_eq!(task.start_date, Some(start_date));
        assert_eq!(task.deadline, Some(deadline));
        assert_eq!(task.tags.len(), 2);
        assert!(task.tags.contains(&"work".to_string()));
        assert!(task.tags.contains(&"urgent".to_string()));
    }

    #[test]
    fn test_task_serialization() {
        let uuid = ThingsId::new_v4();
        let now = Utc::now();

        let task = Task {
            uuid: uuid.clone(),
            title: "Test Task".to_string(),
            task_type: TaskType::Todo,
            status: TaskStatus::Incomplete,
            notes: None,
            start_date: None,
            deadline: None,
            created: now,
            modified: now,
            stop_date: None,
            project_uuid: None,
            area_uuid: None,
            parent_uuid: None,
            tags: vec![],
            children: vec![],
        };

        let serialized = serde_json::to_string(&task).unwrap();
        let deserialized: Task = serde_json::from_str(&serialized).unwrap();

        assert_eq!(deserialized.uuid, task.uuid);
        assert_eq!(deserialized.title, task.title);
        assert_eq!(deserialized.task_type, task.task_type);
        assert_eq!(deserialized.status, task.status);
    }

    #[test]
    fn test_project_creation() {
        let uuid = ThingsId::new_v4();
        let area_uuid = ThingsId::new_v4();
        let now = Utc::now();

        let project = Project {
            uuid: uuid.clone(),
            title: "Test Project".to_string(),
            notes: Some("Project notes".to_string()),
            start_date: None,
            deadline: None,
            created: now,
            modified: now,
            area_uuid: Some(area_uuid.clone()),
            tags: vec!["project".to_string()],
            status: TaskStatus::Incomplete,
            tasks: vec![],
        };

        assert_eq!(project.uuid, uuid);
        assert_eq!(project.title, "Test Project");
        assert_eq!(project.area_uuid, Some(area_uuid));
        assert_eq!(project.status, TaskStatus::Incomplete);
        assert_eq!(project.tags.len(), 1);
    }

    #[test]
    fn test_project_serialization() {
        let uuid = ThingsId::new_v4();
        let now = Utc::now();

        let project = Project {
            uuid: uuid.clone(),
            title: "Test Project".to_string(),
            notes: None,
            start_date: None,
            deadline: None,
            created: now,
            modified: now,
            area_uuid: None,
            tags: vec![],
            status: TaskStatus::Incomplete,
            tasks: vec![],
        };

        let serialized = serde_json::to_string(&project).unwrap();
        let deserialized: Project = serde_json::from_str(&serialized).unwrap();

        assert_eq!(deserialized.uuid, project.uuid);
        assert_eq!(deserialized.title, project.title);
        assert_eq!(deserialized.status, project.status);
    }

    #[test]
    fn test_area_creation() {
        let uuid = ThingsId::new_v4();
        let now = Utc::now();

        let area = Area {
            uuid: uuid.clone(),
            title: "Test Area".to_string(),
            notes: Some("Area notes".to_string()),
            created: now,
            modified: now,
            tags: vec!["area".to_string()],
            projects: vec![],
        };

        assert_eq!(area.uuid, uuid);
        assert_eq!(area.title, "Test Area");
        assert_eq!(area.notes, Some("Area notes".to_string()));
        assert_eq!(area.tags.len(), 1);
    }

    #[test]
    fn test_area_serialization() {
        let uuid = ThingsId::new_v4();
        let now = Utc::now();

        let area = Area {
            uuid: uuid.clone(),
            title: "Test Area".to_string(),
            notes: None,
            created: now,
            modified: now,
            tags: vec![],
            projects: vec![],
        };

        let serialized = serde_json::to_string(&area).unwrap();
        let deserialized: Area = serde_json::from_str(&serialized).unwrap();

        assert_eq!(deserialized.uuid, area.uuid);
        assert_eq!(deserialized.title, area.title);
    }

    #[test]
    fn test_tag_creation() {
        let uuid = ThingsId::new_v4();
        let parent_uuid = ThingsId::new_v4();
        let now = Utc::now();

        let tag = Tag {
            uuid: uuid.clone(),
            title: "work".to_string(),
            shortcut: Some("w".to_string()),
            parent_uuid: Some(parent_uuid.clone()),
            usage_count: 5,
            last_used: Some(now),
        };

        assert_eq!(tag.uuid, uuid);
        assert_eq!(tag.title, "work");
        assert_eq!(tag.shortcut, Some("w".to_string()));
        assert_eq!(tag.parent_uuid, Some(parent_uuid));
        assert_eq!(tag.usage_count, 5);
        assert_eq!(tag.last_used, Some(now));
    }

    #[test]
    fn test_tag_serialization() {
        let uuid = ThingsId::new_v4();

        let tag = Tag {
            uuid: uuid.clone(),
            title: "test".to_string(),
            shortcut: None,
            parent_uuid: None,
            usage_count: 0,
            last_used: None,
        };

        let serialized = serde_json::to_string(&tag).unwrap();
        let deserialized: Tag = serde_json::from_str(&serialized).unwrap();

        assert_eq!(deserialized.uuid, tag.uuid);
        assert_eq!(deserialized.title, tag.title);
        assert_eq!(deserialized.usage_count, tag.usage_count);
    }

    #[test]
    fn test_create_task_request() {
        let project_uuid = ThingsId::new_v4();
        let area_uuid = ThingsId::new_v4();
        let start_date = NaiveDate::from_ymd_opt(2024, 1, 1).unwrap();

        let request = CreateTaskRequest {
            title: "New Task".to_string(),
            task_type: None,
            notes: Some("Task notes".to_string()),
            start_date: Some(start_date),
            deadline: None,
            project_uuid: Some(project_uuid.clone()),
            area_uuid: Some(area_uuid.clone()),
            parent_uuid: None,
            tags: Some(vec!["new".to_string()]),
            status: None,
        };

        assert_eq!(request.title, "New Task");
        assert_eq!(request.project_uuid, Some(project_uuid));
        assert_eq!(request.area_uuid, Some(area_uuid));
        assert_eq!(request.start_date, Some(start_date));
        assert_eq!(request.tags.as_ref().unwrap().len(), 1);
    }

    #[test]
    fn test_create_task_request_serialization() {
        let request = CreateTaskRequest {
            title: "Test".to_string(),
            task_type: None,
            notes: None,
            start_date: None,
            deadline: None,
            project_uuid: None,
            area_uuid: None,
            parent_uuid: None,
            tags: None,
            status: None,
        };

        let serialized = serde_json::to_string(&request).unwrap();
        let deserialized: CreateTaskRequest = serde_json::from_str(&serialized).unwrap();

        assert_eq!(deserialized.title, request.title);
    }

    #[test]
    fn test_update_task_request() {
        let uuid = ThingsId::new_v4();

        let request = UpdateTaskRequest {
            uuid: uuid.clone(),
            title: Some("Updated Title".to_string()),
            notes: Some("Updated notes".to_string()),
            start_date: None,
            deadline: None,
            status: Some(TaskStatus::Completed),
            project_uuid: None,
            area_uuid: None,
            tags: Some(vec!["updated".to_string()]),
        };

        assert_eq!(request.uuid, uuid);
        assert_eq!(request.title, Some("Updated Title".to_string()));
        assert_eq!(request.status, Some(TaskStatus::Completed));
        assert_eq!(request.tags, Some(vec!["updated".to_string()]));
    }

    #[test]
    fn test_update_task_request_serialization() {
        let uuid = ThingsId::new_v4();

        let request = UpdateTaskRequest {
            uuid: uuid.clone(),
            title: None,
            notes: None,
            start_date: None,
            deadline: None,
            status: None,
            project_uuid: None,
            area_uuid: None,
            tags: None,
        };

        let serialized = serde_json::to_string(&request).unwrap();
        let deserialized: UpdateTaskRequest = serde_json::from_str(&serialized).unwrap();

        assert_eq!(deserialized.uuid, request.uuid);
    }

    #[test]
    fn test_task_filters_default() {
        let filters = TaskFilters::default();

        assert!(filters.status.is_none());
        assert!(filters.task_type.is_none());
        assert!(filters.project_uuid.is_none());
        assert!(filters.area_uuid.is_none());
        assert!(filters.tags.is_none());
        assert!(filters.start_date_from.is_none());
        assert!(filters.start_date_to.is_none());
        assert!(filters.deadline_from.is_none());
        assert!(filters.deadline_to.is_none());
        assert!(filters.search_query.is_none());
        assert!(filters.limit.is_none());
        assert!(filters.offset.is_none());
    }

    #[test]
    fn test_task_filters_creation() {
        let project_uuid = ThingsId::new_v4();
        let start_date = NaiveDate::from_ymd_opt(2024, 1, 1).unwrap();

        let filters = TaskFilters {
            status: Some(TaskStatus::Incomplete),
            task_type: Some(TaskType::Todo),
            project_uuid: Some(project_uuid.clone()),
            area_uuid: None,
            tags: Some(vec!["work".to_string()]),
            start_date_from: Some(start_date),
            start_date_to: None,
            deadline_from: None,
            deadline_to: None,
            search_query: Some("test".to_string()),
            limit: Some(10),
            offset: Some(0),
        };

        assert_eq!(filters.status, Some(TaskStatus::Incomplete));
        assert_eq!(filters.task_type, Some(TaskType::Todo));
        assert_eq!(filters.project_uuid, Some(project_uuid));
        assert_eq!(filters.search_query, Some("test".to_string()));
        assert_eq!(filters.limit, Some(10));
        assert_eq!(filters.offset, Some(0));
    }

    #[test]
    fn test_task_filters_serialization() {
        let filters = TaskFilters {
            status: Some(TaskStatus::Completed),
            task_type: Some(TaskType::Project),
            project_uuid: None,
            area_uuid: None,
            tags: None,
            start_date_from: None,
            start_date_to: None,
            deadline_from: None,
            deadline_to: None,
            search_query: None,
            limit: None,
            offset: None,
        };

        let serialized = serde_json::to_string(&filters).unwrap();
        let deserialized: TaskFilters = serde_json::from_str(&serialized).unwrap();

        assert_eq!(deserialized.status, filters.status);
        assert_eq!(deserialized.task_type, filters.task_type);
    }

    #[test]
    fn test_task_status_equality() {
        assert_eq!(TaskStatus::Incomplete, TaskStatus::Incomplete);
        assert_ne!(TaskStatus::Incomplete, TaskStatus::Completed);
        assert_ne!(TaskStatus::Completed, TaskStatus::Canceled);
        assert_ne!(TaskStatus::Canceled, TaskStatus::Trashed);
    }

    #[test]
    fn test_task_type_equality() {
        assert_eq!(TaskType::Todo, TaskType::Todo);
        assert_ne!(TaskType::Todo, TaskType::Project);
        assert_ne!(TaskType::Project, TaskType::Heading);
        assert_ne!(TaskType::Heading, TaskType::Area);
    }

    #[test]
    fn test_task_with_children() {
        let parent_uuid = ThingsId::new_v4();
        let child_uuid = ThingsId::new_v4();
        let now = Utc::now();

        let child_task = Task {
            uuid: child_uuid,
            title: "Child Task".to_string(),
            task_type: TaskType::Todo,
            status: TaskStatus::Incomplete,
            notes: None,
            start_date: None,
            deadline: None,
            created: now,
            modified: now,
            stop_date: None,
            project_uuid: None,
            area_uuid: None,
            parent_uuid: Some(parent_uuid.clone()),
            tags: vec![],
            children: vec![],
        };

        let parent_task = Task {
            uuid: parent_uuid.clone(),
            title: "Parent Task".to_string(),
            task_type: TaskType::Heading,
            status: TaskStatus::Incomplete,
            notes: None,
            start_date: None,
            deadline: None,
            created: now,
            modified: now,
            stop_date: None,
            project_uuid: None,
            area_uuid: None,
            parent_uuid: None,
            tags: vec![],
            children: vec![child_task],
        };

        assert_eq!(parent_task.children.len(), 1);
        assert_eq!(parent_task.children[0].parent_uuid, Some(parent_uuid));
        assert_eq!(parent_task.children[0].title, "Child Task");
    }

    #[test]
    fn test_project_with_tasks() {
        let project_uuid = ThingsId::new_v4();
        let task_uuid = ThingsId::new_v4();
        let now = Utc::now();

        let task = Task {
            uuid: task_uuid,
            title: "Project Task".to_string(),
            task_type: TaskType::Todo,
            status: TaskStatus::Incomplete,
            notes: None,
            start_date: None,
            deadline: None,
            created: now,
            modified: now,
            stop_date: None,
            project_uuid: Some(project_uuid.clone()),
            area_uuid: None,
            parent_uuid: None,
            tags: vec![],
            children: vec![],
        };

        let project = Project {
            uuid: project_uuid.clone(),
            title: "Test Project".to_string(),
            notes: None,
            start_date: None,
            deadline: None,
            created: now,
            modified: now,
            area_uuid: None,
            tags: vec![],
            status: TaskStatus::Incomplete,
            tasks: vec![task],
        };

        assert_eq!(project.tasks.len(), 1);
        assert_eq!(project.tasks[0].project_uuid, Some(project_uuid));
        assert_eq!(project.tasks[0].title, "Project Task");
    }

    #[test]
    fn test_area_with_projects() {
        let area_uuid = ThingsId::new_v4();
        let project_uuid = ThingsId::new_v4();
        let now = Utc::now();

        let project = Project {
            uuid: project_uuid,
            title: "Area Project".to_string(),
            notes: None,
            start_date: None,
            deadline: None,
            created: now,
            modified: now,
            area_uuid: Some(area_uuid.clone()),
            tags: vec![],
            status: TaskStatus::Incomplete,
            tasks: vec![],
        };

        let area = Area {
            uuid: area_uuid.clone(),
            title: "Test Area".to_string(),
            notes: None,
            created: now,
            modified: now,
            tags: vec![],
            projects: vec![project],
        };

        assert_eq!(area.projects.len(), 1);
        assert_eq!(area.projects[0].area_uuid, Some(area_uuid));
        assert_eq!(area.projects[0].title, "Area Project");
    }
}