anytype 0.5.0

An ergonomic Anytype API client in rust
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
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
//! # Anytype Properties
//!
//! This module provides a fluent builder API for working with Anytype properties.
//!
//! - [`properties`](AnytypeClient::properties) - list properties in the space
//! - [`property`](AnytypeClient::property) - get property for retrieval or deletion
//! - [`new_property`](AnytypeClient::new_property) - create a new property
//! - [`update_property`](AnytypeClient::update_property) - update a property
//! - [`lookup_property_by_key`](AnytypeClient::lookup_property_by_key) - find property using key
//! - [`lookup_property_tag`](AnytypeClient::lookup_property_tag) - find tag for property, using keys or ids
//!
//! ## Quick Start
//!
//! ```rust,no_run
//! use anytype::prelude::*;
//!
//! # async fn example(client: &AnytypeClient) -> Result<(), AnytypeError> {
//! let space_id = "your_space_id";
//!
//! // List all properties
//! let properties = client.properties(space_id).list().await?;
//!
//! // Get a specific property
//! let prop = client.property(space_id, "property_id").get().await?;
//!
//! // Create a new property
//! let prop = client
//!     .new_property(space_id, "Priority", PropertyFormat::Select)
//!     .key("priority")
//!     .create().await?;
//!
//! // Update a property
//! let prop = client.update_property(space_id, "property_id")
//!     .name("Updated Name")
//!     .update().await?;
//!
//! // Delete a property
//! client.property(space_id, "property_id").delete().await?;
//! # Ok(())
//! # }
//! ```
//!
//! ## Types
//!
//! - [`Property`] - Object Property info
//! - [`PropertyWithValue`] - Property with its value (from objects)
//! - [`PropertyValue`] - Enum representing different property value types
//! - [`PropertyFormat`] - Enum of available property formats
//! - [`SetProperty`] - Trait for setting property values on objects

/*
  # Notes on Property protocols and serialization

  The REST protocol differs in how properties are sent and received.
  When receiving Objects, such as in response to get_object, search,
  list_objects, etc., we receive and deserialize Object struct containing
  an array of PropertyWithValue. However, we don't ever Serialize Object or
  PropertyWithValue. Objects are created with CreateObjectRequest builder,
  and updated with the UpdateObjectRequest builder, and properties are set and
  updated with the SetProperty trait, which creates json dynamically
  based on the property type.

  Object, PropertyWithValue, and PropertyValue are never Serialized
  into json requests to the server, but Serialize is derived for them
  so the cli can generate json output.

  Another protocol quirk is that when PropertyWithValue is received from
  an Anytype server, the select-format property value is a Tag object
  (json map containing {id, name, key, color}), and multi-select value
  is an array of Tag objects. When sending _to_ the server , select is
  a string tag id and multi-select is an array of string tag ids.
*/
use std::sync::Arc;

use chrono::{DateTime, FixedOffset};
use serde::{Deserialize, Deserializer, Serialize};
use serde_json::{Number, Value, json};
use snafu::prelude::*;
use tracing::error;

use crate::resolve::{MAX_RESOLVE_SCAN_ITEMS, RESOLVE_PAGE_SIZE, resolution_limit};
use crate::{
    Result,
    cache::AnytypeCache,
    client::AnytypeClient,
    error::OtherSnafu,
    filters::{Query, QueryWithFilters},
    http_client::{GetPaged, HttpClient},
    prelude::*,
    tags::{CreateTagRequest, ListTagsRequest},
    validation::looks_like_object_id,
    verify::{VerifyConfig, VerifyPolicy, resolve_verify, verify_available},
};

/// Available property formats.
///
/// Determines how a property value is stored and displayed.
#[derive(
    Debug,
    Default,
    Copy,
    Serialize,
    Deserialize,
    Clone,
    Eq,
    PartialEq,
    strum::Display,
    strum::EnumString,
)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum PropertyFormat {
    /// Plain text
    #[default]
    Text,
    /// Numeric value
    Number,
    /// Single selection from Tag options
    Select,
    /// Multiple selections from Tag options
    MultiSelect,
    /// Date/time value
    Date,
    /// File attachments
    Files,
    /// Boolean checkbox
    Checkbox,
    /// URL/web address
    Url,
    /// Email address
    Email,
    /// Phone number
    Phone,
    /// References to other objects
    Objects,
}

/// Property definition
///
/// This represents the schema/definition of a property, not its value.
/// For Select and `MultiSelect` properties, may optionally include Tags, if `with_tags` set when it was fetched,
/// or if it was cached)
#[derive(Debug, Deserialize, Clone, Serialize)]
pub struct Property {
    /// Data model type returned by the REST API.
    #[serde(default = "property_data_model")]
    pub object: DataModel,

    /// Display name of the property
    pub name: String,

    /// Property key in `snake_case`, e.g., "`last_modified_date`"
    pub key: String,

    /// Unique property identifier
    pub id: String,

    /// Property format (text, number, select, etc.)
    format: PropertyFormat,

    /// optional tags, if property is Select or `MultiSelect`, and tags have been fetched
    tags: Option<Vec<Tag>>,
}

fn property_data_model() -> DataModel {
    DataModel::Property
}

/// Property with its value, as returned in Object.properties.
///
/// Contains both the property definition and its current value.
/// The format is determined by the `PropertyValue` variant.
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct PropertyWithValue {
    /// Property display name
    pub name: String,

    /// Property key
    pub key: String,

    /// Property identifier
    pub id: String,

    /// The property's value (includes format as the enum tag)
    #[serde(flatten)]
    pub value: PropertyValue,
}

impl PropertyWithValue {
    /// Returns the format of this property's value.
    pub fn format(&self) -> PropertyFormat {
        self.value.format()
    }
}

impl Property {
    /// Constructs a `Property` from `PropertyWithValue`.
    pub fn new_from(other: &PropertyWithValue) -> Self {
        Self {
            object: DataModel::Property,
            format: other.format(),
            id: other.id.clone(),
            key: other.key.clone(),
            name: other.name.clone(),
            tags: None,
        }
    }

    /// Returns the format.
    pub fn format(&self) -> PropertyFormat {
        self.format
    }

    /// Returns tags if they have been fetched, or None if the tags were not retrieved.
    pub fn tags(&self) -> Option<&[Tag]> {
        self.tags.as_deref()
    }

    /// Searches for property tag using id, key, or case-insensitive name match.
    /// Error:
    ///  - `NotFound` if tags are not pre-loaded or there is no match
    pub fn lookup_tag(&self, value: impl AsRef<str>) -> Result<Tag> {
        let check = value.as_ref().to_lowercase();
        self.tags()
            .and_then(|tags| {
                tags.iter()
                    .find(|tag| {
                        tag.id == check || tag.name.to_lowercase() == check || tag.key == check
                    })
                    .cloned()
            })
            .map_or_else(
                || {
                    Err(AnytypeError::NotFound {
                        obj_type: "Tag".into(),
                        key: value.as_ref().to_string(),
                    })
                },
                Ok,
            )
    }

    /// Gets the tag with the id, or None if not found.
    pub fn tag_by_id(&self, tag_id: impl AsRef<str>) -> Option<&Tag> {
        let id = tag_id.as_ref();
        if !looks_like_object_id(id) {
            return None;
        }
        self.tags()
            .and_then(|tags| tags.iter().find(|tag| tag.id == id))
    }

    /// Gets the tag with the key, or None if not found.
    pub fn tag_by_key(&self, tag_key: impl AsRef<str>) -> Option<&Tag> {
        let key = tag_key.as_ref();
        self.tags()
            .and_then(|tags| tags.iter().find(|tag| tag.key == key))
    }

    /// Gets the tag with the name, or None if not found.
    pub fn tag_by_name(&self, tag_name: impl AsRef<str>) -> Option<&Tag> {
        let name = tag_name.as_ref();
        self.tags()
            .and_then(|tags| tags.iter().find(|tag| tag.name == name))
    }
}

/// Property value variants.
///
/// Represents the actual value of a property. The variant type
/// corresponds to the property's format. The `format` field in the JSON
/// acts as the discriminant tag.
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(tag = "format", rename_all = "snake_case")]
pub enum PropertyValue {
    /// Plain text value
    Text { text: String },
    /// Numeric value
    Number { number: Number },
    /// Single selected option
    Select { select: Tag },
    /// Multiple selected options
    MultiSelect {
        #[serde(default, deserialize_with = "deserialize_vec_tag_or_null")]
        multi_select: Vec<Tag>,
    },
    /// Date/time string
    Date { date: String },
    /// List of file references
    Files {
        #[serde(default, deserialize_with = "deserialize_vec_string_or_null")]
        files: Vec<String>,
    },
    /// Boolean value
    Checkbox { checkbox: bool },
    /// URL string
    Url { url: String },
    /// Email address
    Email { email: String },
    /// Phone number
    Phone { phone: String },
    /// List of object references
    Objects {
        #[serde(default, deserialize_with = "deserialize_vec_string_or_null")]
        objects: Vec<String>,
    },
}

fn deserialize_vec_string_or_null<'de, D>(deserializer: D) -> Result<Vec<String>, D::Error>
where
    D: Deserializer<'de>,
{
    let value = Option::<Vec<String>>::deserialize(deserializer)?;
    Ok(value.unwrap_or_default())
}

fn deserialize_vec_tag_or_null<'de, D>(deserializer: D) -> Result<Vec<Tag>, D::Error>
where
    D: Deserializer<'de>,
{
    let value = Option::<Vec<Tag>>::deserialize(deserializer)?;
    Ok(value.unwrap_or_default())
}

impl PropertyValue {
    /// Returns the value as a string.
    ///
    /// Works for Text, Date, Url, Email, Phone, and Checkbox formats.
    /// For select properties, returns the tag key
    /// Returns None for array types (Files, `MultiSelect`, Objects).
    pub fn as_str(&self) -> Option<&str> {
        match self {
            Self::Text { text } => Some(text.as_str()),
            Self::Select { select } => Some(&select.key),
            Self::Date { date } => Some(date.as_str()),
            Self::Url { url } => Some(url.as_str()),
            Self::Email { email } => Some(email.as_str()),
            Self::Phone { phone } => Some(phone.as_str()),
            Self::Checkbox { checkbox } => Some(if *checkbox { "true" } else { "false" }),
            _ => None,
        }
    }

    /// Returns the value as a boolean.
    ///
    /// Property must be Checkbox format
    pub fn as_bool(&self) -> Option<bool> {
        match self {
            Self::Checkbox { checkbox } => Some(*checkbox),
            _ => None,
        }
    }

    /// Returns the value as a Number.
    ///
    /// Property must be Number format
    pub fn as_number(&self) -> Option<&Number> {
        match self {
            Self::Number { number } => Some(number),
            _ => None,
        }
    }

    /// Returns the date value as `DateTime` object.
    ///
    /// Returns None if the property is not defined to have format Date, or could not be parsed as a date.
    pub fn as_date(&self) -> Option<DateTime<FixedOffset>> {
        match self {
            Self::Date { date } => match DateTime::parse_from_rfc3339(date) {
                Err(err) => {
                    error!(?err, "Date property has invalid format \"{date}\"");
                    None
                }
                Ok(date) => Some(date),
            },
            _ => None,
        }
    }

    /// Returns the value as an array of strings.
    /// For multi-select (array of tags), returns the tags' keys.
    ///
    /// Property must be Files, `MultiSelect`, or Objects
    pub fn as_array(&self) -> Option<Vec<String>> {
        match self {
            Self::Files { files } => Some(files.clone()),
            Self::MultiSelect { multi_select } => {
                Some(multi_select.iter().map(|tag| tag.key.clone()).collect())
            }
            Self::Objects { objects } => Some(objects.clone()),
            _ => None,
        }
    }

    /// Returns select value as a tag
    pub fn as_tag(&self) -> Option<&Tag> {
        match self {
            Self::Select { select } => Some(select),
            _ => None,
        }
    }

    /// Returns multi-select value as an array of tags
    pub fn as_tags(&self) -> Option<&[Tag]> {
        match self {
            Self::MultiSelect { multi_select } => Some(multi_select),
            _ => None,
        }
    }

    /// Returns the format corresponding to this value variant.
    pub fn format(&self) -> PropertyFormat {
        match self {
            Self::Text { .. } => PropertyFormat::Text,
            Self::Number { .. } => PropertyFormat::Number,
            Self::Select { .. } => PropertyFormat::Select,
            Self::MultiSelect { .. } => PropertyFormat::MultiSelect,
            Self::Date { .. } => PropertyFormat::Date,
            Self::Files { .. } => PropertyFormat::Files,
            Self::Checkbox { .. } => PropertyFormat::Checkbox,
            Self::Url { .. } => PropertyFormat::Url,
            Self::Email { .. } => PropertyFormat::Email,
            Self::Phone { .. } => PropertyFormat::Phone,
            Self::Objects { .. } => PropertyFormat::Objects,
        }
    }
}

fn try_parse_num(key: &str, value: &str) -> Result<serde_json::Number> {
    // first try int
    value.parse::<u64>().map_or_else(
        |_| {
            value.parse::<i64>().map_or_else(
                |_| {
                    value.parse::<f64>().map_or_else(
                        |_| {
                            Err(AnytypeError::Validation {
                                message: format!("Invalid number for property {key}: {value}"),
                            })
                        },
                        |num| Ok(serde_json::Number::from_f64(num).unwrap()),
                    )
                },
                |num| Ok(Number::from(num)),
            )
        },
        |num| Ok(Number::from(num)),
    )
}

fn try_tag(prop: &Property, key: &str, value: &str) -> Result<String> {
    let value = if looks_like_object_id(value) {
        value
    } else if let Some(tag) = prop.tag_by_name(value) {
        &tag.id
    } else if let Some(tag) = prop.tag_by_key(value) {
        &tag.id
    } else {
        return NotFoundSnafu {
            obj_type: "Tag".to_string(),
            key: format!("property {key} tag: {value}"),
        }
        .fail();
    };
    Ok(value.to_string())
}

impl AnytypeClient {
    // Convenience method to set properties on an object (NewObjectRequest or UpdateObjectRequest)
    // using string values. Returns error if the value cannot be converted to the applicable type.
    // When setting select and multi-select values, the value can be an id, name, or key.
    pub async fn set_properties<
        K: AsRef<str> + Sync,
        V: AsRef<str> + Sync,
        SP: SetProperty + Send,
    >(
        &self,
        space_id: &str,
        obj: SP,
        typ: &Type,
        props: &[(K, V)],
    ) -> Result<SP> {
        let mut obj = obj;
        for (key, value) in props {
            let key = key.as_ref();
            let value = value.as_ref();

            if let Some(prop) = typ.get_property_by_key(key) {
                match prop.format() {
                    PropertyFormat::Text => {
                        obj = obj.set_text(key, value);
                    }
                    PropertyFormat::Number => {
                        obj = obj.set_number(key, try_parse_num(key, value)?);
                    }
                    PropertyFormat::Select => {
                        // get property from cache with its tags
                        let prop = self.property(space_id, &prop.id).get().await?;
                        obj = obj.set_select(key, &try_tag(&prop, key, value)?);
                    }
                    PropertyFormat::MultiSelect => {
                        // get property from cache with its tags
                        let prop = self.property(space_id, &prop.id).get().await?;
                        let mut values = Vec::new();
                        for id_or_tag in value.split(',') {
                            values.push(try_tag(&prop, key, id_or_tag)?);
                        }
                        obj = obj.set_multi_select(key, values);
                    }
                    PropertyFormat::Date => {
                        obj = obj.set_date(key, value);
                    }
                    PropertyFormat::Files => {
                        let files = value.split(',').collect::<Vec<&str>>();
                        obj = obj.set_files(key, files);
                    }
                    PropertyFormat::Checkbox => {
                        if let Ok(val) = value.parse::<bool>() {
                            obj = obj.set_checkbox(key, val);
                        } else {
                            return ValidationSnafu {
                                message: format!("Invalid bool value for property {key}: {value}"),
                            }
                            .fail();
                        }
                    }
                    PropertyFormat::Url => {
                        obj = obj.set_url(key, value);
                    }
                    PropertyFormat::Email => {
                        obj = obj.set_email(key, value);
                    }
                    PropertyFormat::Phone => {
                        obj = obj.set_phone(key, value);
                    }
                    PropertyFormat::Objects => {
                        let ids = value.split(',').collect::<Vec<&str>>();
                        obj = obj.set_objects(key, ids);
                    }
                }
            } else {
                return ValidationSnafu {
                    message: format!("invalid property {key} for type {}", typ.key),
                }
                .fail();
            }
        }
        Ok(obj)
    }
}

// ============================================================================
// SetProperty TRAIT
// ============================================================================

/// Trait for setting property values on objects. Used by `CreateObjectRequest` and `UpdateObjectRequest`.
///
/// To set a property on an object, the property must already be defined in the object's type.
///
pub trait SetProperty: Sized {
    /// Adds a raw property value.
    ///
    /// Base method that all typed setters must implement.
    #[must_use]
    fn add_property(self, property: Value) -> Self;

    /// Sets a text property value.
    ///
    /// # Arguments
    /// * `key` - Property key
    /// * `value` - Text value
    #[must_use]
    fn set_text(self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.add_property(json!({
            "key": key.into(),
            "text": value.into(),
        }))
    }

    /// Sets a number property value.
    ///
    /// # Arguments
    /// * `key` - Property key
    /// * `value` - Numeric value
    #[must_use]
    fn set_number(self, key: impl Into<String>, value: impl Into<Number>) -> Self {
        self.add_property(json!({
            "key": key.into(),
            "number": value.into(),
        }))
    }

    /// Sets a date property value.
    ///
    /// # Arguments
    /// * `key` - Property key
    /// * `value` - Date string (ISO 3339 format recommended)
    #[must_use]
    fn set_date(self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.add_property(json!({
            "key": key.into(),
            "date": value.into(),
        }))
    }

    /// Sets a URL property value.
    ///
    /// # Arguments
    /// * `key` - Property key
    /// * `value` - URL string
    #[must_use]
    fn set_url(self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.add_property(json!({
            "key": key.into(),
            "url": value.into(),
        }))
    }

    /// Sets an email property value.
    ///
    /// # Arguments
    /// * `key` - Property key
    /// * `value` - Email address
    #[must_use]
    fn set_email(self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.add_property(json!({
            "key": key.into(),
            "email": value.into(),
        }))
    }

    /// Sets a phone property value.
    ///
    /// # Arguments
    /// * `key` - Property key
    /// * `value` - Phone number
    #[must_use]
    fn set_phone(self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.add_property(json!({
            "key": key.into(),
            "phone": value.into(),
        }))
    }

    /// Sets a checkbox (boolean) property value.
    ///
    /// # Arguments
    /// * `key` - Property key
    /// * `value` - Boolean value
    #[must_use]
    fn set_checkbox(self, key: impl Into<String>, value: bool) -> Self {
        self.add_property(json!({
            "key": key.into(),
            "checkbox": value,
        }))
    }

    /// Sets a select property to the tag id.
    ///
    /// # Arguments
    /// * `key` - Property key
    /// * `tag_id` - id of tag
    #[must_use]
    fn set_select(self, key: impl Into<String>, tag_id: impl Into<String>) -> Self {
        let key = key.into();
        let tag_id = tag_id.into();
        if !looks_like_object_id(&tag_id) {
            error!("set_select({key},...): invalid tag id: {tag_id}");
        }
        self.add_property(json!({
            "key": key,
            "select": tag_id,
        }))
    }

    /// Sets an objects (relation) property value.
    ///
    /// # Arguments
    /// * `key` - Property key
    /// * `objects` - Iterator of object IDs
    #[must_use]
    fn set_objects(
        self,
        key: impl Into<String>,
        objects: impl IntoIterator<Item = impl Into<String>>,
    ) -> Self {
        self.add_property(json!({
            "key": key.into(),
            "objects": objects.into_iter().map(Into::into).collect::<Vec<String>>(),
        }))
    }

    /// Sets a files property value.
    ///
    /// # Arguments
    /// * `key` - Property key
    /// * `files` - Iterator of file references
    #[must_use]
    fn set_files(
        self,
        key: impl Into<String>,
        files: impl IntoIterator<Item = impl Into<String>>,
    ) -> Self {
        self.add_property(json!({
            "key": key.into(),
            "files": files.into_iter().map(Into::into).collect::<Vec<String>>(),
        }))
    }

    /// Sets a multi-select property value. (multiple tag ids)
    ///
    /// # Arguments
    /// * `key` - Property key
    /// * `values` - Iterator of tag ids
    #[must_use]
    fn set_multi_select(
        self,
        key: impl Into<String>,
        values: impl IntoIterator<Item = impl Into<String>>,
    ) -> Self {
        let key = key.into();
        let values = values.into_iter().map(Into::into).collect::<Vec<String>>();
        for value in &values {
            if !looks_like_object_id(value) {
                error!("set_multi_select({key}, ...) invalid tag id: {value}");
            }
        }
        self.add_property(json!({
            "key": key,
            "multi_select": values
        }))
    }
}

/// Response wrapper for single property operations
#[derive(Debug, Deserialize)]
struct PropertyResponse {
    property: Property,
}

/// Internal request body for creating a property
#[derive(Debug, Serialize)]
struct CreatePropertyRequestBody {
    // name (required)
    name: String,

    // format (required)
    format: PropertyFormat,

    #[serde(skip_serializing_if = "Option::is_none")]
    key: Option<String>,

    #[serde(skip_serializing_if = "Vec::is_empty")]
    tags: Vec<CreateTagRequest>,
}

/// Internal request body for updating a property
#[derive(Debug, Serialize)]
struct UpdatePropertyRequestBody {
    name: String,

    #[serde(skip_serializing_if = "Option::is_none")]
    key: Option<String>,
}

/// Request builder for getting or deleting a single property.
///
/// Obtained via [`AnytypeClient::property`].
///
/// # Example
///
/// ```rust,no_run
/// # use anytype::prelude::*;
/// # async fn example(client: &AnytypeClient) -> Result<(), AnytypeError> {
/// // Get a property
/// let prop = client.property("space_id", "property_id").get().await?;
///
/// // Delete a property
/// let deleted = client.property("space_id", "property_id").delete().await?;
/// # Ok(())
/// # }
/// ```
#[derive(Debug)]
pub struct PropertyRequest {
    client: Arc<HttpClient>,
    limits: ValidationLimits,
    space_id: String,
    property_id: String,
    with_tags: bool,
    cache: Arc<AnytypeCache>,
}

pub(crate) async fn set_property_tags(
    client: &Arc<HttpClient>,
    limits: &ValidationLimits,
    space_id: &str,
    property: &mut Property,
) -> Result<(), AnytypeError> {
    if property.format == PropertyFormat::Select || property.format == PropertyFormat::MultiSelect {
        let tags = ListTagsRequest::new(client.clone(), limits.clone(), space_id, &property.id)
            .list()
            .await?
            .collect_all()
            .await?;
        property.tags = Some(tags);
    }
    Ok(())
}

/// Load all space properties into cache.
/// Always fetches tags for Select and `MultiSelect` properties
async fn prime_cache_properties(
    client: &Arc<HttpClient>,
    cache: &Arc<AnytypeCache>,
    limits: &ValidationLimits,
    space_id: &str,
) -> Result<()> {
    let mut properties: Vec<Property> = client
        .get_request_paged(
            &format!("/v1/spaces/{space_id}/properties"),
            QueryWithFilters::default(),
        )
        .await?
        .collect_all()
        .await?;

    for prop in &mut properties {
        // if property is select or multi-select, update tags
        set_property_tags(client, limits, space_id, prop).await?;
    }
    cache.set_properties(space_id, properties);
    Ok(())
}

impl PropertyRequest {
    /// Creates a new `PropertyRequest`.
    pub(crate) fn new(
        client: Arc<HttpClient>,
        limits: ValidationLimits,
        space_id: impl Into<String>,
        property_id: impl Into<String>,
        with_tags: bool,
        cache: Arc<AnytypeCache>,
    ) -> Self {
        Self {
            client,
            limits,
            space_id: space_id.into(),
            property_id: property_id.into(),
            with_tags,
            cache,
        }
    }

    /// Also fetches tags when this request is executed with [`get`](Self::get).
    ///
    /// [`get_direct`](Self::get_direct) is intentionally metadata-only and
    /// never expands tags, even when this option was selected.
    #[must_use]
    pub fn with_tags(mut self) -> Self {
        self.with_tags = true;
        self
    }

    /// Retrieves the property by ID.
    ///
    /// # Returns
    /// The property definition.
    /// If property has format select or multi-select, call `with_tags()` to also fetch the tag options for the property.
    ///
    /// # Errors
    /// - [`AnytypeError::NotFound`] if the property doesn't exist
    /// - [`AnytypeError::Validation`] if IDs are invalid
    pub async fn get(self) -> Result<Property> {
        self.limits.validate_id(&self.space_id, "space_id")?;
        self.limits.validate_id(&self.property_id, "property_id")?;

        if self.cache.is_enabled() {
            if let Some(property) = self.cache.get_property(&self.space_id, &self.property_id) {
                return Ok((*property).clone());
            }
            // see note on locking design in cache.rs
            if !self.cache.has_properties(&self.space_id) {
                prime_cache_properties(&self.client, &self.cache, &self.limits, &self.space_id)
                    .await?;
                if let Some(property) = self.cache.get_property(&self.space_id, &self.property_id) {
                    let mut property = (*property).clone();
                    if !self.with_tags {
                        property.tags = None;
                    }
                    return Ok(property);
                }
            }
            return NotFoundSnafu {
                obj_type: "Property".to_string(),
                key: self.property_id,
            }
            .fail();
        }

        // cache disabled, fetch directly
        let mut property = self.fetch_direct_metadata().await?;
        if self.with_tags {
            set_property_tags(&self.client, &self.limits, &self.space_id, &mut property).await?;
        }
        Ok(property)
    }

    /// Retrieves the property with one cache-independent scoped HTTP GET.
    ///
    /// Unlike [`get`](Self::get), this method neither reads nor primes the
    /// in-memory property cache. It validates the space and property IDs
    /// before dispatch and rejects a successful response whose property ID
    /// differs from the requested ID. This method is always metadata-only:
    /// [`with_tags`](Self::with_tags) affects [`get`](Self::get), but is
    /// intentionally ignored here so a direct read is exactly one request and
    /// can never expand into an unbounded tag scan. Any tags included
    /// unexpectedly in the direct response are discarded.
    ///
    /// # Returns
    /// The property returned for the exact scoped property endpoint.
    ///
    /// # Errors
    /// - [`AnytypeError::NotFound`] if the property doesn't exist
    /// - [`AnytypeError::Validation`] if either ID is invalid
    /// - [`AnytypeError::Other`] if the upstream response identity does not
    ///   match the scoped request
    pub async fn get_direct(self) -> Result<Property> {
        self.limits.validate_id(&self.space_id, "space_id")?;
        self.limits.validate_id(&self.property_id, "property_id")?;
        let mut property = self.fetch_direct_metadata().await?;
        property.tags = None;
        Ok(property)
    }

    async fn fetch_direct_metadata(&self) -> Result<Property> {
        let response: PropertyResponse = self
            .client
            .get_request(
                &format!(
                    "/v1/spaces/{}/properties/{}",
                    self.space_id, self.property_id
                ),
                QueryWithFilters::default(),
            )
            .await?;

        let property = response.property;
        if property.id != self.property_id {
            return OtherSnafu {
                message: "Anytype returned a mismatched property identity".to_string(),
            }
            .fail();
        }

        Ok(property)
    }

    /// Deletes (archives) the property.
    ///
    /// # Returns
    /// The deleted property.
    ///
    /// # Errors
    /// - [`AnytypeError::NotFound`] if the property doesn't exist
    /// - [`AnytypeError::Forbidden`] if you don't have permission
    pub async fn delete(self) -> Result<Property> {
        self.limits.validate_id(&self.space_id, "space_id")?;
        self.limits.validate_id(&self.property_id, "property_id")?;

        let response: PropertyResponse = self
            .client
            .delete_request(&format!(
                "/v1/spaces/{}/properties/{}",
                self.space_id, self.property_id
            ))
            .await?;
        self.cache
            .delete_property(&self.space_id, &self.property_id);
        Ok(response.property)
    }
}

/// Request builder for creating a new property.
///
/// Obtained via [`AnytypeClient::new_property`].
///
/// # Example
///
/// ```rust,no_run
/// # use anytype::prelude::*;
/// # async fn example(client: &AnytypeClient) -> Result<(), AnytypeError> {
/// let prop = client
///     .new_property("space_id", "Priority", PropertyFormat::Select)
///     .key("priority")
///     .create().await?;
/// # Ok(())
/// # }
/// ```
#[derive(Debug)]
pub struct NewPropertyRequest {
    client: Arc<HttpClient>,
    limits: ValidationLimits,
    space_id: String,
    name: String,
    format: PropertyFormat,
    key: Option<String>,
    tags: Vec<CreateTagRequest>,
    cache: Arc<AnytypeCache>,
    verify_policy: VerifyPolicy,
    verify_config: Option<VerifyConfig>,
    refresh_cache: bool,
}

impl NewPropertyRequest {
    /// Creates a new `NewPropertyRequest`.
    pub(crate) fn new(
        client: Arc<HttpClient>,
        limits: ValidationLimits,
        space_id: impl Into<String>,
        name: impl Into<String>,
        format: PropertyFormat,
        cache: Arc<AnytypeCache>,
        verify_config: Option<VerifyConfig>,
    ) -> Self {
        Self {
            client,
            limits,
            space_id: space_id.into(),
            name: name.into(),
            format,
            key: None,
            tags: Vec::new(),
            cache,
            verify_policy: VerifyPolicy::Default,
            verify_config,
            refresh_cache: true,
        }
    }

    /// Sets the property key.
    ///
    /// Should be in `snake_case` format.
    ///
    /// # Arguments
    /// * `key` - Unique key for the property
    #[must_use]
    pub fn key(mut self, key: impl Into<String>) -> Self {
        self.key = Some(key.into());
        self
    }

    /// Adds a tag for select/multi-select properties.
    ///
    /// # Arguments
    /// * `name` - tag name
    /// * `key` - optional key
    /// * `color` - tag color
    #[must_use]
    pub fn tag(mut self, name: &str, key: Option<String>, color: Color) -> Self {
        self.tags.push(CreateTagRequest {
            name: name.into(),
            key,
            color,
        });
        self
    }

    /// Adds multiple tags for select/multi-select properties.
    ///
    /// # Arguments
    /// * `tags` - Iterator of tags to add
    #[must_use]
    pub fn tags(mut self, tags: impl IntoIterator<Item = CreateTagRequest>) -> Self {
        self.tags.extend(tags);
        self
    }

    /// Enables read-after-write verification for this request.
    #[must_use]
    pub fn ensure_available(mut self) -> Self {
        self.verify_policy = VerifyPolicy::Enabled;
        self
    }

    /// Enables verification using a custom config for this request.
    #[must_use]
    pub fn ensure_available_with(mut self, config: VerifyConfig) -> Self {
        self.verify_policy = VerifyPolicy::Enabled;
        self.verify_config = Some(config);
        self
    }

    /// Disables verification for this request.
    #[must_use]
    pub fn no_verify(mut self) -> Self {
        self.verify_policy = VerifyPolicy::Disabled;
        self
    }

    /// Avoids post-write tag pagination and invalidates the space's property cache.
    ///
    /// This cache-independent path keeps the mutation's request count bounded
    /// even when the property cache was already primed. Callers that need tags
    /// can issue an explicitly bounded [`AnytypeClient::tags`] request after
    /// the mutation.
    #[must_use]
    pub fn no_cache_refresh(mut self) -> Self {
        self.refresh_cache = false;
        self
    }

    /// Creates the property with the configured settings.
    ///
    /// # Returns
    /// The newly created property.
    ///
    /// # Errors
    /// - [`AnytypeError::Validation`] if name is not provided or invalid
    pub async fn create(self) -> Result<Property> {
        self.limits.validate_id(&self.space_id, "space_id")?;
        self.limits.validate_name(&self.name, "property")?;
        let create_with_tags = !self.tags.is_empty();
        if let Some(ref key) = self.key {
            self.limits.validate_name(key, "property key")?;
        }
        ensure!(
            self.tags.is_empty()
                || self.format == PropertyFormat::Select
                || self.format == PropertyFormat::MultiSelect,
            ValidationSnafu {
                message: format!(
                    "Property {} format {} cannot be created with tags, because tags are only supported for formats Select and MultiSelect",
                    self.name, self.format
                ),
            }
        );

        let request_body = CreatePropertyRequestBody {
            name: self.name,
            key: self.key,
            format: self.format,
            tags: self.tags,
        };

        let response: PropertyResponse = self
            .client
            .post_request(
                &format!("/v1/spaces/{}/properties", self.space_id),
                &request_body,
                QueryWithFilters::default(),
            )
            .await?;

        // replace cached property, including tags
        if self.refresh_cache && self.cache.has_properties(&self.space_id) {
            let mut property = response.property.clone();
            if create_with_tags {
                set_property_tags(&self.client, &self.limits, &self.space_id, &mut property)
                    .await?;
            }
            self.cache.set_property(&self.space_id, property);
        } else if !self.refresh_cache {
            self.cache.clear_properties(Some(&self.space_id));
        }

        let property = response.property;
        if let Some(config) = resolve_verify(self.verify_policy, self.verify_config.as_ref()) {
            return verify_available(&config, "Property", &property.id, || async {
                let response: PropertyResponse = self
                    .client
                    .get_request(
                        &format!("/v1/spaces/{}/properties/{}", self.space_id, property.id),
                        QueryWithFilters::default(),
                    )
                    .await?;
                Ok(response.property)
            })
            .await;
        }
        Ok(property)
    }
}

/// Request builder for updating an existing property.
///
/// Obtained via [`AnytypeClient::update_property`].
///
/// # Example
///
/// ```rust,no_run
/// # use anytype::prelude::*;
/// # async fn example(client: &AnytypeClient) -> Result<(), AnytypeError> {
/// let prop = client.update_property("space_id", "property_id")
///     .name("Updated Priority")
///     .key("updated_priority")
///     .update().await?;
/// # Ok(())
/// # }
/// ```
#[derive(Debug)]
pub struct UpdatePropertyRequest {
    client: Arc<HttpClient>,
    limits: ValidationLimits,
    space_id: String,
    property_id: String,
    name: Option<String>,
    key: Option<String>,
    cache: Arc<AnytypeCache>,
    verify_policy: VerifyPolicy,
    verify_config: Option<VerifyConfig>,
    refresh_cache: bool,
}

impl UpdatePropertyRequest {
    /// Creates a new `UpdatePropertyRequest`.
    pub(crate) fn new(
        client: Arc<HttpClient>,
        limits: ValidationLimits,
        space_id: impl Into<String>,
        property_id: impl Into<String>,
        cache: Arc<AnytypeCache>,
        verify_config: Option<VerifyConfig>,
    ) -> Self {
        Self {
            client,
            limits,
            space_id: space_id.into(),
            property_id: property_id.into(),
            name: None,
            key: None,
            cache,
            verify_policy: VerifyPolicy::Default,
            verify_config,
            refresh_cache: true,
        }
    }

    /// Sets the property name required by the REST update endpoint.
    ///
    /// This must be supplied even when only changing the property key. Use the
    /// property's current name to leave it unchanged.
    ///
    /// # Arguments
    /// * `name` - New display name for the property
    #[must_use]
    pub fn name(mut self, name: impl Into<String>) -> Self {
        self.name = Some(name.into());
        self
    }

    /// Updates the property key.
    ///
    /// # Arguments
    /// * `key` - New key for the property (`snake_case`)
    #[must_use]
    pub fn key(mut self, key: impl Into<String>) -> Self {
        self.key = Some(key.into());
        self
    }

    /// Enables read-after-write verification for this request.
    #[must_use]
    pub fn ensure_available(mut self) -> Self {
        self.verify_policy = VerifyPolicy::Enabled;
        self
    }

    /// Enables verification using a custom config for this request.
    #[must_use]
    pub fn ensure_available_with(mut self, config: VerifyConfig) -> Self {
        self.verify_policy = VerifyPolicy::Enabled;
        self.verify_config = Some(config);
        self
    }

    /// Disables verification for this request.
    #[must_use]
    pub fn no_verify(mut self) -> Self {
        self.verify_policy = VerifyPolicy::Disabled;
        self
    }

    /// Avoids post-write tag pagination and invalidates the space's property cache.
    ///
    /// This cache-independent path bounds the mutation independently of cache
    /// state. A later cached property read will repopulate explicitly.
    #[must_use]
    pub fn no_cache_refresh(mut self) -> Self {
        self.refresh_cache = false;
        self
    }

    /// Applies the update to the property.
    ///
    /// Note: Property format cannot be changed after creation.
    ///
    /// # Returns
    /// The updated property.
    ///
    /// # Errors
    /// - [`AnytypeError::Validation`] if called without setting a name
    /// - [`AnytypeError::NotFound`] if the property doesn't exist
    pub async fn update(self) -> Result<Property> {
        self.limits.validate_id(&self.space_id, "space_id")?;
        self.limits.validate_id(&self.property_id, "property_id")?;

        // anytype-heart's REST binding requires name even when only the key changes.
        ensure!(
            self.name.is_some(),
            ValidationSnafu {
                message:
                    "update_property: name is required by the REST API (including for key changes)"
                        .to_string(),
            }
        );

        let name = self.name.expect("property name checked above");
        self.limits.validate_name(&name, "property name")?;
        if let Some(ref key) = self.key {
            self.limits.validate_name(key, "property key")?;
        }

        let request_body = UpdatePropertyRequestBody {
            name,
            key: self.key,
        };

        let response: PropertyResponse = self
            .client
            .patch_request(
                &format!(
                    "/v1/spaces/{}/properties/{}",
                    self.space_id, self.property_id
                ),
                &request_body,
            )
            .await?;

        // update property in cache
        if self.refresh_cache && self.cache.has_properties(&self.space_id) {
            let mut property = response.property.clone();
            set_property_tags(&self.client, &self.limits, &self.space_id, &mut property).await?;
            self.cache.set_property(&self.space_id, property);
        } else if !self.refresh_cache {
            self.cache.clear_properties(Some(&self.space_id));
        }

        let property = response.property;
        if let Some(config) = resolve_verify(self.verify_policy, self.verify_config.as_ref()) {
            return verify_available(&config, "Property", &property.id, || async {
                let response: PropertyResponse = self
                    .client
                    .get_request(
                        &format!("/v1/spaces/{}/properties/{}", self.space_id, property.id),
                        QueryWithFilters::default(),
                    )
                    .await?;
                Ok(response.property)
            })
            .await;
        }
        Ok(property)
    }
}

/// Request builder for listing properties in a space.
///
/// Obtained via [`AnytypeClient::properties`].
///
/// # Example
///
/// ```rust
/// # use anytype::prelude::*;
/// # async fn example() -> Result<(), AnytypeError> {
/// #   let client = AnytypeClient::new("doc test")?;
/// #   let space_id = anytype::test_util::example_space_id(&client).await?;
/// let properties = client.properties(&space_id)
///     .limit(50)
///     .list().await?;
///
/// for prop in properties.iter() {
///     println!("{}: {} ({})", prop.key, prop.name, prop.format());
/// }
/// # Ok(())
/// # }
/// ```
#[derive(Debug)]
pub struct ListPropertiesRequest {
    client: Arc<HttpClient>,
    limits: ValidationLimits,
    space_id: String,
    limit: Option<u32>,
    offset: Option<u32>,
    filters: Vec<Filter>,
    cache: Arc<AnytypeCache>,
}

impl ListPropertiesRequest {
    /// Creates a new `ListPropertiesRequest`.
    #[must_use]
    pub(crate) fn new(
        client: Arc<HttpClient>,
        limits: ValidationLimits,
        space_id: impl Into<String>,
        cache: Arc<AnytypeCache>,
    ) -> Self {
        Self {
            client,
            limits,
            space_id: space_id.into(),
            limit: None,
            offset: None,
            filters: Vec::new(),
            cache,
        }
    }

    /// Sets the pagination limit (max items per page).
    ///
    /// Default is 100, maximum is 1000.
    ///
    /// # Arguments
    /// * `limit` - Number of items to return per page
    #[must_use]
    pub fn limit(mut self, limit: u32) -> Self {
        self.limit = Some(limit);
        self
    }

    /// Sets the pagination offset (starting position).
    ///
    /// # Arguments
    /// * `offset` - Number of items to skip
    #[must_use]
    pub fn offset(mut self, offset: u32) -> Self {
        self.offset = Some(offset);
        self
    }

    /// Adds a filter condition.
    ///
    /// Multiple filters are combined with AND logic.
    ///
    /// # Arguments
    /// * `filter` - Filter condition to add
    #[must_use]
    pub fn filter(mut self, filter: Filter) -> Self {
        self.filters.push(filter);
        self
    }

    /// Adds multiple filter conditions.
    ///
    /// # Arguments
    /// * `filters` - Iterator of filters to add
    #[must_use]
    pub fn filters(mut self, filters: impl IntoIterator<Item = Filter>) -> Self {
        self.filters.extend(filters);
        self
    }

    /// Executes the list request.
    ///
    /// # Returns
    /// A paginated result containing the matching properties.
    ///
    /// To take advantage of cached properties for the `list()` method,
    /// the cache must be enabled, and the query
    /// parameter must not contain filters or pagination limits or offsets.
    ///
    /// # Errors
    /// - [`AnytypeError::Validation`] if `space_id` is invalid
    pub async fn list(self) -> Result<PagedResult<Property>> {
        self.limits.validate_id(&self.space_id, "space_id")?;

        if self.cache.is_enabled()
            && self.limit.is_none()
            && (self.offset.unwrap_or_default() == 0)
            && self.filters.is_empty()
        {
            // see note on locking design in cache.rs
            if !self.cache.has_properties(&self.space_id) {
                prime_cache_properties(&self.client, &self.cache, &self.limits, &self.space_id)
                    .await?;
            }
            return Ok(PagedResult::from_items(
                self.cache
                    .properties_for_space(&self.space_id)
                    .unwrap_or_default(),
            ));
        }
        let query = Query::default()
            .set_limit_opt(self.limit)
            .set_offset_opt(self.offset)
            .add_filters(&self.filters);

        self.client
            .get_request_paged(&format!("/v1/spaces/{}/properties", self.space_id), query)
            .await
    }
}

// ============================================================================
// ANYTYPECLIENT METHODS
// ============================================================================

impl AnytypeClient {
    /// Creates a request builder for getting or deleting a single property by its id.
    /// To look up a property by its key,
    /// use [`lookup_property_by_key`](AnytypeClient::lookup_property_by_key)
    ///
    /// # Arguments
    /// * `space_id` - ID of the space containing the property
    /// * `property_id` - ID of the property
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use anytype::prelude::*;
    /// # async fn example(client: &AnytypeClient) -> Result<(), AnytypeError> {
    /// let prop = client.property("space_id", "property_id").get().await?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn property(
        &self,
        space_id: impl Into<String>,
        property_id: impl Into<String>,
    ) -> PropertyRequest {
        PropertyRequest::new(
            self.client.clone(),
            self.config.limits.clone(),
            space_id,
            property_id,
            false,
            self.cache.clone(),
        )
    }

    /// Creates a request builder for creating a new property.
    ///
    /// # Arguments
    /// * `space_id` - ID of the space to create the property in
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use anytype::prelude::*;
    /// # async fn example(client: &AnytypeClient) -> Result<(), AnytypeError> {
    /// let prop = client.new_property("space_id", "Priority", PropertyFormat::Number)
    ///     .create().await?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn new_property(
        &self,
        space_id: impl Into<String>,
        name: impl Into<String>,
        format: PropertyFormat,
    ) -> NewPropertyRequest {
        NewPropertyRequest::new(
            self.client.clone(),
            self.config.limits.clone(),
            space_id,
            name,
            format,
            self.cache.clone(),
            self.config.verify.clone(),
        )
    }

    /// Creates a request builder for updating an existing property.
    ///
    /// The builder must be given [`UpdatePropertyRequest::name`] before
    /// [`UpdatePropertyRequest::update`] is called, including for key-only
    /// changes, because the REST endpoint requires the property's name.
    ///
    /// # Arguments
    /// * `space_id` - ID of the space containing the property
    /// * `property_id` - ID of the property to update
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use anytype::prelude::*;
    /// # async fn example(client: &AnytypeClient) -> Result<(), AnytypeError> {
    /// let prop = client.update_property("space_id", "property_id")
    ///     .name("New Name")
    ///     .update().await?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn update_property(
        &self,
        space_id: impl Into<String>,
        property_id: impl Into<String>,
    ) -> UpdatePropertyRequest {
        UpdatePropertyRequest::new(
            self.client.clone(),
            self.config.limits.clone(),
            space_id,
            property_id,
            self.cache.clone(),
            self.config.verify.clone(),
        )
    }

    /// Creates a request builder for listing properties in a space.
    ///
    /// # Arguments
    /// * `space_id` - ID of the space to list properties from
    ///
    /// # Example
    ///
    /// ```rust
    /// # use anytype::prelude::*;
    /// # async fn example() -> Result<(), AnytypeError> {
    /// #   let client = AnytypeClient::new("doc test")?;
    /// #   let space_id = anytype::test_util::example_space_id(&client).await?;
    /// let properties = client.properties(&space_id)
    ///     .limit(50)
    ///     .list().await?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn properties(&self, space_id: impl Into<String>) -> ListPropertiesRequest {
        ListPropertiesRequest::new(
            self.client.clone(),
            self.config.limits.clone(),
            space_id,
            self.cache.clone(),
        )
    }

    /// Searches for properties in space by id, key, or name, using case-insensitive match.
    /// If the property is type select or multi-select, the property includes the tags.
    ///
    /// This method requires cache to be enabled (the default).
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use anytype::prelude::*;
    /// # async fn example(client: &AnytypeClient) -> Result<(), AnytypeError> {
    /// let props = client.lookup_properties("space_id", "status").await?;
    /// for prop in props {
    ///     println!("Property {} format {}", &prop.name, &prop.format());
    ///     // display tags, for Select and MultiSelect properties
    ///     if let Some(tags) = prop.tags() {
    ///         println!("Values:");
    ///         for tag in tags {
    ///             println!("    {} {}", &tag.key, &tag.name);
    ///         }
    ///     }
    /// }
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// Errors:
    /// - `AnytypeError::NotFound` if no property in the space matched
    /// - `AnytypeError::CacheDisabled` if cache is disabled
    /// - `AnytypeError::*` any other error
    ///
    pub async fn lookup_properties(
        &self,
        space_id: &str,
        text: impl AsRef<str>,
    ) -> Result<Vec<Property>> {
        ensure!(self.cache.is_enabled(), CacheDisabledSnafu);
        // see note on locking design in cache.rs
        if !self.cache.has_properties(space_id) {
            prime_cache_properties(&self.client, &self.cache, &self.config.limits, space_id)
                .await?;
        }
        match self.cache.lookup_property(space_id, text.as_ref()) {
            Some(properties) if !properties.is_empty() => {
                Ok(properties.into_iter().map(|arc| (*arc).clone()).collect())
            }
            _ => Err(AnytypeError::NotFound {
                obj_type: "Property".into(),
                key: text.as_ref().to_string(),
            }),
        }
    }

    /// Searches for properties in space by key using case-insensitive match.
    /// If a property is type select or multi-select, the tags are included.
    ///
    /// This method requires cache to be enabled (the default).
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use anytype::prelude::*;
    /// # async fn example(client: &AnytypeClient) -> Result<(), AnytypeError> {
    /// let prop = client.lookup_property_by_key("space_id", "status").await?;
    /// println!("Property {} format {}", &prop.name, &prop.format());
    /// // display tags, for Select and MultiSelect properties
    /// if let Some(tags) = prop.tags() {
    ///   println!("Values:");
    ///   for tag in tags {
    ///     println!("    {} {}", &tag.key, &tag.name);
    ///   }
    /// }
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// Errors:
    /// - `AnytypeError::NotFound` if no property in the space matched
    /// - `AnytypeError::CacheDisabled` if cache is disabled
    /// - `AnytypeError::*` any other error
    ///
    pub async fn lookup_property_by_key(
        &self,
        space_id: &str,
        text: impl AsRef<str>,
    ) -> Result<Property> {
        ensure!(self.cache.is_enabled(), CacheDisabledSnafu);
        // see note on locking design in cache.rs
        if !self.cache.has_properties(space_id) {
            prime_cache_properties(&self.client, &self.cache, &self.config.limits, space_id)
                .await?;
        }
        self.cache
            .lookup_property_by_key(space_id, text.as_ref())
            .map_or_else(
                || {
                    Err(AnytypeError::NotFound {
                        obj_type: "Property".into(),
                        key: text.as_ref().to_string(),
                    })
                },
                |property| Ok((*property).clone()),
            )
    }

    /// Searches for property and tag combination.
    /// `property_key` can be a property key or id
    /// `tag_name` can be tag id, name, or key
    ///
    /// An explicit property ID is fetched with one metadata-only,
    /// cache-independent scoped GET before tag options are scanned in explicit
    /// 99-row pages. The scan examines at most
    /// [`MAX_RESOLVE_SCAN_ITEMS`] options and returns
    /// [`AnytypeError::ResolutionLimitExceeded`] rather than guessing when
    /// completeness exceeds that bound. The advertised total must stay stable,
    /// continuation pages must be complete, and a terminal page must account
    /// for the total before either a matching tag or `NotFound` is returned. A
    /// property key retains the cached key lookup behavior and therefore
    /// requires cache to be enabled (the default).
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use anytype::prelude::*;
    /// # async fn example(client: &AnytypeClient) -> Result<(), AnytypeError> {
    /// let in_progress = client
    ///     .lookup_property_tag("space_id", "status", "In Progress")
    ///     .await?;
    /// println!("Tag:'{}' id:'{}'", &in_progress.name, &in_progress.id);
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// Errors:
    /// - `AnytypeError::NotFound` if no property in the space matched, or tag doesn't match
    /// - `AnytypeError::CacheDisabled` if cache is disabled and a property key
    ///   was supplied
    /// - `AnytypeError::*` any other error
    ///
    pub async fn lookup_property_tag(
        &self,
        space_id: &str,
        property_key: impl AsRef<str>,
        tag_name: impl AsRef<str>,
    ) -> Result<Tag> {
        let prop_key_or_id = property_key.as_ref();
        let tag_key_or_id = tag_name.as_ref();
        if looks_like_object_id(prop_key_or_id) {
            let property = self.property(space_id, prop_key_or_id).get_direct().await?;
            if !matches!(
                property.format(),
                PropertyFormat::Select | PropertyFormat::MultiSelect
            ) {
                return NotFoundSnafu {
                    obj_type: "Tag".to_owned(),
                    key: tag_key_or_id.to_owned(),
                }
                .fail();
            }
            return self
                .lookup_property_tag_bounded(space_id, prop_key_or_id, tag_key_or_id)
                .await;
        }

        self.lookup_property_by_key(space_id, prop_key_or_id)
            .await?
            .lookup_tag(tag_key_or_id)
    }

    async fn lookup_property_tag_bounded(
        &self,
        space_id: &str,
        property_id: &str,
        tag_key_or_id: &str,
    ) -> Result<Tag> {
        const MAX_PAGES: usize = MAX_RESOLVE_SCAN_ITEMS.div_ceil(RESOLVE_PAGE_SIZE as usize);

        let needle = tag_key_or_id.to_lowercase();
        let mut offset = 0_u32;
        let mut scanned = 0_usize;
        let mut advertised_total = None;
        for _ in 0..MAX_PAGES {
            let remaining = MAX_RESOLVE_SCAN_ITEMS.saturating_sub(scanned);
            if remaining == 0 {
                return Err(resolution_limit("tag", tag_key_or_id));
            }
            let requested_limit = RESOLVE_PAGE_SIZE.min(remaining as u32);
            let page = self
                .tags(space_id, property_id)
                .limit(requested_limit)
                .offset(offset)
                .list()
                .await?
                .into_response();
            let total = page.pagination.total;
            if let Some(expected_total) = advertised_total {
                if total != expected_total {
                    return Err(malformed_tag_pagination());
                }
            } else {
                advertised_total = Some(total);
            }
            if total > MAX_RESOLVE_SCAN_ITEMS {
                return Err(resolution_limit("tag", tag_key_or_id));
            }

            let Ok(page_offset) = usize::try_from(page.pagination.offset) else {
                return Err(malformed_tag_pagination());
            };
            let Some(page_end) = page_offset.checked_add(page.items.len()) else {
                return Err(malformed_tag_pagination());
            };
            let has_remaining = page_end < total;
            if page.pagination.offset != offset
                || page_offset != scanned
                || page.pagination.limit != requested_limit
                || page.items.len() > remaining
                || page.items.len() > requested_limit as usize
                || page_end > total
                || page.pagination.has_more != has_remaining
                || (page.pagination.has_more && page.items.len() != requested_limit as usize)
            {
                return Err(malformed_tag_pagination());
            }

            for tag in &page.items {
                if tag.id == needle || tag.key == needle || tag.name.to_lowercase() == needle {
                    return Ok(tag.clone());
                }
            }
            scanned = page_end;

            if scanned == MAX_RESOLVE_SCAN_ITEMS && page.pagination.has_more {
                return Err(resolution_limit("tag", tag_key_or_id));
            }
            if !page.pagination.has_more {
                return NotFoundSnafu {
                    obj_type: "Tag".to_owned(),
                    key: tag_key_or_id.to_owned(),
                }
                .fail();
            }
            offset = offset
                .checked_add(requested_limit)
                .ok_or_else(|| resolution_limit("tag", tag_key_or_id))?;
        }
        Err(resolution_limit("tag", tag_key_or_id))
    }
}

fn malformed_tag_pagination() -> AnytypeError {
    AnytypeError::Other {
        message: "Anytype returned malformed tag pagination".to_owned(),
    }
}

// ============================================================================
// TESTS
// ============================================================================

#[cfg(test)]
mod tests {
    use std::collections::BTreeMap;

    use super::*;

    const TEST_SPACE_ID: &str =
        "bafyreid5fvqlnsobih2keakcxjrrlpmly6kf37klzjzen4ibfdgalcdp4y.2tq5w93cr6oe7";
    const TEST_PROPERTY_ID: &str = "bafyreid5fvqlnsobih2keakcxjrrlpmly6kf37klzjzen4ibfdgalcdp4y";
    const OTHER_PROPERTY_ID: &str = "bafyreid5fvqlnsobih2keakcxjrrlpmly6kf37klzjzen4ibfdgalcdp4z";
    const TEST_TAG_ID: &str = "bafyreid5fvqlnsobih2keakcxjrrlpmly6kf37klzjzen4ibfdgalcdp4x";

    #[test]
    fn property_schema_preserves_discriminator() {
        let response: PropertyResponse = serde_json::from_value(serde_json::json!({
            "property": {
                "object": "property",
                "name": "Description",
                "key": "description",
                "id": "property-id",
                "format": "text"
            }
        }))
        .expect("property response schema");

        assert_eq!(response.property.object, DataModel::Property);
        let serialized = serde_json::to_value(response.property).expect("serialize property");
        assert_eq!(serialized["object"], "property");
    }

    #[test]
    fn property_discriminator_defaults_when_omitted_and_preserves_present_value() {
        let property_without_discriminator: Property = serde_json::from_value(serde_json::json!({
            "name": "Description",
            "key": "description",
            "id": "property-id",
            "format": "text"
        }))
        .expect("property without discriminator");
        assert_eq!(property_without_discriminator.object, DataModel::Property);

        let property_with_observed_tag: Property = serde_json::from_value(serde_json::json!({
            "object": "tag",
            "name": "Description",
            "key": "description",
            "id": "property-id",
            "format": "text"
        }))
        .expect("property with observed discriminator");
        assert_eq!(property_with_observed_tag.object, DataModel::Tag);
    }

    #[derive(Debug, Default)]
    struct PropertyRouteTraffic {
        requests: Vec<String>,
        property_list_pages: usize,
        direct_property_gets: usize,
        tag_list_pages: usize,
    }

    #[derive(Clone, Copy)]
    enum TagRoute {
        Single,
        TargetSecondPage,
        OverLimitTarget,
        FalseTerminal,
        ChangingTotal,
        ValidAbsentSecondPage,
    }

    fn full_unrelated_tag_page() -> Vec<serde_json::Value> {
        (0..99)
            .map(|index| {
                serde_json::json!({
                    "id": format!("other-tag-{index}"),
                    "key": format!("other_{index}"),
                    "name": format!("Other {index}"),
                    "color": "grey"
                })
            })
            .collect()
    }

    async fn route_aware_property_server(
        returned_property_id: &'static str,
        tag_route: TagRoute,
    ) -> (
        String,
        tokio::sync::oneshot::Sender<()>,
        tokio::task::JoinHandle<PropertyRouteTraffic>,
    ) {
        use tokio::io::{AsyncReadExt, AsyncWriteExt};

        let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
            .await
            .expect("bind route-aware property fixture");
        let address = listener.local_addr().expect("property fixture address");
        let (shutdown_tx, mut shutdown_rx) = tokio::sync::oneshot::channel();
        let task = tokio::spawn(async move {
            let mut traffic = PropertyRouteTraffic::default();
            loop {
                let accepted = tokio::select! {
                    _ = &mut shutdown_rx => break,
                    accepted = listener.accept() => accepted,
                };
                let (mut stream, _) = accepted.expect("accept property fixture request");
                let mut request = Vec::new();
                let mut buffer = [0_u8; 1024];
                loop {
                    let read = stream
                        .read(&mut buffer)
                        .await
                        .expect("read property fixture request");
                    assert!(
                        read > 0,
                        "property fixture connection closed before headers"
                    );
                    request.extend_from_slice(&buffer[..read]);
                    assert!(
                        request.len() <= 64 * 1024,
                        "property fixture headers too large"
                    );
                    if request.windows(4).any(|window| window == b"\r\n\r\n") {
                        break;
                    }
                }
                let request = String::from_utf8(request).expect("property request is utf-8");
                let request_line = request.lines().next().expect("property request line");
                let mut parts = request_line.split_ascii_whitespace();
                assert_eq!(parts.next(), Some("GET"));
                let target = parts.next().expect("property request target");
                assert_eq!(parts.next(), Some("HTTP/1.1"));
                assert_eq!(parts.next(), None, "extra property request-line field");
                let (path, raw_query) = target
                    .split_once('?')
                    .map_or((target, ""), |(path, query)| (path, query));
                let mut query = BTreeMap::new();
                for (key, value) in url::form_urlencoded::parse(raw_query.as_bytes()) {
                    let previous = query.insert(key.into_owned(), value.into_owned());
                    assert!(previous.is_none(), "duplicate property query key");
                }
                let collection_path = format!("/v1/spaces/{TEST_SPACE_ID}/properties");
                let direct_path = format!("{collection_path}/{TEST_PROPERTY_ID}");
                let tags_path = format!("{direct_path}/tags");
                let body = if path == collection_path {
                    let page = traffic.property_list_pages;
                    traffic.property_list_pages += 1;
                    if page == 0 {
                        assert_eq!(query, BTreeMap::new(), "first property-list query");
                        serde_json::json!({
                            "data": [{
                                "id": OTHER_PROPERTY_ID,
                                "key": "other",
                                "name": "Other",
                                "format": "text",
                                "tags": null
                            }],
                            "pagination": {
                                "has_more": true,
                                "limit": 100,
                                "offset": 0,
                                "total": 101
                            }
                        })
                        .to_string()
                    } else {
                        assert_eq!(
                            query,
                            BTreeMap::from([
                                ("limit".to_owned(), "100".to_owned()),
                                ("offset".to_owned(), "100".to_owned()),
                            ]),
                            "continued property-list query"
                        );
                        serde_json::json!({
                            "data": [{
                                "id": TEST_PROPERTY_ID,
                                "key": "status",
                                "name": "Status",
                                "format": "select",
                                "tags": null
                            }],
                            "pagination": {
                                "has_more": false,
                                "limit": 100,
                                "offset": 100,
                                "total": 101
                            }
                        })
                        .to_string()
                    }
                } else if path == direct_path {
                    assert_eq!(query, BTreeMap::new(), "direct property query");
                    traffic.direct_property_gets += 1;
                    serde_json::json!({
                        "property": {
                            "id": returned_property_id,
                            "key": "status",
                            "name": "private-property-body-marker",
                            "format": "select",
                            "tags": [{
                                "id": OTHER_PROPERTY_ID,
                                "key": "embedded-private-tag",
                                "name": "embedded private tag",
                                "color": "red"
                            }]
                        }
                    })
                    .to_string()
                } else if path == tags_path {
                    let page = traffic.tag_list_pages;
                    traffic.tag_list_pages += 1;
                    let expected_query = if page == 0 {
                        BTreeMap::from([("limit".to_owned(), "99".to_owned())])
                    } else {
                        BTreeMap::from([
                            ("limit".to_owned(), "99".to_owned()),
                            ("offset".to_owned(), "99".to_owned()),
                        ])
                    };
                    assert_eq!(query, expected_query, "tag-list query for page {page}");
                    match (tag_route, page) {
                        (TagRoute::Single, 0) => serde_json::json!({
                            "data": [{
                                "id": TEST_TAG_ID,
                                "key": "open",
                                "name": "Open",
                                "color": "blue"
                            }],
                            "pagination": {
                                "has_more": false,
                                "limit": 99,
                                "offset": 0,
                                "total": 1
                            }
                        })
                        .to_string(),
                        (
                            TagRoute::TargetSecondPage
                            | TagRoute::ChangingTotal
                            | TagRoute::ValidAbsentSecondPage,
                            0,
                        ) => {
                            let tags = full_unrelated_tag_page();
                            serde_json::json!({
                                "data": tags,
                                "pagination": {
                                    "has_more": true,
                                    "limit": 99,
                                    "offset": 0,
                                    "total": 100
                                }
                            })
                            .to_string()
                        }
                        (TagRoute::TargetSecondPage, 1) => serde_json::json!({
                            "data": [{
                                "id": TEST_TAG_ID,
                                "key": "open",
                                "name": "Open",
                                "color": "blue"
                            }],
                            "pagination": {
                                "has_more": false,
                                "limit": 99,
                                "offset": 99,
                                "total": 100
                            }
                        })
                        .to_string(),
                        (TagRoute::OverLimitTarget, 0) => serde_json::json!({
                            "data": [{
                                "id": TEST_TAG_ID,
                                "key": "open",
                                "name": "Open",
                                "color": "blue"
                            }],
                            "pagination": {
                                "has_more": true,
                                "limit": 99,
                                "offset": 0,
                                "total": 1001
                            }
                        })
                        .to_string(),
                        (TagRoute::FalseTerminal, 0) => serde_json::json!({
                            "data": [{
                                "id": "other-tag",
                                "key": "other",
                                "name": "Other",
                                "color": "grey"
                            }],
                            "pagination": {
                                "has_more": false,
                                "limit": 99,
                                "offset": 0,
                                "total": 1000
                            }
                        })
                        .to_string(),
                        (TagRoute::ChangingTotal, 1) => serde_json::json!({
                            "data": [{
                                "id": TEST_TAG_ID,
                                "key": "open",
                                "name": "Open",
                                "color": "blue"
                            }],
                            "pagination": {
                                "has_more": true,
                                "limit": 99,
                                "offset": 99,
                                "total": 101
                            }
                        })
                        .to_string(),
                        (TagRoute::ValidAbsentSecondPage, 1) => serde_json::json!({
                            "data": [{
                                "id": "last-other-tag",
                                "key": "last_other",
                                "name": "Last Other",
                                "color": "grey"
                            }],
                            "pagination": {
                                "has_more": false,
                                "limit": 99,
                                "offset": 99,
                                "total": 100
                            }
                        })
                        .to_string(),
                        _ => panic!("unexpected tag fixture page {page}"),
                    }
                } else {
                    panic!("unexpected property fixture route: {request_line}");
                };
                let response = format!(
                    "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
                    body.len()
                );
                traffic.requests.push(request);
                stream
                    .write_all(response.as_bytes())
                    .await
                    .expect("write property fixture response");
                stream
                    .shutdown()
                    .await
                    .expect("shutdown property fixture response");
            }
            traffic
        });
        (format!("http://{address}"), shutdown_tx, task)
    }

    fn route_fixture_client(base_url: String) -> AnytypeClient {
        let mut config = crate::client::ClientConfig::default().app_name("property-route-fixture");
        config.base_url = Some(base_url);
        config.keystore = Some("env".to_owned());
        let client = AnytypeClient::with_config(config).expect("property fixture client");
        client.set_api_key(crate::keystore::HttpCredentials::new("fixture-token"));
        client
    }

    #[tokio::test]
    async fn direct_property_get_is_cache_independent_and_exactly_scoped() {
        let (base_url, shutdown, traffic) =
            route_aware_property_server(TEST_PROPERTY_ID, TagRoute::Single).await;
        let client = route_fixture_client(base_url);
        assert!(
            client.cache().is_enabled(),
            "fixture must exercise cache-on behavior"
        );

        let property = client
            .property(TEST_SPACE_ID, TEST_PROPERTY_ID)
            .with_tags()
            .get_direct()
            .await
            .expect("direct property");
        assert_eq!(property.id, TEST_PROPERTY_ID);
        assert!(
            property.tags().is_none(),
            "direct metadata must discard embedded tags"
        );

        shutdown.send(()).expect("stop property fixture");
        let traffic = traffic.await.expect("property fixture task");
        assert_eq!(
            traffic.property_list_pages, 0,
            "must not prime property cache"
        );
        assert_eq!(traffic.direct_property_gets, 1);
        assert_eq!(traffic.tag_list_pages, 0);
        assert_eq!(traffic.requests.len(), 1);
        assert_eq!(
            traffic.requests[0].lines().next().unwrap(),
            format!("GET /v1/spaces/{TEST_SPACE_ID}/properties/{TEST_PROPERTY_ID} HTTP/1.1")
        );
    }

    #[tokio::test]
    async fn explicit_id_tag_lookup_uses_direct_property_get_with_cold_cache() {
        let (base_url, shutdown, traffic) =
            route_aware_property_server(TEST_PROPERTY_ID, TagRoute::Single).await;
        let client = route_fixture_client(base_url);
        assert!(
            client.cache().is_enabled(),
            "fixture must exercise cache-on behavior"
        );

        let tag = client
            .lookup_property_tag(TEST_SPACE_ID, TEST_PROPERTY_ID, "Open")
            .await
            .expect("explicit-id tag lookup");
        assert_eq!(tag.id, TEST_TAG_ID);

        shutdown.send(()).expect("stop property fixture");
        let traffic = traffic.await.expect("property fixture task");
        assert_eq!(
            traffic.property_list_pages, 0,
            "must not prime property cache"
        );
        assert_eq!(traffic.direct_property_gets, 1);
        assert_eq!(traffic.tag_list_pages, 1);
        assert_eq!(traffic.requests.len(), 2);
    }

    #[tokio::test]
    async fn explicit_id_tag_lookup_finds_second_page_target_within_budget() {
        let (base_url, shutdown, traffic) =
            route_aware_property_server(TEST_PROPERTY_ID, TagRoute::TargetSecondPage).await;
        let client = route_fixture_client(base_url);

        let tag = client
            .lookup_property_tag(TEST_SPACE_ID, TEST_PROPERTY_ID, "open")
            .await
            .expect("bounded second-page tag lookup");
        assert_eq!(tag.id, TEST_TAG_ID);

        shutdown.send(()).expect("stop property fixture");
        let traffic = traffic.await.expect("property fixture task");
        assert_eq!(traffic.property_list_pages, 0);
        assert_eq!(traffic.direct_property_gets, 1);
        assert_eq!(traffic.tag_list_pages, 2);
        assert_eq!(traffic.requests.len(), 3);
    }

    #[tokio::test]
    async fn explicit_id_tag_lookup_rejects_over_budget_total_before_target() {
        let (base_url, shutdown, traffic) =
            route_aware_property_server(TEST_PROPERTY_ID, TagRoute::OverLimitTarget).await;
        let client = route_fixture_client(base_url);

        let error = client
            .lookup_property_tag(TEST_SPACE_ID, TEST_PROPERTY_ID, "open")
            .await
            .expect_err("over-budget total must precede a matching target");
        assert!(matches!(
            error,
            AnytypeError::ResolutionLimitExceeded {
                obj_type,
                limit: MAX_RESOLVE_SCAN_ITEMS,
                ..
            } if obj_type == "tag"
        ));

        shutdown.send(()).expect("stop property fixture");
        let traffic = traffic.await.expect("property fixture task");
        assert_eq!(traffic.property_list_pages, 0);
        assert_eq!(traffic.direct_property_gets, 1);
        assert_eq!(
            traffic.tag_list_pages, 1,
            "known over-budget total stops immediately"
        );
        assert_eq!(traffic.requests.len(), 2);
    }

    #[tokio::test]
    async fn explicit_id_tag_lookup_rejects_false_terminal_page() {
        let (base_url, shutdown, traffic) =
            route_aware_property_server(TEST_PROPERTY_ID, TagRoute::FalseTerminal).await;
        let client = route_fixture_client(base_url);

        let error = client
            .lookup_property_tag(TEST_SPACE_ID, TEST_PROPERTY_ID, "absent")
            .await
            .expect_err("incomplete terminal page must not report not-found");
        assert_malformed_tag_pagination(error);

        shutdown.send(()).expect("stop property fixture");
        let traffic = traffic.await.expect("property fixture task");
        assert_eq!(traffic.property_list_pages, 0);
        assert_eq!(traffic.direct_property_gets, 1);
        assert_eq!(traffic.tag_list_pages, 1);
        assert_eq!(traffic.requests.len(), 2);
    }

    #[tokio::test]
    async fn explicit_id_tag_lookup_rejects_changing_total_before_target() {
        let (base_url, shutdown, traffic) =
            route_aware_property_server(TEST_PROPERTY_ID, TagRoute::ChangingTotal).await;
        let client = route_fixture_client(base_url);

        let error = client
            .lookup_property_tag(TEST_SPACE_ID, TEST_PROPERTY_ID, "open")
            .await
            .expect_err("changing total must precede a matching target");
        assert_malformed_tag_pagination(error);

        shutdown.send(()).expect("stop property fixture");
        let traffic = traffic.await.expect("property fixture task");
        assert_eq!(traffic.property_list_pages, 0);
        assert_eq!(traffic.direct_property_gets, 1);
        assert_eq!(traffic.tag_list_pages, 2);
        assert_eq!(traffic.requests.len(), 3);
    }

    #[tokio::test]
    async fn explicit_id_tag_lookup_returns_not_found_only_after_complete_last_page() {
        let (base_url, shutdown, traffic) =
            route_aware_property_server(TEST_PROPERTY_ID, TagRoute::ValidAbsentSecondPage).await;
        let client = route_fixture_client(base_url);

        let error = client
            .lookup_property_tag(TEST_SPACE_ID, TEST_PROPERTY_ID, "absent")
            .await
            .expect_err("complete absent lookup must return not-found");
        assert!(matches!(
            error,
            AnytypeError::NotFound { obj_type, key }
                if obj_type == "Tag" && key == "absent"
        ));

        shutdown.send(()).expect("stop property fixture");
        let traffic = traffic.await.expect("property fixture task");
        assert_eq!(traffic.property_list_pages, 0);
        assert_eq!(traffic.direct_property_gets, 1);
        assert_eq!(traffic.tag_list_pages, 2);
        assert_eq!(traffic.requests.len(), 3);
    }

    fn assert_malformed_tag_pagination(error: AnytypeError) {
        let AnytypeError::Other { message } = &error else {
            panic!("malformed pagination must be an upstream error: {error}");
        };
        assert_eq!(message, "Anytype returned malformed tag pagination");
        let display = error.to_string();
        for private in [TEST_SPACE_ID, TEST_PROPERTY_ID, TEST_TAG_ID] {
            assert!(!display.contains(private), "pagination error leaked an id");
        }
    }

    #[tokio::test]
    async fn direct_property_identity_mismatch_is_secret_safe_and_skips_tags() {
        let (base_url, shutdown, traffic) =
            route_aware_property_server(OTHER_PROPERTY_ID, TagRoute::Single).await;
        let client = route_fixture_client(base_url);

        let error = client
            .lookup_property_tag(TEST_SPACE_ID, TEST_PROPERTY_ID, "Open")
            .await
            .expect_err("mismatched direct property must fail closed");
        let AnytypeError::Other { message } = &error else {
            panic!("identity mismatch must be an upstream error: {error}");
        };
        assert_eq!(message, "Anytype returned a mismatched property identity");
        let display = error.to_string();
        for private in [
            TEST_SPACE_ID,
            TEST_PROPERTY_ID,
            OTHER_PROPERTY_ID,
            "private-property-body-marker",
        ] {
            assert!(
                !display.contains(private),
                "error display leaked fixture data"
            );
        }

        shutdown.send(()).expect("stop property fixture");
        let traffic = traffic.await.expect("property fixture task");
        assert_eq!(traffic.property_list_pages, 0);
        assert_eq!(traffic.direct_property_gets, 1);
        assert_eq!(
            traffic.tag_list_pages, 0,
            "mismatch must stop before tag lookup"
        );
        assert_eq!(traffic.requests.len(), 1);
    }

    #[tokio::test]
    async fn direct_property_get_validates_both_ids_before_io() {
        let client = route_fixture_client("http://127.0.0.1:1".to_owned());
        for (space_id, property_id) in [
            ("unsafe/space", TEST_PROPERTY_ID),
            (TEST_SPACE_ID, "unsafe/property"),
        ] {
            let error = client
                .property(space_id, property_id)
                .get_direct()
                .await
                .expect_err("unsafe scoped id must fail before transport");
            assert!(matches!(error, AnytypeError::Validation { .. }));
        }
    }

    #[tokio::test]
    async fn property_key_tag_lookup_retains_documented_cache_requirement() {
        let mut config =
            crate::client::ClientConfig::default().app_name("property-key-cache-fixture");
        config.base_url = Some("http://127.0.0.1:1".to_owned());
        config.keystore = Some("env".to_owned());
        config.disable_cache = true;
        let client = AnytypeClient::with_config(config).expect("cache-disabled fixture client");
        client.set_api_key(crate::keystore::HttpCredentials::new("fixture-token"));

        let error = client
            .lookup_property_tag(TEST_SPACE_ID, "status", "Open")
            .await
            .expect_err("property-key lookup requires enabled cache");
        assert!(matches!(error, AnytypeError::CacheDisabled));
    }

    #[test]
    fn test_property_format_default() {
        let format: PropertyFormat = PropertyFormat::default();
        assert_eq!(format, PropertyFormat::Text);
    }

    #[test]
    fn test_property_format_display() {
        assert_eq!(PropertyFormat::Text.to_string(), "text");
        assert_eq!(PropertyFormat::Select.to_string(), "select");
        assert_eq!(PropertyFormat::MultiSelect.to_string(), "multi_select");
    }

    #[test]
    fn test_property_format_from_string() {
        use std::str::FromStr;
        assert_eq!(
            PropertyFormat::from_str("text").unwrap(),
            PropertyFormat::Text
        );
        assert_eq!(
            PropertyFormat::from_str("number").unwrap(),
            PropertyFormat::Number
        );
        assert_eq!(
            PropertyFormat::from_str("multi_select").unwrap(),
            PropertyFormat::MultiSelect
        );
    }

    #[test]
    fn test_property_value_as_str() {
        let text_val = PropertyValue::Text {
            text: "hello".to_string(),
        };
        assert_eq!(text_val.as_str(), Some("hello"));

        let url_val = PropertyValue::Url {
            url: "https://example.com".to_string(),
        };
        assert_eq!(url_val.as_str(), Some("https://example.com"));

        let files_val = PropertyValue::Files { files: vec![] };
        assert_eq!(files_val.as_str(), None);
    }

    #[test]
    fn test_property_value_as_bool() {
        let checkbox_true = PropertyValue::Checkbox { checkbox: true };
        assert_eq!(checkbox_true.as_bool(), Some(true));

        let checkbox_false = PropertyValue::Checkbox { checkbox: false };
        assert_eq!(checkbox_false.as_bool(), Some(false));

        let text_val = PropertyValue::Text {
            text: "true".to_string(),
        };
        assert_eq!(text_val.as_bool(), None);
    }

    #[test]
    fn test_property_value_as_array() {
        let files = PropertyValue::Files {
            files: vec!["file1".to_string(), "file2".to_string()],
        };
        assert_eq!(
            files.as_array(),
            Some(vec!["file1".to_string(), "file2".to_string()])
        );

        let text = PropertyValue::Text {
            text: "hello".to_string(),
        };
        assert_eq!(text.as_array(), None);
    }

    #[test]
    fn test_create_property_request_body_serialization() {
        let body = CreatePropertyRequestBody {
            name: "Priority".to_string(),
            key: Some("priority".to_string()),
            format: PropertyFormat::Select,
            tags: vec![],
        };

        let json = serde_json::to_string(&body).unwrap();
        assert!(json.contains("\"name\":\"Priority\""));
        assert!(json.contains("\"key\":\"priority\""));
        assert!(json.contains("\"format\":\"select\""));
    }

    #[test]
    fn test_update_property_request_body_requires_name_on_wire() {
        let body = UpdatePropertyRequestBody {
            name: "Priority".to_string(),
            key: None,
        };
        let json = serde_json::to_string(&body).unwrap();
        assert_eq!(json, r#"{"name":"Priority"}"#);
    }

    #[tokio::test]
    async fn test_update_property_rejects_key_without_name() {
        let mut config = crate::client::ClientConfig::default().app_name("property-update-unit");
        config.keystore = Some("env".to_string());
        let client = AnytypeClient::with_config(config).expect("client");
        let valid_id = "bafyreie6n5l5nkbjal37su54cha4coy7qzuhrnajluzv5qd5jvtsrxkequ";

        let error = client
            .update_property(valid_id, valid_id)
            .key("new_key")
            .update()
            .await
            .expect_err("a key-only REST update must fail validation");

        assert!(
            matches!(error, AnytypeError::Validation { ref message } if message.contains("name is required"))
        );
    }

    #[test]
    fn test_property_info_deserialization() {
        let json = r#"{
            "name": "Status",
            "format": "select",
            "id": "prop123",
            "key": "status"
        }"#;

        let prop: Property = serde_json::from_str(json).unwrap();
        assert_eq!(prop.name, "Status");
        assert_eq!(prop.format, PropertyFormat::Select);
        assert_eq!(prop.id, "prop123");
        assert_eq!(prop.key, "status");
    }
}