cloudillo-types 0.8.13

Shared types, adapter traits, and error types for the Cloudillo federated collaboration platform
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
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
// SPDX-FileCopyrightText: Szilárd Hajba
// SPDX-License-Identifier: LGPL-3.0-or-later

//! Adapter that manages metadata. Everything including tenants, profiles, actions, file metadata, etc.

/// Special parent_id value for trashed files
pub const TRASH_PARENT_ID: &str = "__trash__";

use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use serde_with::skip_serializing_none;
use std::{cmp::Ordering, collections::HashMap, fmt::Debug};

use crate::{
	prelude::*,
	types::{serialize_timestamp_iso, serialize_timestamp_iso_opt},
};

// Tenants, profiles
//*******************
#[derive(Debug, Clone, Copy, Serialize, Deserialize, Default, PartialEq, Eq)]
pub enum ProfileType {
	#[default]
	#[serde(rename = "person")]
	Person,
	#[serde(rename = "community")]
	Community,
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
pub enum ProfileStatus {
	#[serde(rename = "A")]
	Active,
	#[serde(rename = "T")]
	Trusted,
	#[serde(rename = "B")]
	Blocked,
	#[serde(rename = "M")]
	Muted,
	#[serde(rename = "S")]
	Suspended,
	#[serde(rename = "X")]
	Banned,
}

impl ProfileStatus {
	/// Lowercase string form for JSON DTO exposure to the frontend.
	pub fn as_str(&self) -> &'static str {
		match self {
			ProfileStatus::Active => "active",
			ProfileStatus::Trusted => "trusted",
			ProfileStatus::Blocked => "blocked",
			ProfileStatus::Muted => "muted",
			ProfileStatus::Suspended => "suspended",
			ProfileStatus::Banned => "banned",
		}
	}
}

/// Per-profile proxy-token preference for passive reads of a remote profile's content.
/// Absent (NULL) means ask the user at the time of access.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum ProfileTrust {
	/// Always authenticate via proxy token when accessing this profile.
	Always,
	/// Never authenticate; always access anonymously.
	Never,
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, Default, PartialEq, Eq)]
pub enum ProfileConnectionStatus {
	#[default]
	Disconnected,
	RequestPending,
	Connected,
}

impl ProfileConnectionStatus {
	pub fn is_connected(&self) -> bool {
		matches!(self, ProfileConnectionStatus::Connected)
	}
}

impl std::fmt::Display for ProfileConnectionStatus {
	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
		match self {
			ProfileConnectionStatus::Disconnected => write!(f, "disconnected"),
			ProfileConnectionStatus::RequestPending => write!(f, "pending"),
			ProfileConnectionStatus::Connected => write!(f, "connected"),
		}
	}
}

// Reference / Bookmark types
//*****************************

#[skip_serializing_none]
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct RefData {
	pub ref_id: Box<str>,
	pub r#type: Box<str>,
	pub description: Option<Box<str>>,
	#[serde(serialize_with = "serialize_timestamp_iso")]
	pub created_at: Timestamp,
	#[serde(serialize_with = "serialize_timestamp_iso_opt")]
	pub expires_at: Option<Timestamp>,
	/// Usage count: None = unlimited, Some(n) = n uses remaining
	pub count: Option<u32>,
	/// Resource ID for share links (e.g., file_id for share.file type)
	pub resource_id: Option<Box<str>>,
	/// Access level for share links ('R'=Read, 'W'=Write)
	pub access_level: Option<char>,
	/// Launch params as serialized query string (e.g., "mode=present")
	pub params: Option<Box<str>>,
}

pub struct ListRefsOptions {
	pub typ: Option<String>,
	pub filter: Option<String>, // 'active', 'used', 'expired', 'all'
	/// Filter by resource_id (for listing share links for a specific resource)
	pub resource_id: Option<String>,
}

#[derive(Default)]
pub struct CreateRefOptions {
	pub typ: String,
	pub description: Option<String>,
	pub expires_at: Option<Timestamp>,
	pub count: Option<u32>,
	/// Resource ID for share links (e.g., file_id for share.file type)
	pub resource_id: Option<String>,
	/// Access level for share links ('R'=Read, 'W'=Write)
	pub access_level: Option<char>,
	/// Launch params as serialized query string (e.g., "mode=present")
	pub params: Option<String>,
}

#[skip_serializing_none]
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Tenant<S: AsRef<str>> {
	#[serde(rename = "id")]
	pub tn_id: TnId,
	pub id_tag: S,
	pub name: S,
	#[serde(rename = "type")]
	pub typ: ProfileType,
	pub profile_pic: Option<S>,
	pub cover_pic: Option<S>,
	#[serde(serialize_with = "serialize_timestamp_iso")]
	pub created_at: Timestamp,
	pub x: HashMap<S, S>,
}

/// Options for listing tenants in meta adapter
#[derive(Debug, Default)]
pub struct ListTenantsMetaOptions {
	pub limit: Option<u32>,
	pub offset: Option<u32>,
}

/// Tenant list item from meta adapter (without cover_pic and x fields)
#[skip_serializing_none]
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct TenantListMeta {
	pub tn_id: TnId,
	pub id_tag: Box<str>,
	pub name: Box<str>,
	#[serde(rename = "type")]
	pub typ: ProfileType,
	pub profile_pic: Option<Box<str>>,
	#[serde(serialize_with = "serialize_timestamp_iso")]
	pub created_at: Timestamp,
}

#[derive(Debug, Default, Deserialize)]
pub struct UpdateTenantData {
	#[serde(rename = "idTag", default)]
	pub id_tag: Patch<String>,
	#[serde(default)]
	pub name: Patch<String>,
	#[serde(rename = "type", default)]
	pub typ: Patch<ProfileType>,
	#[serde(rename = "profilePic", default)]
	pub profile_pic: Patch<String>,
	#[serde(rename = "coverPic", default)]
	pub cover_pic: Patch<String>,
	/// Partial merge for x JSON field: Some(value) = upsert, None = delete key
	#[serde(default)]
	pub x: Option<std::collections::HashMap<String, Option<String>>>,
}

#[derive(Debug)]
pub struct Profile<S: AsRef<str>> {
	pub id_tag: S,
	pub name: S,
	pub typ: ProfileType,
	pub profile_pic: Option<S>,
	pub status: Option<ProfileStatus>,
	pub synced_at: Option<Timestamp>,
	pub following: bool,
	pub connected: ProfileConnectionStatus,
	pub roles: Option<Box<[Box<str>]>>,
	pub trust: Option<ProfileTrust>,
}

#[derive(Debug, Default, Deserialize)]
pub struct ListProfileOptions {
	#[serde(rename = "type")]
	pub typ: Option<ProfileType>,
	pub status: Option<Box<[ProfileStatus]>>,
	pub connected: Option<ProfileConnectionStatus>,
	pub following: Option<bool>,
	pub q: Option<String>,
	pub id_tag: Option<String>,
	/// Filter profiles by whether a trust preference is set.
	/// `Some(true)` returns only profiles with a non-null trust value;
	/// `Some(false)` returns only profiles with NULL trust; `None` does not filter.
	pub trust_set: Option<bool>,
}

/// Profile data returned from adapter queries
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ProfileData {
	pub id_tag: Box<str>,
	pub name: Box<str>,
	#[serde(rename = "type")]
	pub r#type: Box<str>, // "person" or "community"
	pub profile_pic: Option<Box<str>>,
	/// Federation lifecycle: "active" | "trusted" | "suspended" | "blocked" | "muted" | "banned"
	#[serde(default, skip_serializing_if = "Option::is_none")]
	pub status: Option<Box<str>>,
	#[serde(serialize_with = "serialize_timestamp_iso")]
	pub created_at: Timestamp,
}

/// List of profiles response
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProfileList {
	pub profiles: Vec<ProfileData>,
	pub total: usize,
	pub limit: usize,
	pub offset: usize,
}

#[derive(Debug, Default, Deserialize)]
pub struct UpdateProfileData {
	// Profile content fields
	#[serde(default)]
	pub name: Patch<Box<str>>,
	#[serde(default, rename = "profilePic")]
	pub profile_pic: Patch<Option<Box<str>>>,
	#[serde(default)]
	pub roles: Patch<Option<Vec<Box<str>>>>,

	// Status and moderation
	#[serde(default)]
	pub status: Patch<ProfileStatus>,

	// Relationship fields
	#[serde(default)]
	pub synced: Patch<bool>,
	#[serde(default)]
	pub following: Patch<bool>,
	#[serde(default)]
	pub connected: Patch<ProfileConnectionStatus>,
	#[serde(default)]
	pub trust: Patch<ProfileTrust>,

	// Sync metadata
	#[serde(default)]
	pub etag: Patch<Box<str>>,
}

/// Outcome of an `upsert_profile` call.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum UpsertResult {
	/// The profile row did not exist and was inserted.
	Created,
	/// The profile row existed and was updated.
	Updated,
}

/// Fields for `MetaAdapter::upsert_profile`.
///
/// All fields are `Patch` and apply to both INSERT and UPDATE:
/// * `Patch::Value(v)` / `Patch::Null` → set the column on both branches.
/// * `Patch::Undefined` → leave the column at its current value on UPDATE,
///   and use the column default (NULL or `""` for `name`) on INSERT.
///
/// **Note on the INSERT branch:** `Patch::Null` and `Patch::Undefined`
/// collapse to the same column default for most fields — the INSERT can't
/// distinguish "user explicitly set to NULL" from "user didn't touch this
/// field." This is fine semantically (both mean "no value here"), but
/// differs from UPDATE, which preserves the existing value on `Undefined`.
///
/// **Stub-row idiom:** `upsert_profile` creates a row with `type = NULL`
/// when `typ` is `Patch::Undefined`. These stub rows are filtered out of
/// `list_profiles` (which requires `type IS NOT NULL`), but `read_profile` /
/// `get_info` will return `Error::NotFound` for them. This is intentional:
/// relationship hooks (FOLLOW, FSHR) create stubs first and federation sync
/// populates `type` later. Callers performing read-then-write should not
/// rely on `read_profile` finding a freshly-inserted stub.
#[derive(Default)]
pub struct UpsertProfileFields {
	pub name: Patch<Box<str>>,
	pub typ: Patch<ProfileType>,
	pub profile_pic: Patch<Option<Box<str>>>,
	pub roles: Patch<Option<Vec<Box<str>>>>,
	pub status: Patch<ProfileStatus>,
	pub synced: Patch<bool>,
	pub following: Patch<bool>,
	pub connected: Patch<ProfileConnectionStatus>,
	pub trust: Patch<ProfileTrust>,
	pub etag: Patch<Box<str>>,
}

impl UpsertProfileFields {
	/// Build an `UpsertProfileFields` from an existing `UpdateProfileData`.
	///
	/// `typ` is left `Undefined` — callers that know the profile type should
	/// set it explicitly.
	pub fn from_update(update: UpdateProfileData) -> Self {
		Self {
			name: update.name,
			typ: Patch::Undefined,
			profile_pic: update.profile_pic,
			roles: update.roles,
			status: update.status,
			synced: update.synced,
			following: update.following,
			connected: update.connected,
			trust: update.trust,
			etag: update.etag,
		}
	}
}

// Actions
//*********

/// Additional action data (cached counts/stats)
#[derive(Debug, Clone)]
pub struct ActionData {
	pub subject: Option<Box<str>>,
	pub reactions: Option<Box<str>>,
	pub comments: Option<u32>,
}

/// Options for updating action metadata
#[derive(Debug, Clone, Default)]
pub struct UpdateActionDataOptions {
	pub subject: Patch<String>,
	pub reactions: Patch<String>,
	pub comments: Patch<u32>,
	pub comments_read: Patch<u32>,
	pub status: Patch<char>,
	pub visibility: Patch<char>,
	pub x: Patch<serde_json::Value>, // Extensible metadata (x.role for SUBS, etc.)
	pub content: Patch<String>,
	pub attachments: Patch<String>, // Comma-separated list of attachment IDs
	pub flags: Patch<String>,
	pub sub_typ: Patch<String>,
	/// Dual-purpose for actions in status `R` (draft) or `S` (scheduled): the
	/// `actions.created_at` column holds the target publish instant, not the
	/// row's actual creation time. PATCH /actions, `publish_draft`, and
	/// `task::handle_create_action` all rely on this overload. For any other
	/// status, leave this `Patch::Undefined` — overwriting `created_at` on a
	/// finalized (`A`) action would corrupt the timeline.
	pub created_at: Patch<Timestamp>,
}

/// Options for finalizing an action (resolved fields from ActionCreatorTask)
#[derive(Debug, Clone, Default)]
pub struct FinalizeActionOptions<'a> {
	pub attachments: Option<&'a [&'a str]>,
	pub subject: Option<&'a str>,
	pub audience_tag: Option<&'a str>,
	pub key: Option<&'a str>,
}

fn deserialize_split<'de, D>(deserializer: D) -> Result<Option<Vec<String>>, D::Error>
where
	D: serde::Deserializer<'de>,
{
	let s = String::deserialize(deserializer)?;
	let values: Vec<String> =
		s.split(',').map(|v| v.trim().to_string()).filter(|v| !v.is_empty()).collect();
	if values.is_empty() { Ok(None) } else { Ok(Some(values)) }
}

/// Audience filter axis: classify actions by the **type of the effective wall
/// owner** (`coalesce(audience, issuer_tag)` joined to `profiles.type`).
/// `Personal` matches `pa.type='P'` (with NULL→Personal fallback for unknown
/// remote profiles). `Community` matches `pa.type='C'`.
/// Combines with `audience` (specific community) as AND.
#[derive(Debug, Clone, Copy, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum AudienceType {
	Personal,
	Community,
}

/// Options for listing actions
#[derive(Debug, Default, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ListActionOptions {
	/// Maximum number of items to return (default: 20)
	pub limit: Option<u32>,
	/// Cursor for pagination (opaque base64-encoded string)
	pub cursor: Option<String>,
	/// Sort order: 'created' (default, created_at DESC)
	pub sort: Option<String>,
	/// Sort direction: 'asc' or 'desc' (default: desc)
	#[serde(rename = "sortDir")]
	pub sort_dir: Option<String>,
	#[serde(default, rename = "type", deserialize_with = "deserialize_split")]
	pub typ: Option<Vec<String>>,
	#[serde(default, deserialize_with = "deserialize_split")]
	pub status: Option<Vec<String>>,
	pub tag: Option<String>,
	pub search: Option<String>,
	#[serde(default, deserialize_with = "deserialize_split")]
	pub visibility: Option<Vec<String>>,
	pub issuer: Option<String>,
	pub audience: Option<String>,
	#[serde(rename = "audienceType")]
	pub audience_type: Option<AudienceType>,
	pub involved: Option<String>,
	/// The authenticated user's id_tag (set by handler, not from query params)
	#[serde(skip)]
	pub viewer_id_tag: Option<String>,
	#[serde(rename = "actionId")]
	pub action_id: Option<String>,
	#[serde(rename = "parentId")]
	pub parent_id: Option<String>,
	#[serde(rename = "rootId")]
	pub root_id: Option<String>,
	pub subject: Option<String>,
	#[serde(rename = "createdAfter")]
	pub created_after: Option<Timestamp>,
}

#[skip_serializing_none]
#[derive(Debug, Clone, Serialize)]
pub struct ProfileInfo {
	#[serde(rename = "idTag")]
	pub id_tag: Box<str>,
	pub name: Box<str>,
	#[serde(rename = "type")]
	pub typ: ProfileType,
	#[serde(rename = "profilePic")]
	pub profile_pic: Option<Box<str>>,
}

pub struct Action<S: AsRef<str>> {
	pub action_id: S,
	pub typ: S,
	pub sub_typ: Option<S>,
	pub issuer_tag: S,
	pub parent_id: Option<S>,
	pub root_id: Option<S>,
	pub audience_tag: Option<S>,
	pub content: Option<S>,
	pub attachments: Option<Vec<S>>,
	pub subject: Option<S>,
	pub created_at: Timestamp,
	pub expires_at: Option<Timestamp>,
	pub visibility: Option<char>, // None: Direct, P: Public, V: Verified, 2: 2nd degree, F: Follower, C: Connected
	pub flags: Option<S>,         // Action flags: R/r (reactions), C/c (comments), O/o (open)
	pub x: Option<serde_json::Value>, // Extensible metadata (x.role for SUBS, etc.)
}

#[skip_serializing_none]
#[derive(Debug, Clone, Serialize)]
pub struct AttachmentView {
	#[serde(rename = "fileId")]
	pub file_id: Box<str>,
	pub dim: Option<(u32, u32)>,
	#[serde(rename = "localVariants")]
	pub local_variants: Option<Vec<Box<str>>>,
}

#[skip_serializing_none]
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ActionView {
	pub action_id: Box<str>,
	#[serde(rename = "type")]
	pub typ: Box<str>,
	#[serde(rename = "subType")]
	pub sub_typ: Option<Box<str>>,
	pub parent_id: Option<Box<str>>,
	pub root_id: Option<Box<str>>,
	pub issuer: ProfileInfo,
	pub audience: Option<ProfileInfo>,
	pub content: Option<serde_json::Value>,
	pub attachments: Option<Vec<AttachmentView>>,
	pub subject: Option<Box<str>>,
	pub subject_profile: Option<ProfileInfo>,
	#[serde(serialize_with = "serialize_timestamp_iso")]
	pub created_at: Timestamp,
	#[serde(serialize_with = "serialize_timestamp_iso_opt")]
	pub expires_at: Option<Timestamp>,
	pub status: Option<Box<str>>,
	pub stat: Option<serde_json::Value>,
	pub visibility: Option<char>,
	pub flags: Option<Box<str>>, // Action flags: R/r (reactions), C/c (comments), O/o (open)
	pub x: Option<serde_json::Value>, // Extensible metadata (x.role for SUBS, etc.)
}

// Files
//*******
#[derive(Debug)]
pub enum FileId<S: AsRef<str>> {
	FileId(S),
	FId(u64),
}

pub enum ActionId<S: AsRef<str>> {
	ActionId(S),
	AId(u64),
}

/// File status enum
/// Note: Mutability is determined by fileTp (BLOB=immutable, CRDT/RTDB=mutable)
#[derive(Debug, Clone, Copy, Deserialize, Serialize)]
pub enum FileStatus {
	#[serde(rename = "A")]
	Active,
	#[serde(rename = "P")]
	Pending,
	#[serde(rename = "D")]
	Deleted,
}

/// User-specific file metadata (access tracking, pinned/starred status)
#[skip_serializing_none]
#[derive(Debug, Clone, Default, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct FileUserData {
	#[serde(serialize_with = "serialize_timestamp_iso_opt")]
	pub accessed_at: Option<Timestamp>,
	#[serde(serialize_with = "serialize_timestamp_iso_opt")]
	pub modified_at: Option<Timestamp>,
	pub pinned: bool,
	pub starred: bool,
}

#[skip_serializing_none]
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct FileView {
	pub file_id: Box<str>,
	pub parent_id: Option<Box<str>>, // Parent folder file_id (None = root)
	pub root_id: Option<Box<str>>,   // Document tree root file_id (None = standalone)
	pub owner: Option<ProfileInfo>,
	pub creator: Option<ProfileInfo>,
	pub preset: Option<Box<str>>,
	pub content_type: Option<Box<str>>,
	pub file_name: Box<str>,
	pub file_tp: Option<Box<str>>, // 'BLOB', 'CRDT', 'RTDB', 'FLDR'
	#[serde(serialize_with = "serialize_timestamp_iso")]
	pub created_at: Timestamp,
	#[serde(serialize_with = "crate::types::serialize_timestamp_iso_opt")]
	pub accessed_at: Option<Timestamp>, // Global: when anyone last accessed
	#[serde(serialize_with = "crate::types::serialize_timestamp_iso_opt")]
	pub modified_at: Option<Timestamp>, // Global: when anyone last modified
	pub status: FileStatus,
	pub tags: Option<Vec<Box<str>>>,
	pub visibility: Option<char>, // None: Direct, P: Public, V: Verified, 2: 2nd degree, F: Follower, C: Connected
	pub hidden: bool,
	pub access_level: Option<crate::types::AccessLevel>, // User's access level to this file (R/W)
	pub user_data: Option<FileUserData>, // User-specific data (only when authenticated)
	pub x: Option<serde_json::Value>, // Extensible metadata (e.g., {"dim": [width, height]} for images)
}

#[skip_serializing_none]
#[derive(Debug, Clone, Serialize)]
pub struct FileVariant<S: AsRef<str> + Debug> {
	#[serde(rename = "variantId")]
	pub variant_id: S,
	pub variant: S,
	pub format: S,
	pub size: u64,
	pub resolution: (u32, u32),
	pub available: bool,
	/// Duration in seconds (for video/audio)
	pub duration: Option<f64>,
	/// Bitrate in kbps (for video/audio)
	pub bitrate: Option<u32>,
	/// Page count (for documents like PDF)
	#[serde(rename = "pageCount")]
	pub page_count: Option<u32>,
}

impl<S: AsRef<str> + Debug> PartialEq for FileVariant<S> {
	fn eq(&self, other: &Self) -> bool {
		self.variant_id.as_ref() == other.variant_id.as_ref()
			&& self.variant.as_ref() == other.variant.as_ref()
			&& self.format.as_ref() == other.format.as_ref()
			&& self.size == other.size
			&& self.resolution == other.resolution
			&& self.available == other.available
			&& self.duration == other.duration
			&& self.bitrate == other.bitrate
			&& self.page_count == other.page_count
	}
}

impl<S: AsRef<str> + Debug> Eq for FileVariant<S> {}

impl<S: AsRef<str> + Debug + Ord> PartialOrd for FileVariant<S> {
	fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
		Some(self.cmp(other))
	}
}

impl<S: AsRef<str> + Debug + Ord> Ord for FileVariant<S> {
	fn cmp(&self, other: &Self) -> Ordering {
		self.size
			.cmp(&other.size)
			.then_with(|| self.resolution.0.cmp(&other.resolution.0))
			.then_with(|| self.resolution.1.cmp(&other.resolution.1))
			.then_with(|| self.variant.as_ref().cmp(other.variant.as_ref()))
	}
}

/// Options for listing files
///
/// By default (when `status` is `None`), deleted files (status 'D') are excluded.
/// To include deleted files, explicitly set `status` to `FileStatus::Deleted`.
#[derive(Debug, Default, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ListFileOptions {
	/// Maximum number of items to return (default: 30)
	pub limit: Option<u32>,
	/// Cursor for pagination (opaque base64-encoded string)
	pub cursor: Option<String>,
	#[serde(default, rename = "fileId", deserialize_with = "deserialize_split")]
	pub file_id: Option<Vec<String>>,
	#[serde(rename = "parentId")]
	pub parent_id: Option<String>, // Filter by parent folder (None = root, "__trash__" = trash)
	#[serde(rename = "rootId")]
	pub root_id: Option<String>, // Filter by document tree root
	pub tag: Option<String>,
	pub preset: Option<String>,
	pub variant: Option<String>,
	/// File status filter. If None, excludes deleted files by default.
	pub status: Option<FileStatus>,
	#[serde(default, rename = "fileTp", deserialize_with = "deserialize_split")]
	pub file_type: Option<Vec<String>>,
	/// Filter by content type pattern (e.g., "image/*", "video/*")
	#[serde(default, rename = "contentType", deserialize_with = "deserialize_split")]
	pub content_type: Option<Vec<String>>,
	/// Substring search in file name
	#[serde(rename = "fileName")]
	pub file_name: Option<String>,
	/// Filter by owner id_tag
	#[serde(rename = "ownerIdTag")]
	pub owner_id_tag: Option<String>,
	/// Exclude files by this owner id_tag
	#[serde(rename = "notOwnerIdTag")]
	pub not_owner_id_tag: Option<String>,
	/// Filter by pinned status (user-specific)
	pub pinned: Option<bool>,
	/// Filter by starred status (user-specific)
	pub starred: Option<bool>,
	/// Hidden file filter. None = exclude hidden (default). Some(true) = only hidden.
	pub hidden: Option<bool>,
	/// Sort order: 'recent' (accessed_at), 'modified' (modified_at), 'name', 'created'
	pub sort: Option<String>,
	/// Sort direction: 'asc' or 'desc' (default: desc for dates, asc for name)
	#[serde(rename = "sortDir")]
	pub sort_dir: Option<String>,
	/// User id_tag for user-specific data (set by handler, not from query)
	#[serde(skip)]
	pub user_id_tag: Option<String>,
	/// Scope file_id filter: returns files matching this file_id OR having this root_id.
	/// Overrides the normal root_id IS NULL constraint. Set by handler for scoped tokens.
	#[serde(skip)]
	pub scope_file_id: Option<String>,
	/// Allowed visibility levels for SQL-level filtering (correct pagination).
	/// None = no filter (owner sees all including NULL/Direct).
	/// Set by handler based on subject's access level via `SubjectAccessLevel::visible_levels()`.
	#[serde(skip)]
	pub visible_levels: Option<Vec<char>>,
}

#[derive(Debug, Clone, Default)]
pub struct CreateFile {
	pub orig_variant_id: Option<Box<str>>,
	pub file_id: Option<Box<str>>,
	pub parent_id: Option<Box<str>>, // Parent folder file_id (None = root)
	pub root_id: Option<Box<str>>,   // Document tree root file_id (None = standalone)
	pub owner_tag: Option<Box<str>>, // Set only for files owned by someone OTHER than the tenant (e.g., shared files)
	pub creator_tag: Option<Box<str>>, // The user who actually created the file
	pub preset: Option<Box<str>>,
	pub content_type: Box<str>,
	pub file_name: Box<str>,
	pub file_tp: Option<Box<str>>, // 'BLOB', 'CRDT', 'RTDB', 'FLDR' - defaults to 'BLOB'
	pub created_at: Option<Timestamp>,
	pub tags: Option<Vec<Box<str>>>,
	pub x: Option<serde_json::Value>,
	pub visibility: Option<char>, // None: Direct (default), P: Public, V: Verified, 2: 2nd degree, F: Follower, C: Connected
	pub hidden: bool,
	pub status: Option<FileStatus>, // None defaults to Pending, can set to Active for shared files
}

#[derive(Debug, Clone, Deserialize)]
pub struct CreateFileVariant {
	pub variant: Box<str>,
	pub format: Box<str>,
	pub resolution: (u32, u32),
	pub size: u64,
	pub available: bool,
}

/// Options for updating file metadata
#[derive(Debug, Clone, Default, Deserialize)]
pub struct UpdateFileOptions {
	#[serde(default, rename = "fileName")]
	pub file_name: Patch<String>,
	#[serde(default, rename = "parentId")]
	pub parent_id: Patch<String>, // Move file to different folder (null = root)
	#[serde(default)]
	pub visibility: Patch<char>,
	#[serde(default)]
	pub status: Patch<char>,
	#[serde(default)]
	pub hidden: Patch<bool>,
}

// Share Entries
//**************

#[skip_serializing_none]
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ShareEntry {
	pub id: i64,
	pub resource_type: char,
	pub resource_id: Box<str>,
	pub subject_type: char,
	pub subject_id: Box<str>,
	pub permission: char,
	#[serde(serialize_with = "serialize_timestamp_iso_opt")]
	pub expires_at: Option<Timestamp>,
	pub created_by: Box<str>,
	#[serde(serialize_with = "serialize_timestamp_iso")]
	pub created_at: Timestamp,
	// Enrichment fields (populated by JOINs in list_by_resource)
	pub subject_file_name: Option<Box<str>>,
	pub subject_content_type: Option<Box<str>>,
	pub subject_file_tp: Option<Box<str>>,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CreateShareEntry {
	pub subject_type: char,
	pub subject_id: String,
	pub permission: char,
	pub expires_at: Option<Timestamp>,
}

// Push Subscriptions
//********************

/// Web Push subscription data (RFC 8030)
#[skip_serializing_none]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PushSubscriptionData {
	/// Push endpoint URL
	pub endpoint: String,
	/// Expiration time (Unix timestamp, if provided by browser)
	#[serde(rename = "expirationTime")]
	pub expiration_time: Option<i64>,
	/// Subscription keys (p256dh and auth)
	pub keys: PushSubscriptionKeys,
}

/// Subscription keys for Web Push encryption
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PushSubscriptionKeys {
	/// P-256 public key for encryption (base64url encoded)
	pub p256dh: String,
	/// Authentication secret (base64url encoded)
	pub auth: String,
}

/// Full push subscription record stored in database
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PushSubscription {
	/// Unique subscription ID
	pub id: u64,
	/// The subscription data (endpoint, keys, etc.)
	pub subscription: PushSubscriptionData,
	/// When this subscription was created
	#[serde(serialize_with = "serialize_timestamp_iso")]
	pub created_at: Timestamp,
}

// Tasks
//*******
pub struct Task {
	pub task_id: u64,
	pub tn_id: TnId,
	pub kind: Box<str>,
	pub status: char,
	pub created_at: Timestamp,
	pub next_at: Option<Timestamp>,
	pub input: Box<str>,
	pub output: Box<str>,
	pub deps: Box<[u64]>,
	pub retry: Option<Box<str>>,
	pub cron: Option<Box<str>>,
}

#[derive(Debug, Default)]
pub struct TaskPatch {
	pub input: Patch<String>,
	pub next_at: Patch<Timestamp>,
	pub deps: Patch<Vec<u64>>,
	pub retry: Patch<String>,
	pub cron: Patch<String>,
}

#[derive(Debug, Default)]
pub struct ListTaskOptions {}

// Installed Apps
//***************

/// Data for installing an app
#[derive(Debug)]
pub struct InstallApp {
	pub app_name: Box<str>,
	pub publisher_tag: Box<str>,
	pub version: Box<str>,
	pub action_id: Box<str>,
	pub file_id: Box<str>,
	pub blob_id: Box<str>,
	pub capabilities: Option<Vec<Box<str>>>,
}

/// Installed app record
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct InstalledApp {
	pub app_name: Box<str>,
	pub publisher_tag: Box<str>,
	pub version: Box<str>,
	pub action_id: Box<str>,
	pub file_id: Box<str>,
	pub blob_id: Box<str>,
	pub status: Box<str>,
	pub capabilities: Option<Vec<Box<str>>>,
	pub auto_update: bool,
	#[serde(serialize_with = "serialize_timestamp_iso")]
	pub installed_at: Timestamp,
}

// Contacts / Address Books (CardDAV + JSON REST)
//*************************************************

/// Address book collection metadata
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AddressBook {
	pub ab_id: u64,
	pub name: Box<str>,
	pub description: Option<Box<str>>,
	/// Collection tag — changes on any contact mutation within this book (used by CardDAV sync)
	pub ctag: Box<str>,
	#[serde(serialize_with = "serialize_timestamp_iso")]
	pub created_at: Timestamp,
	#[serde(serialize_with = "serialize_timestamp_iso")]
	pub updated_at: Timestamp,
}

#[derive(Debug, Default)]
pub struct UpdateAddressBookData {
	pub name: Patch<String>,
	pub description: Patch<String>,
}

/// Indexed projection of a contact — lives in DB columns, parallel to the stored vCard blob.
/// Used both for REST API responses (via the handler layer's JSON conversion) and for
/// CardDAV `addressbook-query` REPORT text-match filtering.
#[derive(Debug, Clone, Default)]
pub struct ContactExtracted {
	pub fn_name: Option<Box<str>>,
	pub given_name: Option<Box<str>>,
	pub family_name: Option<Box<str>>,
	pub email: Option<Box<str>>,
	pub emails: Option<Box<str>>,
	pub tel: Option<Box<str>>,
	pub tels: Option<Box<str>>,
	pub org: Option<Box<str>>,
	pub title: Option<Box<str>>,
	pub note: Option<Box<str>>,
	pub photo_uri: Option<Box<str>>,
	pub profile_id_tag: Option<Box<str>>,
}

/// Full contact row including the authoritative stored vCard blob.
#[derive(Debug, Clone)]
pub struct Contact {
	pub c_id: u64,
	pub ab_id: u64,
	pub uid: Box<str>,
	pub etag: Box<str>,
	pub vcard: Box<str>,
	pub extracted: ContactExtracted,
	pub created_at: Timestamp,
	pub updated_at: Timestamp,
}

/// Contact summary without the vCard blob — for list endpoints (REST + CardDAV REPORTs that
/// don't need the full body).
#[derive(Debug, Clone)]
pub struct ContactView {
	pub c_id: u64,
	pub ab_id: u64,
	pub uid: Box<str>,
	pub etag: Box<str>,
	pub extracted: ContactExtracted,
	pub created_at: Timestamp,
	pub updated_at: Timestamp,
}

/// One entry in a CardDAV `sync-collection` REPORT response. Tombstones (`deleted: true`)
/// let clients drop stale cards.
#[derive(Debug, Clone)]
pub struct ContactSyncEntry {
	pub uid: Box<str>,
	pub etag: Box<str>,
	pub deleted: bool,
	pub updated_at: Timestamp,
}

#[derive(Debug, Default)]
pub struct ListContactOptions {
	/// Free-text query — matches against fn_name, emails, tels (SQL LIKE).
	pub q: Option<String>,
	/// Opaque cursor for pagination.
	pub cursor: Option<String>,
	/// Page size.
	pub limit: Option<u32>,
}

// Calendars / Calendar Objects (CalDAV + JSON REST)
//***************************************************

/// Calendar collection metadata. Parallels `AddressBook`.
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Calendar {
	pub cal_id: u64,
	pub name: Box<str>,
	pub description: Option<Box<str>>,
	/// CSS `#RRGGBB` hex for client colouring (CalendarServer `calendar-color` ext).
	pub color: Option<Box<str>>,
	/// Default VTIMEZONE blob, surfaced via CalDAV `calendar-timezone`.
	pub timezone: Option<Box<str>>,
	/// Comma-separated component set (`VEVENT,VTODO`) — powers `supported-calendar-component-set`.
	pub components: Box<str>,
	/// Collection tag — bumps on any calendar-object mutation (used by CalDAV sync).
	pub ctag: Box<str>,
	#[serde(serialize_with = "serialize_timestamp_iso")]
	pub created_at: Timestamp,
	#[serde(serialize_with = "serialize_timestamp_iso")]
	pub updated_at: Timestamp,
}

#[derive(Debug, Default)]
pub struct CreateCalendarData {
	pub name: String,
	pub description: Option<String>,
	pub color: Option<String>,
	pub timezone: Option<String>,
	/// If `None`, defaults to `VEVENT,VTODO`.
	pub components: Option<String>,
}

#[derive(Debug, Default)]
pub struct UpdateCalendarData {
	pub name: Patch<String>,
	pub description: Patch<String>,
	pub color: Patch<String>,
	pub timezone: Patch<String>,
	pub components: Patch<String>,
}

/// Indexed projection of a calendar object — lives in DB columns alongside the authoritative
/// iCalendar blob. Enables `calendar-query` time-range filtering and REST search.
#[derive(Debug, Clone, Default)]
pub struct CalendarObjectExtracted {
	/// `VEVENT` | `VTODO` (first primary component in the VCALENDAR; overrides share it).
	pub component: Box<str>,
	pub summary: Option<Box<str>>,
	pub location: Option<Box<str>>,
	pub description: Option<Box<str>>,
	/// Master DTSTART as unix seconds (UTC). `None` for floating/undated VTODO.
	pub dtstart: Option<Timestamp>,
	/// DTEND for VEVENT, DUE for VTODO, as unix seconds (UTC). `None` for open-ended.
	pub dtend: Option<Timestamp>,
	/// True when DTSTART is `VALUE=DATE`.
	pub all_day: bool,
	/// `STATUS` value (CONFIRMED / TENTATIVE / CANCELLED / NEEDS-ACTION / COMPLETED / IN-PROCESS).
	pub status: Option<Box<str>>,
	/// `PRIORITY` 0..9 (primarily VTODO).
	pub priority: Option<u8>,
	pub organizer: Option<Box<str>>,
	/// Raw RRULE string — presence signals recurrence; expansion is client-side.
	pub rrule: Option<Box<str>>,
	/// `EXDATE` exclusions on the master as unix seconds; empty for override rows.
	pub exdate: Vec<Timestamp>,
	/// `RECURRENCE-ID` as unix seconds for override instances; `None` for the master row.
	pub recurrence_id: Option<Timestamp>,
	pub sequence: i64,
}

/// Borrowed write payload for calendar-object upserts. Groups the four fields that always
/// travel together (authoritative blob + its derived etag + indexed projection) so trait
/// methods writing multiple objects in one tx don't accumulate parallel-scalar parameter
/// lists.
#[derive(Debug, Clone, Copy)]
pub struct CalendarObjectWrite<'a> {
	pub uid: &'a str,
	pub ical: &'a str,
	pub etag: &'a str,
	pub extracted: &'a CalendarObjectExtracted,
}

/// Full calendar object row including the authoritative stored VCALENDAR blob.
#[derive(Debug, Clone)]
pub struct CalendarObject {
	pub co_id: u64,
	pub cal_id: u64,
	pub uid: Box<str>,
	pub etag: Box<str>,
	pub ical: Box<str>,
	pub extracted: CalendarObjectExtracted,
	pub created_at: Timestamp,
	pub updated_at: Timestamp,
}

/// Calendar object summary without the iCalendar blob — for list endpoints.
#[derive(Debug, Clone)]
pub struct CalendarObjectView {
	pub co_id: u64,
	pub cal_id: u64,
	pub uid: Box<str>,
	pub etag: Box<str>,
	pub extracted: CalendarObjectExtracted,
	pub created_at: Timestamp,
	pub updated_at: Timestamp,
}

/// One entry in a CalDAV `sync-collection` REPORT response. Tombstones (`deleted: true`) let
/// clients drop stale objects.
#[derive(Debug, Clone)]
pub struct CalendarObjectSyncEntry {
	pub uid: Box<str>,
	pub etag: Box<str>,
	pub deleted: bool,
	pub updated_at: Timestamp,
}

#[derive(Debug, Default)]
pub struct ListCalendarObjectOptions {
	/// Restrict to a component (`VEVENT` or `VTODO`); `None` lists both.
	pub component: Option<String>,
	/// Free-text query matched against summary / location / description.
	pub q: Option<String>,
	/// Time-range start (inclusive, unix seconds).
	pub start: Option<Timestamp>,
	/// Time-range end (exclusive, unix seconds).
	pub end: Option<Timestamp>,
	pub cursor: Option<String>,
	pub limit: Option<u32>,
	/// Include recurrence-exception rows (`RECURRENCE-ID IS NOT NULL`) in the result set.
	/// Default `false` preserves CalDAV/legacy semantics where list endpoints return masters only.
	pub include_exceptions: bool,
}

#[async_trait]
pub trait MetaAdapter: Debug + Send + Sync {
	// Tenant management
	//*******************

	/// Reads a tenant profile
	async fn read_tenant(&self, tn_id: TnId) -> ClResult<Tenant<Box<str>>>;

	/// Creates a new tenant
	async fn create_tenant(&self, tn_id: TnId, id_tag: &str) -> ClResult<TnId>;

	/// Updates a tenant
	async fn update_tenant(&self, tn_id: TnId, tenant: &UpdateTenantData) -> ClResult<()>;

	/// Deletes a tenant
	async fn delete_tenant(&self, tn_id: TnId) -> ClResult<()>;

	/// Lists all tenants (for admin use)
	async fn list_tenants(&self, opts: &ListTenantsMetaOptions) -> ClResult<Vec<TenantListMeta>>;

	/// Lists all profiles matching a set of options
	async fn list_profiles(
		&self,
		tn_id: TnId,
		opts: &ListProfileOptions,
	) -> ClResult<Vec<Profile<Box<str>>>>;

	/// Get relationships between the current user and multiple target profiles
	///
	/// Efficiently queries relationship status (following, connected) for multiple profiles
	/// in a single database call, avoiding N+1 query patterns.
	///
	/// Returns: HashMap<target_id_tag, (following: bool, connected: bool)>
	async fn get_relationships(
		&self,
		tn_id: TnId,
		target_id_tags: &[&str],
	) -> ClResult<HashMap<String, (bool, bool)>>;

	/// Reads a profile
	///
	/// Returns an `(etag, Profile)` tuple.
	async fn read_profile(
		&self,
		tn_id: TnId,
		id_tag: &str,
	) -> ClResult<(Box<str>, Profile<Box<str>>)>;

	/// Read profile roles for access token generation
	async fn read_profile_roles(
		&self,
		tn_id: TnId,
		id_tag: &str,
	) -> ClResult<Option<Box<[Box<str>]>>>;

	/// Insert a profile row if missing, otherwise update it.
	///
	/// Returns `UpsertResult::Created` if the row was inserted, or
	/// `UpsertResult::Updated` if an existing row was updated. Never returns
	/// `Error::Conflict` or `Error::NotFound` — the operation is idempotent
	/// with respect to row existence.
	async fn upsert_profile(
		&self,
		tn_id: TnId,
		id_tag: &str,
		fields: &UpsertProfileFields,
	) -> ClResult<UpsertResult>;

	/// Reads the public key of a profile
	///
	/// Returns a `(public key, expiration)` tuple.
	async fn read_profile_public_key(
		&self,
		id_tag: &str,
		key_id: &str,
	) -> ClResult<(Box<str>, Timestamp)>;
	/// Cache a federated profile public key.
	///
	/// `expires_at` is the owner-declared key expiration from the remote profile.
	/// `None` means the owner did not declare an expiration; the implementation
	/// may store it as NULL (treated as "never expires" by `read_profile_public_key`).
	async fn add_profile_public_key(
		&self,
		id_tag: &str,
		key_id: &str,
		public_key: &str,
		expires_at: Option<Timestamp>,
	) -> ClResult<()>;
	/// List stale profiles that need refreshing
	///
	/// Returns profiles where:
	/// - `synced_at IS NULL` (never synced — always eligible), OR
	/// - `synced_at < now - max_age_secs` AND `synced_at >= now - disable_after_secs`
	///   (stale but not yet abandoned).
	///
	/// Profiles with `synced_at < now - disable_after_secs` are excluded so the
	/// refresh batch stops attempting persistently failing remotes.
	/// Returns `Vec<(tn_id, id_tag, etag)>` tuples for conditional refresh requests.
	async fn list_stale_profiles(
		&self,
		max_age_secs: i64,
		disable_after_secs: i64,
		limit: u32,
	) -> ClResult<Vec<(TnId, Box<str>, Option<Box<str>>)>>;

	// Action management
	//*******************
	async fn get_action_id(&self, tn_id: TnId, a_id: u64) -> ClResult<Box<str>>;
	async fn list_actions(
		&self,
		tn_id: TnId,
		opts: &ListActionOptions,
	) -> ClResult<Vec<ActionView>>;
	async fn list_action_tokens(
		&self,
		tn_id: TnId,
		opts: &ListActionOptions,
	) -> ClResult<Box<[Box<str>]>>;

	async fn create_action(
		&self,
		tn_id: TnId,
		action: &Action<&str>,
		key: Option<&str>,
	) -> ClResult<ActionId<Box<str>>>;

	async fn finalize_action(
		&self,
		tn_id: TnId,
		a_id: u64,
		action_id: &str,
		options: FinalizeActionOptions<'_>,
	) -> ClResult<()>;

	async fn create_inbound_action(
		&self,
		tn_id: TnId,
		action_id: &str,
		token: &str,
		ack_token: Option<&str>,
	) -> ClResult<()>;

	/// Get the root_id of an action
	async fn get_action_root_id(&self, tn_id: TnId, action_id: &str) -> ClResult<Box<str>>;

	/// Get action data (subject, reaction count, comment count)
	async fn get_action_data(&self, tn_id: TnId, action_id: &str) -> ClResult<Option<ActionData>>;

	/// Get action by key
	async fn get_action_by_key(
		&self,
		tn_id: TnId,
		action_key: &str,
	) -> ClResult<Option<Action<Box<str>>>>;

	/// Store action token for federation (called when action is created)
	async fn store_action_token(&self, tn_id: TnId, action_id: &str, token: &str) -> ClResult<()>;

	/// Get action token for federation
	async fn get_action_token(&self, tn_id: TnId, action_id: &str) -> ClResult<Option<Box<str>>>;

	/// Update action data (subject, reactions, comments, status)
	async fn update_action_data(
		&self,
		tn_id: TnId,
		action_id: &str,
		opts: &UpdateActionDataOptions,
	) -> ClResult<()>;

	/// Update inbound action status
	async fn update_inbound_action(
		&self,
		tn_id: TnId,
		action_id: &str,
		status: Option<char>,
	) -> ClResult<()>;

	/// Get related action tokens by APRV action_id
	/// Returns list of (action_id, token) pairs for actions that have ack = aprv_action_id
	async fn get_related_action_tokens(
		&self,
		tn_id: TnId,
		aprv_action_id: &str,
	) -> ClResult<Vec<(Box<str>, Box<str>)>>;

	// File management
	//*****************
	async fn get_file_id(&self, tn_id: TnId, f_id: u64) -> ClResult<Box<str>>;
	async fn list_files(&self, tn_id: TnId, opts: &ListFileOptions) -> ClResult<Vec<FileView>>;
	async fn list_file_variants(
		&self,
		tn_id: TnId,
		file_id: FileId<&str>,
	) -> ClResult<Vec<FileVariant<Box<str>>>>;
	/// List locally available variant names for a file (only those marked available)
	async fn list_available_variants(&self, tn_id: TnId, file_id: &str) -> ClResult<Vec<Box<str>>>;
	async fn read_file_variant(
		&self,
		tn_id: TnId,
		variant_id: &str,
	) -> ClResult<FileVariant<Box<str>>>;
	/// Look up the file_id for a given variant_id
	async fn read_file_id_by_variant(&self, tn_id: TnId, variant_id: &str) -> ClResult<Box<str>>;
	/// Look up the internal f_id for a given file_id (for adding variants to existing files)
	async fn read_f_id_by_file_id(&self, tn_id: TnId, file_id: &str) -> ClResult<u64>;
	async fn create_file(&self, tn_id: TnId, opts: CreateFile) -> ClResult<FileId<Box<str>>>;
	async fn create_file_variant<'a>(
		&'a self,
		tn_id: TnId,
		f_id: u64,
		opts: FileVariant<&'a str>,
	) -> ClResult<&'a str>;
	async fn update_file_id(&self, tn_id: TnId, f_id: u64, file_id: &str) -> ClResult<()>;

	/// Finalize a pending file - sets file_id and transitions status from 'P' to 'A' atomically
	async fn finalize_file(&self, tn_id: TnId, f_id: u64, file_id: &str) -> ClResult<()>;

	// Task scheduler
	//****************
	async fn list_tasks(&self, opts: ListTaskOptions) -> ClResult<Vec<Task>>;
	async fn list_task_ids(&self, kind: &str, keys: &[Box<str>]) -> ClResult<Vec<u64>>;
	async fn create_task(
		&self,
		kind: &'static str,
		key: Option<&str>,
		input: &str,
		deps: &[u64],
	) -> ClResult<u64>;
	async fn update_task_finished(&self, task_id: u64, output: &str) -> ClResult<()>;
	async fn update_task_error(
		&self,
		task_id: u64,
		output: &str,
		next_at: Option<Timestamp>,
	) -> ClResult<()>;

	/// Find a pending task by its key
	async fn find_task_by_key(&self, key: &str) -> ClResult<Option<Task>>;

	/// Update task fields with partial updates
	async fn update_task(&self, task_id: u64, patch: &TaskPatch) -> ClResult<()>;

	/// Find deps that have completed (status != 'P')
	async fn find_completed_deps(&self, deps: &[u64]) -> ClResult<Vec<u64>>;

	// Phase 1: Profile Management
	//****************************
	/// Get a single profile by id_tag
	async fn get_profile_info(&self, tn_id: TnId, id_tag: &str) -> ClResult<ProfileData>;

	// Phase 2: Action Management
	//***************************
	/// Get a single action by action_id
	async fn get_action(&self, tn_id: TnId, action_id: &str) -> ClResult<Option<ActionView>>;

	/// Update action content and attachments (if not yet federated)
	async fn update_action(
		&self,
		tn_id: TnId,
		action_id: &str,
		content: Option<&str>,
		attachments: Option<&[&str]>,
	) -> ClResult<()>;

	/// Delete an action (soft delete with cleanup)
	async fn delete_action(&self, tn_id: TnId, action_id: &str) -> ClResult<()>;

	/// Count active (non-DEL, non-deleted) REACT actions for a given subject, grouped by type
	/// Returns colon-separated format: "L5:V3:W1" (Like=5, Love=3, Wow=1)
	async fn count_reactions(&self, tn_id: TnId, subject_id: &str) -> ClResult<String>;

	// Phase 2: File Management Enhancements
	//**************************************
	/// Delete a file (set status to 'D')
	async fn delete_file(&self, tn_id: TnId, file_id: &str) -> ClResult<()>;

	/// List all child files in a document tree (files with the given root_id)
	async fn list_children_by_root(&self, tn_id: TnId, root_id: &str) -> ClResult<Vec<Box<str>>>;

	// Settings Management
	//*********************
	/// List all settings for a tenant, optionally filtered by prefix
	async fn list_settings(
		&self,
		tn_id: TnId,
		prefix: Option<&[String]>,
	) -> ClResult<std::collections::HashMap<String, serde_json::Value>>;

	/// Read a single setting by name
	async fn read_setting(&self, tn_id: TnId, name: &str) -> ClResult<Option<serde_json::Value>>;

	/// Update or delete a setting (None = delete)
	async fn update_setting(
		&self,
		tn_id: TnId,
		name: &str,
		value: Option<serde_json::Value>,
	) -> ClResult<()>;

	// Reference / Bookmark Management
	//********************************
	/// List all references for a tenant
	async fn list_refs(&self, tn_id: TnId, opts: &ListRefsOptions) -> ClResult<Vec<RefData>>;

	/// Get a specific reference by ID
	async fn get_ref(&self, tn_id: TnId, ref_id: &str) -> ClResult<Option<(Box<str>, Box<str>)>>;

	/// Create a new reference
	async fn create_ref(
		&self,
		tn_id: TnId,
		ref_id: &str,
		opts: &CreateRefOptions,
	) -> ClResult<RefData>;

	/// Delete a reference
	async fn delete_ref(&self, tn_id: TnId, ref_id: &str) -> ClResult<()>;

	/// Use/consume a reference - validates type, expiration, counter, decrements counter
	/// Returns (TnId, id_tag, RefData) of the tenant that owns this ref
	async fn use_ref(
		&self,
		ref_id: &str,
		expected_types: &[&str],
	) -> ClResult<(TnId, Box<str>, RefData)>;

	/// Validate a reference without consuming it - checks type, expiration, counter
	/// Returns (TnId, id_tag, RefData) of the tenant that owns this ref if valid
	async fn validate_ref(
		&self,
		ref_id: &str,
		expected_types: &[&str],
	) -> ClResult<(TnId, Box<str>, RefData)>;

	// Tag Management
	//***************
	/// List all tags for a tenant
	///
	/// # Arguments
	/// * `tn_id` - Tenant ID
	/// * `prefix` - Optional prefix filter
	/// * `with_counts` - If true, include file counts per tag
	/// * `limit` - Optional limit on number of tags returned
	async fn list_tags(
		&self,
		tn_id: TnId,
		prefix: Option<&str>,
		with_counts: bool,
		limit: Option<u32>,
	) -> ClResult<Vec<TagInfo>>;

	/// Add a tag to a file
	async fn add_tag(&self, tn_id: TnId, file_id: &str, tag: &str) -> ClResult<Vec<String>>;

	/// Remove a tag from a file
	async fn remove_tag(&self, tn_id: TnId, file_id: &str, tag: &str) -> ClResult<Vec<String>>;

	// File Management Enhancements
	//****************************
	/// Update file metadata (name, visibility, status)
	async fn update_file_data(
		&self,
		tn_id: TnId,
		file_id: &str,
		opts: &UpdateFileOptions,
	) -> ClResult<()>;

	/// Read file metadata
	async fn read_file(&self, tn_id: TnId, file_id: &str) -> ClResult<Option<FileView>>;

	// File User Data (per-user file activity tracking)
	//**************************************************

	/// Record file access for a user (upserts record, updates accessed_at timestamp)
	async fn record_file_access(&self, tn_id: TnId, id_tag: &str, file_id: &str) -> ClResult<()>;

	/// Record file modification for a user (upserts record, updates modified_at timestamp)
	async fn record_file_modification(
		&self,
		tn_id: TnId,
		id_tag: &str,
		file_id: &str,
	) -> ClResult<()>;

	/// Update file user data (pinned/starred status)
	async fn update_file_user_data(
		&self,
		tn_id: TnId,
		id_tag: &str,
		file_id: &str,
		pinned: Option<bool>,
		starred: Option<bool>,
	) -> ClResult<FileUserData>;

	/// Get file user data for a specific file
	async fn get_file_user_data(
		&self,
		tn_id: TnId,
		id_tag: &str,
		file_id: &str,
	) -> ClResult<Option<FileUserData>>;

	// Push Subscription Management
	//*****************************

	/// List all push subscriptions for a tenant (user)
	///
	/// Returns all active push subscriptions for this tenant.
	/// Each tenant represents a user, so this returns all their device subscriptions.
	async fn list_push_subscriptions(&self, tn_id: TnId) -> ClResult<Vec<PushSubscription>>;

	/// Create a new push subscription
	///
	/// Stores a Web Push subscription for a tenant. The subscription contains
	/// the endpoint URL and encryption keys needed to send push notifications.
	/// Returns the generated subscription ID.
	async fn create_push_subscription(
		&self,
		tn_id: TnId,
		subscription: &PushSubscriptionData,
	) -> ClResult<u64>;

	/// Delete a push subscription by ID
	///
	/// Removes a push subscription. Called when a subscription becomes invalid
	/// (e.g., 410 Gone response from push service) or when user unsubscribes.
	async fn delete_push_subscription(&self, tn_id: TnId, subscription_id: u64) -> ClResult<()>;

	// Share Entry Management
	//***********************

	/// Create a share entry (idempotent on unique constraint)
	async fn create_share_entry(
		&self,
		tn_id: TnId,
		resource_type: char,
		resource_id: &str,
		created_by: &str,
		entry: &CreateShareEntry,
	) -> ClResult<ShareEntry>;

	/// Delete a share entry by ID
	async fn delete_share_entry(&self, tn_id: TnId, id: i64) -> ClResult<()>;

	/// List share entries for a resource
	async fn list_share_entries(
		&self,
		tn_id: TnId,
		resource_type: char,
		resource_id: &str,
	) -> ClResult<Vec<ShareEntry>>;

	/// List share entries by subject (reverse lookup).
	/// If `subject_type` is None, matches all subject types.
	async fn list_share_entries_by_subject(
		&self,
		tn_id: TnId,
		subject_type: Option<char>,
		subject_id: &str,
	) -> ClResult<Vec<ShareEntry>>;

	/// Check if a subject has share access to a resource
	/// Returns the permission char if access exists, None otherwise
	async fn check_share_access(
		&self,
		tn_id: TnId,
		resource_type: char,
		resource_id: &str,
		subject_type: char,
		subject_id: &str,
	) -> ClResult<Option<char>>;

	/// Read a single share entry by ID (for delete validation)
	async fn read_share_entry(&self, tn_id: TnId, id: i64) -> ClResult<Option<ShareEntry>>;

	// Installed App Management
	//*************************

	/// Install an app package
	async fn install_app(&self, tn_id: TnId, install: &InstallApp) -> ClResult<()>;

	/// Uninstall an app by name and publisher
	async fn uninstall_app(&self, tn_id: TnId, app_name: &str, publisher_tag: &str)
	-> ClResult<()>;

	/// List installed apps, optionally filtered by search term
	async fn list_installed_apps(
		&self,
		tn_id: TnId,
		search: Option<&str>,
	) -> ClResult<Vec<InstalledApp>>;

	/// Get a specific installed app
	async fn get_installed_app(
		&self,
		tn_id: TnId,
		app_name: &str,
		publisher_tag: &str,
	) -> ClResult<Option<InstalledApp>>;

	// Address book / contact management
	//***********************************

	/// Create a new address book collection.
	async fn create_address_book(
		&self,
		tn_id: TnId,
		name: &str,
		description: Option<&str>,
	) -> ClResult<AddressBook>;

	/// List all address books for a tenant.
	async fn list_address_books(&self, tn_id: TnId) -> ClResult<Vec<AddressBook>>;

	/// Read a single address book by id.
	async fn get_address_book(&self, tn_id: TnId, ab_id: u64) -> ClResult<Option<AddressBook>>;

	/// Look up an address book by its name (for CardDAV path routing).
	async fn get_address_book_by_name(
		&self,
		tn_id: TnId,
		name: &str,
	) -> ClResult<Option<AddressBook>>;

	/// Patch an address book's metadata.
	async fn update_address_book(
		&self,
		tn_id: TnId,
		ab_id: u64,
		patch: &UpdateAddressBookData,
	) -> ClResult<()>;

	/// Delete an address book (and all its contacts).
	async fn delete_address_book(&self, tn_id: TnId, ab_id: u64) -> ClResult<()>;

	/// List + search contacts. When `ab_id` is `Some`, scopes to that book (cursor
	/// is c_id-ordered). When `None`, queries across all books sorted by name.
	async fn list_contacts(
		&self,
		tn_id: TnId,
		ab_id: Option<u64>,
		opts: &ListContactOptions,
	) -> ClResult<Vec<ContactView>>;

	/// Read a single contact (including vCard blob) by UID.
	async fn get_contact(&self, tn_id: TnId, ab_id: u64, uid: &str) -> ClResult<Option<Contact>>;

	/// Insert or update a contact (keyed by UID). Also bumps the address book's ctag.
	/// Returns the new etag.
	async fn upsert_contact(
		&self,
		tn_id: TnId,
		ab_id: u64,
		uid: &str,
		vcard: &str,
		etag: &str,
		extracted: &ContactExtracted,
	) -> ClResult<Box<str>>;

	/// Soft-delete a contact (sets `deleted_at`), leaving a tombstone row for CardDAV sync.
	/// Also bumps the address book's ctag.
	async fn delete_contact(&self, tn_id: TnId, ab_id: u64, uid: &str) -> ClResult<()>;

	/// Fetch multiple contacts by UID — for CardDAV `addressbook-multiget` REPORT.
	async fn get_contacts_by_uids(
		&self,
		tn_id: TnId,
		ab_id: u64,
		uids: &[&str],
	) -> ClResult<Vec<Contact>>;

	/// Return live + tombstone entries for CardDAV `sync-collection` REPORT.
	/// `since` is the sync token's timestamp; `None` means full sync.
	/// `limit` caps the number of rows returned; callers supply their own hard ceiling
	/// to keep responses bounded. `None` means no client-supplied limit — callers should
	/// still pass their server-side ceiling.
	async fn list_contacts_since(
		&self,
		tn_id: TnId,
		ab_id: u64,
		since: Option<Timestamp>,
		limit: Option<u32>,
	) -> ClResult<Vec<ContactSyncEntry>>;

	/// List all contacts linked to a given profile id_tag (for bulk snapshot refresh).
	async fn list_contacts_by_profile(
		&self,
		tn_id: TnId,
		profile_id_tag: &str,
	) -> ClResult<Vec<Contact>>;

	// Calendar / calendar-object management (CalDAV + JSON REST)
	//************************************************************

	/// Create a new calendar collection.
	async fn create_calendar(&self, tn_id: TnId, input: &CreateCalendarData) -> ClResult<Calendar>;

	/// List all calendars for a tenant.
	async fn list_calendars(&self, tn_id: TnId) -> ClResult<Vec<Calendar>>;

	/// Read a single calendar by id.
	async fn get_calendar(&self, tn_id: TnId, cal_id: u64) -> ClResult<Option<Calendar>>;

	/// Look up a calendar by its name (for CalDAV path routing).
	async fn get_calendar_by_name(&self, tn_id: TnId, name: &str) -> ClResult<Option<Calendar>>;

	/// Patch a calendar's metadata.
	async fn update_calendar(
		&self,
		tn_id: TnId,
		cal_id: u64,
		patch: &UpdateCalendarData,
	) -> ClResult<()>;

	/// Delete a calendar (and all its objects).
	async fn delete_calendar(&self, tn_id: TnId, cal_id: u64) -> ClResult<()>;

	/// List + search calendar objects within a calendar. Excludes soft-deleted rows.
	async fn list_calendar_objects(
		&self,
		tn_id: TnId,
		cal_id: u64,
		opts: &ListCalendarObjectOptions,
	) -> ClResult<Vec<CalendarObjectView>>;

	/// Read a single calendar object (including iCalendar blob) by UID.
	/// Returns the master row; recurrence-override rows live under the same UID but distinct
	/// `recurrence_id` and are not merged here.
	async fn get_calendar_object(
		&self,
		tn_id: TnId,
		cal_id: u64,
		uid: &str,
	) -> ClResult<Option<CalendarObject>>;

	/// Read a single recurrence-override row keyed by `(uid, recurrence_id)`.
	async fn get_calendar_object_override(
		&self,
		tn_id: TnId,
		cal_id: u64,
		uid: &str,
		recurrence_id: Timestamp,
	) -> ClResult<Option<CalendarObject>>;

	/// List all non-deleted recurrence-override rows for a given master UID.
	async fn list_calendar_object_overrides(
		&self,
		tn_id: TnId,
		cal_id: u64,
		uid: &str,
	) -> ClResult<Vec<CalendarObject>>;

	/// Soft-delete a single recurrence-override row (leaves the master untouched).
	async fn delete_calendar_object_override(
		&self,
		tn_id: TnId,
		cal_id: u64,
		uid: &str,
		recurrence_id: Timestamp,
	) -> ClResult<()>;

	/// Insert or update a calendar object (keyed by UID). Also bumps the calendar's ctag.
	/// Returns the new etag. The `extracted.recurrence_id` selects which row is written — the
	/// master row has `None`, recurrence overrides carry their own timestamp.
	async fn upsert_calendar_object(
		&self,
		tn_id: TnId,
		cal_id: u64,
		uid: &str,
		ical: &str,
		etag: &str,
		extracted: &CalendarObjectExtracted,
	) -> ClResult<Box<str>>;

	/// Soft-delete a calendar object by UID (sets `deleted_at` on all rows sharing that UID),
	/// leaving tombstones for CalDAV sync. Also bumps the calendar's ctag.
	async fn delete_calendar_object(&self, tn_id: TnId, cal_id: u64, uid: &str) -> ClResult<()>;

	/// Atomically split a recurring series at `split_at`:
	///   1. Upsert the existing master (typically with a truncated RRULE) using the
	///      caller-supplied ical / etag / extracted projection.
	///   2. Soft-delete every override row whose `recurrence_id >= split_at`.
	///   3. Insert the tail as a new master under its own UID.
	///   4. Bump the calendar's ctag once for the whole fork.
	///
	/// The whole operation runs in a single transaction; on any error the caller sees the
	/// original series unchanged. Returns the stored etags of the master and the tail,
	/// in that order.
	async fn split_calendar_object_series(
		&self,
		tn_id: TnId,
		cal_id: u64,
		master: CalendarObjectWrite<'_>,
		tail: CalendarObjectWrite<'_>,
		split_at: Timestamp,
	) -> ClResult<(Box<str>, Box<str>)>;

	/// Fetch multiple calendar objects by UID — for CalDAV `calendar-multiget` REPORT.
	async fn get_calendar_objects_by_uids(
		&self,
		tn_id: TnId,
		cal_id: u64,
		uids: &[&str],
	) -> ClResult<Vec<CalendarObject>>;

	/// Return live + tombstone entries for CalDAV `sync-collection` REPORT.
	/// `since` is the sync token's timestamp; `None` means full sync.
	async fn list_calendar_objects_since(
		&self,
		tn_id: TnId,
		cal_id: u64,
		since: Option<Timestamp>,
		limit: Option<u32>,
	) -> ClResult<Vec<CalendarObjectSyncEntry>>;

	/// Return calendar objects overlapping a time range — for CalDAV `calendar-query` REPORT.
	/// Semantics are deliberately loose (superset): any object whose master `dtstart` is ≤ `end`
	/// AND (`rrule` is set OR `dtend` is ≥ `start` OR `dtend IS NULL`) is returned. Clients
	/// expand recurrence locally. A `None` component lists both VEVENT and VTODO.
	async fn query_calendar_objects_in_range(
		&self,
		tn_id: TnId,
		cal_id: u64,
		component: Option<&str>,
		start: Option<Timestamp>,
		end: Option<Timestamp>,
	) -> ClResult<Vec<CalendarObject>>;
}

#[cfg(test)]
mod tests {
	use super::*;
	#[test]
	fn test_deserialize_list_action_options_with_multiple_statuses() {
		let query = "status=C,N&type=POST,REPLY";
		let opts: ListActionOptions =
			serde_urlencoded::from_str(query).expect("should deserialize");

		assert!(opts.status.is_some());
		let statuses = opts.status.expect("status should be Some");
		assert_eq!(statuses.len(), 2);
		assert_eq!(statuses[0].as_str(), "C");
		assert_eq!(statuses[1].as_str(), "N");

		assert!(opts.typ.is_some());
		let types = opts.typ.expect("type should be Some");
		assert_eq!(types.len(), 2);
		assert_eq!(types[0].as_str(), "POST");
		assert_eq!(types[1].as_str(), "REPLY");
	}

	#[test]
	fn test_deserialize_list_action_options_without_status() {
		let query = "issuer=alice";
		let opts: ListActionOptions =
			serde_urlencoded::from_str(query).expect("should deserialize");

		assert!(opts.status.is_none());
		assert!(opts.typ.is_none());
		assert_eq!(opts.issuer.as_deref(), Some("alice"));
	}

	#[test]
	fn test_deserialize_list_action_options_single_status() {
		let query = "status=C";
		let opts: ListActionOptions =
			serde_urlencoded::from_str(query).expect("should deserialize");

		assert!(opts.status.is_some());
		let statuses = opts.status.expect("status should be Some");
		assert_eq!(statuses.len(), 1);
		assert_eq!(statuses[0].as_str(), "C");
	}

	#[test]
	fn test_deserialize_list_action_options_audience_type() {
		let opts: ListActionOptions = serde_urlencoded::from_str("audienceType=personal")
			.expect("should deserialize personal");
		assert!(matches!(opts.audience_type, Some(AudienceType::Personal)));

		let opts: ListActionOptions = serde_urlencoded::from_str("audienceType=community")
			.expect("should deserialize community");
		assert!(matches!(opts.audience_type, Some(AudienceType::Community)));

		let opts: ListActionOptions =
			serde_urlencoded::from_str("issuer=alice").expect("should deserialize");
		assert!(opts.audience_type.is_none());

		let res: Result<ListActionOptions, _> = serde_urlencoded::from_str("audienceType=garbage");
		assert!(res.is_err(), "garbage audienceType should error");
	}

	#[test]
	fn test_deserialize_list_action_options_multi_visibility() {
		let opts: ListActionOptions =
			serde_urlencoded::from_str("visibility=F,C").expect("should deserialize");
		let v = opts.visibility.expect("visibility should be Some");
		assert_eq!(v.len(), 2);
		assert_eq!(v[0].as_str(), "F");
		assert_eq!(v[1].as_str(), "C");

		let opts: ListActionOptions =
			serde_urlencoded::from_str("visibility=P").expect("should deserialize");
		let v = opts.visibility.expect("visibility should be Some");
		assert_eq!(v.len(), 1);
		assert_eq!(v[0].as_str(), "P");

		let opts: ListActionOptions =
			serde_urlencoded::from_str("issuer=alice").expect("should deserialize");
		assert!(opts.visibility.is_none());
	}

	#[test]
	fn test_deserialize_list_action_options_visibility_with_direct() {
		let opts: ListActionOptions =
			serde_urlencoded::from_str("visibility=D,F").expect("should deserialize");
		let v = opts.visibility.expect("visibility should be Some");
		assert_eq!(v.len(), 2);
		assert_eq!(v[0].as_str(), "D");
		assert_eq!(v[1].as_str(), "F");
	}
}

// vim: ts=4