surrealdb-types 3.2.1

A scalable, distributed, collaborative, document-graph database, for the realtime web
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
use surrealdb_types::{
	AlreadyExistsError, AuthError, Chain, ConfigurationError, ConnectionError, ConversionError,
	Error, ErrorDetails, Kind, LengthMismatchError, NotAllowedError, NotFoundError, Number, Object,
	OutOfRangeError, QueryError, SerializationError, SurrealValue, TypeError, ValidationError,
	Value,
};

#[test]
fn test_conversion_error_basic() {
	let err = ConversionError::new(Kind::String, Kind::Int);

	assert_eq!(err.expected, Kind::String);
	assert_eq!(err.actual, Kind::Int);
	assert!(err.context.is_none());

	let msg = err.to_string();
	// Kind Display shows lowercase: "string", "int"
	assert!(msg.contains("string"));
	assert!(msg.contains("int"));
}

#[test]
fn test_conversion_error_from_value() {
	let value = Value::Number(42.into());
	let err = ConversionError::from_value(Kind::String, &value);

	assert_eq!(err.expected, Kind::String);
	assert_eq!(err.actual, Kind::Number);
}

#[test]
fn test_conversion_error_with_context() {
	let err =
		ConversionError::new(Kind::String, Kind::Int).with_context("field 'name' on struct User");

	assert_eq!(err.context, Some("field 'name' on struct User".to_string()));

	let msg = err.to_string();
	assert!(msg.contains("field 'name' on struct User"));
}

#[test]
fn test_out_of_range_error() {
	let err = OutOfRangeError::new(300, "i8");

	assert_eq!(err.value, "300");
	assert_eq!(err.target_type, "i8");
	assert!(err.context.is_none());

	let msg = err.to_string();
	assert!(msg.contains("300"));
	assert!(msg.contains("i8"));
	assert!(msg.contains("out of range"));
}

#[test]
fn test_out_of_range_error_with_context() {
	let err = OutOfRangeError::new(-1, "u8").with_context("array index");

	assert_eq!(err.context, Some("array index".to_string()));

	let msg = err.to_string();
	assert!(msg.contains("array index"));
}

#[test]
fn test_length_mismatch_error() {
	let err = LengthMismatchError::new(5, 3, "Vec<String>");

	assert_eq!(err.expected, 5);
	assert_eq!(err.actual, 3);
	assert_eq!(err.target_type, "Vec<String>");

	let msg = err.to_string();
	assert!(msg.contains("5"));
	assert!(msg.contains("3"));
	assert!(msg.contains("Vec<String>"));
	assert!(msg.contains("Length mismatch"));
}

#[test]
fn test_type_error_variants() {
	let conv_err = TypeError::Conversion(ConversionError::new(Kind::String, Kind::Int));
	let range_err = TypeError::OutOfRange(OutOfRangeError::new(256, "u8"));
	let len_err = TypeError::LengthMismatch(LengthMismatchError::new(3, 2, "tuple"));
	let invalid_err = TypeError::Invalid("custom error".to_owned());

	// All should display without panicking
	assert!(!conv_err.to_string().is_empty());
	assert!(!range_err.to_string().is_empty());
	assert!(!len_err.to_string().is_empty());
	assert!(!invalid_err.to_string().is_empty());
}

// Integration tests with actual conversions

#[test]
fn test_conversion_error_in_practice() {
	// Try to convert a number to a string
	let value = Value::Number(42.into());
	let result: Result<String, _> = value.into_t();

	assert!(result.is_err());
	let err = result.unwrap_err();

	let err_msg = err.to_string();
	// Kind Display shows lowercase
	assert!(err_msg.contains("string"));
	assert!(err_msg.contains("number"));
}

#[test]
fn test_out_of_range_error_in_practice() {
	// Try to convert a large number to i8
	let value = Value::Number(300.into());
	let result: Result<i8, _> = value.into_t();

	assert!(result.is_err());
	let err = result.unwrap_err();

	let err_msg = err.to_string();
	assert!(err_msg.contains("300"));
	assert!(err_msg.contains("out of range") || err_msg.contains("i8"));
}

#[test]
fn test_length_mismatch_in_practice() {
	// Try to convert wrong-length array to tuple
	let value = Value::Array(vec![Value::Number(1.into()), Value::Number(2.into())].into());
	let result: Result<(i64, i64, i64), _> = value.into_t();

	assert!(result.is_err());
	let err = result.unwrap_err();

	let err_msg = err.to_string();
	assert!(err_msg.contains("3") && err_msg.contains("2") || err_msg.contains("Length"));
}

#[test]
fn test_u8_overflow() {
	let value = Value::Number(256.into());
	let result: Result<u8, _> = value.into_t();

	assert!(result.is_err());
	let err = result.unwrap_err();
	let err_msg = err.to_string();

	// Should mention 256 and u8
	assert!(err_msg.contains("256"));
	assert!(err_msg.contains("u8") || err_msg.contains("out of range"));
}

#[test]
fn test_u8_underflow() {
	let value = Value::Number((-1).into());
	let result: Result<u8, _> = value.into_t();

	assert!(result.is_err());
	let err = result.unwrap_err();
	let err_msg = err.to_string();

	// Should mention -1 and u8
	assert!(err_msg.contains("-1") || err_msg.contains("out of range"));
}

#[test]
fn test_i8_overflow() {
	let value = Value::Number(128.into());
	let result: Result<i8, _> = value.into_t();

	assert!(result.is_err());
}

#[test]
fn test_i8_underflow() {
	let value = Value::Number((-129).into());
	let result: Result<i8, _> = value.into_t();

	assert!(result.is_err());
}

#[test]
fn test_u64_success() {
	// This should work
	let value = Value::Number(Number::Int(i64::MAX));
	let result: Result<u64, _> = value.into_t();

	assert!(result.is_ok());
}

#[test]
fn test_array_length_mismatch_tuple() {
	// 2-element array into 3-element tuple
	let value = Value::Array(vec![Value::Number(1.into()), Value::Number(2.into())].into());
	let result: Result<(i64, i64, i64), _> = value.into_t();

	assert!(result.is_err());
	let err = result.unwrap_err();
	let err_msg = err.to_string();

	// Should mention expected 3, got 2
	assert!(err_msg.contains("Length") || (err_msg.contains("3") && err_msg.contains("2")));
}

#[test]
fn test_fixed_array_length_mismatch() {
	// Wrong length for fixed-size array
	let value = Value::Array(vec![Value::Number(1.into()), Value::Number(2.into())].into());
	let result: Result<[i64; 5], _> = value.into_t();

	assert!(result.is_err());
	let err = result.unwrap_err();
	let err_msg = err.to_string();

	// Should mention array length issue
	assert!(err_msg.contains("5") && err_msg.contains("2"));
}

#[test]
fn test_nested_conversion_error() {
	// Array with wrong inner type
	let value = Value::Array(
		vec![
			Value::String("hello".to_string()),
			Value::Number(42.into()), // Wrong type!
		]
		.into(),
	);
	let result: Result<Vec<String>, _> = value.into_t();

	assert!(result.is_err());
	let err = result.unwrap_err();
	let err_msg = err.to_string();

	// Should mention the type mismatch (lowercase)
	assert!(err_msg.contains("string") || err_msg.contains("number"));
}

#[test]
fn test_conversion_errors_implement_std_error() {
	// Ensure our conversion errors implement std::error::Error and have non-empty display
	let conv_err = ConversionError::new(Kind::String, Kind::Int);
	assert!(!conv_err.to_string().is_empty());

	let range_err = OutOfRangeError::new(300, "i8");
	assert!(!range_err.to_string().is_empty());

	let len_err = LengthMismatchError::new(3, 2, "tuple");
	assert!(!len_err.to_string().is_empty());
}

#[test]
fn test_multiple_numeric_types() {
	// Test all numeric types for safety
	let values = vec![
		(Value::Number(0.into()), true),     // 0 fits in all types
		(Value::Number(255.into()), true),   // Max u8
		(Value::Number(256.into()), false),  // Over u8
		(Value::Number((-1).into()), false), // Under u8
	];

	for (value, should_succeed) in values {
		let result: Result<u8, _> = value.into_t();
		assert_eq!(result.is_ok(), should_succeed, "Failed for u8 with {:?}", result);
	}
}

#[test]
fn test_error_message_quality() {
	// Ensure error messages are helpful
	let value = Value::String("hello".to_string());
	let result: Result<i64, _> = value.into_t();

	let err_msg = result.unwrap_err().to_string();

	// Good error messages should:
	// 1. Mention what was expected
	assert!(err_msg.to_lowercase().contains("int") || err_msg.to_lowercase().contains("number"));

	// 2. Mention what was received
	assert!(err_msg.contains("String") || err_msg.contains("string"));

	println!("Error message: {}", err_msg);
}

// -----------------------------------------------------------------------------
// Public API Error type (wire-friendly, chaining)
// -----------------------------------------------------------------------------

#[test]
fn test_public_error_new() {
	let err = Error::not_found("The table 'users' does not exist".to_string(), None);

	assert!(err.is_not_found());
	assert_eq!(err.message(), "The table 'users' does not exist");
	assert!(err.not_found_details().is_none());
}

#[test]
fn test_public_error_with_details() {
	let err = Error::not_allowed("Token expired".to_string(), AuthError::TokenExpired);

	assert!(err.is_not_allowed());
	let d = err.not_allowed_details().unwrap();
	assert!(matches!(d, NotAllowedError::Auth(AuthError::TokenExpired)));
}

#[test]
fn test_public_error_validation_details() {
	let err =
		Error::validation("Invalid request".to_string(), Some(ValidationError::InvalidRequest));
	assert!(err.is_validation());
	assert_eq!(err.validation_details(), Some(&ValidationError::InvalidRequest));

	let err_no_details = Error::validation("Parse error".to_string(), None);
	assert_eq!(err_no_details.validation_details(), None);
	assert!(err_no_details.is_validation()); // kind is still Validation

	let err_wrong_kind = Error::not_allowed("Auth failed".to_string(), None);
	assert_eq!(err_wrong_kind.validation_details(), None);
}

#[test]
fn test_public_error_display() {
	let err = Error::thrown("Something went wrong".to_string());
	assert!(err.to_string().contains("Something went wrong"));
}

#[test]
fn test_public_error_details_pattern_matching() {
	let err = Error::not_found(
		"Table not found".to_string(),
		NotFoundError::Table {
			name: "users".into(),
		},
	);

	// Users can pattern match on ErrorDetails directly
	match err.details() {
		ErrorDetails::NotFound(Some(NotFoundError::Table {
			name,
		})) => assert_eq!(name, "users"),
		_ => panic!("Expected NotFound Table details"),
	}
}

#[test]
fn test_error_kind_unknown_falls_back_to_internal() {
	// Forward compatibility: unknown wire kind strings fall back to Internal
	// so that older SDKs can still deserialize errors from newer servers.
	let mut obj = Object::new();
	obj.insert("kind", "future_kind");
	obj.insert("message", "Message");
	let value = Value::Object(obj);
	let err = Error::from_value(value).unwrap();
	assert!(err.is_internal());
	assert_eq!(err.message(), "Message");
}

#[test]
fn test_error_deserialize_without_kind_defaults_to_internal() {
	// Backwards compatibility: wire format without "kind" (e.g. older clients) defaults to Internal
	// when deserialising via SurrealValue::from_value (#[surreal(default)]).
	let mut obj = Object::new();
	obj.insert("message", "Something went wrong");
	let value = Value::Object(obj);
	let err = Error::from_value(value).unwrap();
	assert!(err.is_internal());
	assert_eq!(err.message(), "Something went wrong");
}

// -----------------------------------------------------------------------------
// Detail enum wire format: { kind, details? } pattern
// -----------------------------------------------------------------------------

#[test]
fn test_detail_wire_format_unit_variant() {
	// Unit variants produce { "kind": "VariantName" } with no details field
	let val = AuthError::TokenExpired.into_value();
	let Value::Object(obj) = &val else {
		panic!("Expected object, got {val:?}");
	};
	assert_eq!(obj.get("kind"), Some(&Value::String("TokenExpired".into())));
	assert!(!obj.contains_key("details"), "Unit variant should not have details field");

	// Round-trip
	let parsed = AuthError::from_value(val).unwrap();
	assert_eq!(parsed, AuthError::TokenExpired);
}

#[test]
fn test_detail_wire_format_struct_variant() {
	// Struct variants produce { "kind": "VariantName", "details": { fields... } }
	let val = AuthError::InvalidRole {
		name: "admin".into(),
	}
	.into_value();
	let Value::Object(obj) = &val else {
		panic!("Expected object, got {val:?}");
	};
	assert_eq!(obj.get("kind"), Some(&Value::String("InvalidRole".into())));
	let Some(Value::Object(details)) = obj.get("details") else {
		panic!("Expected details object");
	};
	assert_eq!(details.get("name"), Some(&Value::String("admin".into())));

	// Round-trip
	let parsed = AuthError::from_value(val).unwrap();
	assert_eq!(
		parsed,
		AuthError::InvalidRole {
			name: "admin".into()
		}
	);
}

#[test]
fn test_detail_wire_format_newtype_variant() {
	// Newtype variant (Auth wrapping AuthError) produces nested { kind, details? }
	let val = NotAllowedError::Auth(AuthError::TokenExpired).into_value();
	let Value::Object(obj) = &val else {
		panic!("Expected object, got {val:?}");
	};
	assert_eq!(obj.get("kind"), Some(&Value::String("Auth".into())));
	let Some(Value::Object(inner)) = obj.get("details") else {
		panic!("Expected details object with inner auth error");
	};
	assert_eq!(inner.get("kind"), Some(&Value::String("TokenExpired".into())));
	assert!(!inner.contains_key("details"), "Inner unit variant should not have details");

	// Round-trip
	let parsed = NotAllowedError::from_value(val).unwrap();
	assert_eq!(parsed, NotAllowedError::Auth(AuthError::TokenExpired));
}

#[test]
fn test_detail_wire_format_newtype_with_struct_inner() {
	// Auth wrapping a struct variant
	let val = NotAllowedError::Auth(AuthError::NotAllowed {
		actor: "user:john".into(),
		action: "edit".into(),
		resource: "table:secrets".into(),
	})
	.into_value();
	let Value::Object(obj) = &val else {
		panic!("Expected object");
	};
	assert_eq!(obj.get("kind"), Some(&Value::String("Auth".into())));
	let Some(Value::Object(inner)) = obj.get("details") else {
		panic!("Expected details");
	};
	assert_eq!(inner.get("kind"), Some(&Value::String("NotAllowed".into())));
	let Some(Value::Object(inner_details)) = inner.get("details") else {
		panic!("Expected inner details");
	};
	assert_eq!(inner_details.get("actor"), Some(&Value::String("user:john".into())));

	// Round-trip
	let parsed = NotAllowedError::from_value(val).unwrap();
	assert!(matches!(parsed, NotAllowedError::Auth(AuthError::NotAllowed { .. })));
}

#[test]
fn test_detail_wire_format_all_flat_enums() {
	// Verify all flat detail enums produce the { kind, details? } pattern

	// ValidationError unit
	let val = ValidationError::Parse.into_value();
	let parsed = ValidationError::from_value(val).unwrap();
	assert_eq!(parsed, ValidationError::Parse);

	// ValidationError struct
	let val = ValidationError::InvalidParameter {
		name: "x".into(),
	}
	.into_value();
	let parsed = ValidationError::from_value(val).unwrap();
	assert_eq!(
		parsed,
		ValidationError::InvalidParameter {
			name: "x".into()
		}
	);

	// ConfigurationError unit
	let val = ConfigurationError::LiveQueryNotSupported.into_value();
	let parsed = ConfigurationError::from_value(val).unwrap();
	assert_eq!(parsed, ConfigurationError::LiveQueryNotSupported);

	// SerializationError unit
	let val = SerializationError::Deserialization.into_value();
	let parsed = SerializationError::from_value(val).unwrap();
	assert_eq!(parsed, SerializationError::Deserialization);

	// NotFoundError struct
	let val = NotFoundError::Table {
		name: "users".into(),
	}
	.into_value();
	let Value::Object(obj) = &val else {
		panic!("Expected object");
	};
	assert_eq!(obj.get("kind"), Some(&Value::String("Table".into())));
	let parsed = NotFoundError::from_value(val).unwrap();
	assert_eq!(
		parsed,
		NotFoundError::Table {
			name: "users".into()
		}
	);

	// NotFoundError unit
	let val = NotFoundError::Transaction.into_value();
	let parsed = NotFoundError::from_value(val).unwrap();
	assert_eq!(parsed, NotFoundError::Transaction);

	// AlreadyExistsError struct
	let val = AlreadyExistsError::Record {
		id: "users:123".into(),
	}
	.into_value();
	let parsed = AlreadyExistsError::from_value(val).unwrap();
	assert_eq!(
		parsed,
		AlreadyExistsError::Record {
			id: "users:123".into()
		}
	);

	// ConnectionError unit
	let val = ConnectionError::Uninitialised.into_value();
	let parsed = ConnectionError::from_value(val).unwrap();
	assert_eq!(parsed, ConnectionError::Uninitialised);
}

#[test]
fn test_detail_wire_format_full_error_round_trip() {
	// Full Error with NotAllowed + Auth(TokenExpired) round-trips through into_value/from_value.
	// Wire format:
	// {
	//   "code": -32002,
	//   "message": "Token expired",
	//   "kind": "NotAllowed",
	//   "details": { "kind": "Auth", "details": { "kind": "TokenExpired" } }
	// }
	let err = Error::not_allowed("Token expired".to_string(), AuthError::TokenExpired);
	let val = err.into_value();
	let parsed = Error::from_value(val).unwrap();
	assert!(parsed.is_not_allowed());
	assert_eq!(parsed.message(), "Token expired");
	let details = parsed.not_allowed_details().unwrap();
	assert!(matches!(details, NotAllowedError::Auth(AuthError::TokenExpired)));
}

#[test]
fn test_detail_wire_format_query_timeout() {
	// QueryError::TimedOut detail enum serialization.
	// Wire format (detail only):
	// { "kind": "TimedOut", "details": { "duration": { "secs": 5, "nanos": 0 } } }
	use std::time::Duration;
	let val = QueryError::TimedOut {
		duration: Duration::from_secs(5),
	}
	.into_value();
	let Value::Object(obj) = &val else {
		panic!("Expected object");
	};
	assert_eq!(obj.get("kind"), Some(&Value::String("TimedOut".into())));
	assert!(obj.contains_key("details"), "Struct variant should have details field");

	let parsed = QueryError::from_value(val).unwrap();
	assert!(
		matches!(parsed, QueryError::TimedOut { duration } if duration == Duration::from_secs(5))
	);
}

// -----------------------------------------------------------------------------
// Error serialization snapshots: verify exact wire format and round-trip
// Each test documents the full JSON structure in comments.
// -----------------------------------------------------------------------------

#[test]
fn test_error_snapshot_not_allowed_auth_token_expired() {
	// Wire format:
	// {
	//   "code": -32002,
	//   "message": "Token expired",
	//   "kind": "NotAllowed",
	//   "details": { "kind": "Auth", "details": { "kind": "TokenExpired" } }
	// }
	let err = Error::not_allowed("Token expired".to_string(), AuthError::TokenExpired);
	let val = err.into_value();

	let Value::Object(ref obj) = val else {
		panic!("Expected object");
	};
	assert_eq!(obj.get("kind"), Some(&Value::String("NotAllowed".into())));
	assert_eq!(obj.get("message"), Some(&Value::String("Token expired".into())));
	// cause may be omitted or null when absent
	assert!(obj.get("cause").is_none_or(|v| *v == Value::None));
	let Some(Value::Object(details)) = obj.get("details") else {
		panic!("Expected details object");
	};
	assert_eq!(details.get("kind"), Some(&Value::String("Auth".into())));
	let Some(Value::Object(inner)) = details.get("details") else {
		panic!("Expected inner details");
	};
	assert_eq!(inner.get("kind"), Some(&Value::String("TokenExpired".into())));
	assert!(!inner.contains_key("details"), "Unit variant should not have inner details key");

	// Round-trip
	let parsed = Error::from_value(val).unwrap();
	assert!(parsed.is_not_allowed());
	assert_eq!(parsed.message(), "Token expired");
	let details = parsed.not_allowed_details().unwrap();
	assert!(matches!(details, NotAllowedError::Auth(AuthError::TokenExpired)));
}

#[test]
fn test_error_snapshot_not_allowed_auth_invalid_role() {
	// Wire format:
	// {
	//   "code": -32002,
	//   "message": "Bad role",
	//   "kind": "NotAllowed",
	//   "details": {
	//     "kind": "Auth",
	//     "details": { "kind": "InvalidRole", "details": { "name": "admin" } }
	//   }
	// }
	let err = Error::not_allowed(
		"Bad role".to_string(),
		AuthError::InvalidRole {
			name: "admin".into(),
		},
	);
	let val = err.into_value();

	let Value::Object(ref obj) = val else {
		panic!("Expected object");
	};
	let Some(Value::Object(details)) = obj.get("details") else {
		panic!("Expected details");
	};
	assert_eq!(details.get("kind"), Some(&Value::String("Auth".into())));
	let Some(Value::Object(auth_details)) = details.get("details") else {
		panic!("Expected auth details");
	};
	assert_eq!(auth_details.get("kind"), Some(&Value::String("InvalidRole".into())));
	let Some(Value::Object(role_details)) = auth_details.get("details") else {
		panic!("Expected role details");
	};
	assert_eq!(role_details.get("name"), Some(&Value::String("admin".into())));

	// Round-trip
	let parsed = Error::from_value(val).unwrap();
	let details = parsed.not_allowed_details().unwrap();
	assert!(matches!(
		details,
		NotAllowedError::Auth(AuthError::InvalidRole { name }) if name == "admin"
	));
}

#[test]
fn test_error_snapshot_not_found_table() {
	// Wire format:
	// {
	//   "code": -32000,
	//   "message": "Table not found",
	//   "kind": "NotFound",
	//   "details": { "kind": "Table", "details": { "name": "users" } }
	// }
	let err = Error::not_found(
		"Table not found".to_string(),
		NotFoundError::Table {
			name: "users".into(),
		},
	);
	let val = err.into_value();

	let Value::Object(ref obj) = val else {
		panic!("Expected object");
	};
	let Some(Value::Object(details)) = obj.get("details") else {
		panic!("Expected details");
	};
	assert_eq!(details.get("kind"), Some(&Value::String("Table".into())));
	let Some(Value::Object(table_details)) = details.get("details") else {
		panic!("Expected table details");
	};
	assert_eq!(table_details.get("name"), Some(&Value::String("users".into())));

	// Round-trip
	let parsed = Error::from_value(val).unwrap();
	assert!(parsed.is_not_found());
	let details = parsed.not_found_details().unwrap();
	assert!(matches!(
		details,
		NotFoundError::Table { name } if name == "users"
	));
}

#[test]
fn test_error_snapshot_validation_parse() {
	// Wire format:
	// {
	//   "code": -32700,
	//   "message": "Parse error",
	//   "kind": "Validation",
	//   "details": { "kind": "Parse" }
	// }
	let err = Error::validation("Parse error".to_string(), ValidationError::Parse);
	let val = err.into_value();

	let Value::Object(ref obj) = val else {
		panic!();
	};
	assert_eq!(obj.get("kind"), Some(&Value::String("Validation".into())));
	let Some(Value::Object(details)) = obj.get("details") else {
		panic!("Expected details");
	};
	assert_eq!(details.get("kind"), Some(&Value::String("Parse".into())));
	assert!(!details.contains_key("details"), "Unit variant should not have inner details key");

	// Round-trip
	let parsed = Error::from_value(val).unwrap();
	assert_eq!(parsed.validation_details(), Some(&ValidationError::Parse));
}

#[test]
fn test_error_snapshot_query_timed_out() {
	// Wire format:
	// {
	//   "code": -32004,
	//   "message": "Timed out",
	//   "kind": "Query",
	//   "details": { "kind": "TimedOut", "details": { "duration": { "secs": 5, "nanos": 0 } } }
	// }
	use std::time::Duration;
	let err = Error::query(
		"Timed out".to_string(),
		QueryError::TimedOut {
			duration: Duration::from_secs(5),
		},
	);
	let val = err.into_value();

	let Value::Object(ref obj) = val else {
		panic!("Expected object");
	};
	assert_eq!(obj.get("kind"), Some(&Value::String("Query".into())));
	let Some(Value::Object(details)) = obj.get("details") else {
		panic!("Expected details");
	};
	assert_eq!(details.get("kind"), Some(&Value::String("TimedOut".into())));
	assert!(details.contains_key("details"), "Struct variant should have details");

	// Round-trip
	let parsed = Error::from_value(val).unwrap();
	assert!(parsed.is_query());
	let details = parsed.query_details().unwrap();
	assert!(matches!(
		details,
		QueryError::TimedOut { duration } if *duration == Duration::from_secs(5)
	));
}

#[test]
fn test_error_snapshot_already_exists_record() {
	// Wire format:
	// {
	//   "code": -32000,
	//   "message": "Record exists",
	//   "kind": "AlreadyExists",
	//   "details": { "kind": "Record", "details": { "id": "users:123" } }
	// }
	let err = Error::already_exists(
		"Record exists".to_string(),
		AlreadyExistsError::Record {
			id: "users:123".into(),
		},
	);
	let val = err.into_value();

	let Value::Object(ref obj) = val else {
		panic!("Expected object");
	};
	let Some(Value::Object(details)) = obj.get("details") else {
		panic!("Expected details");
	};
	assert_eq!(details.get("kind"), Some(&Value::String("Record".into())));
	let Some(Value::Object(record_details)) = details.get("details") else {
		panic!("Expected record details");
	};
	assert_eq!(record_details.get("id"), Some(&Value::String("users:123".into())));

	// Round-trip
	let parsed = Error::from_value(val).unwrap();
	assert!(parsed.is_already_exists());
	let details = parsed.already_exists_details().unwrap();
	assert!(matches!(
		details,
		AlreadyExistsError::Record { id } if id == "users:123"
	));
}

#[test]
fn test_error_snapshot_not_allowed_method() {
	// Wire format:
	// {
	//   "code": -32602,
	//   "message": "Method blocked",
	//   "kind": "NotAllowed",
	//   "details": { "kind": "Method", "details": { "name": "begin" } }
	// }
	let err = Error::not_allowed(
		"Method blocked".to_string(),
		NotAllowedError::Method {
			name: "begin".into(),
		},
	);
	let val = err.into_value();

	let Value::Object(ref obj) = val else {
		panic!("Expected object");
	};
	let Some(Value::Object(details)) = obj.get("details") else {
		panic!("Expected details");
	};
	assert_eq!(details.get("kind"), Some(&Value::String("Method".into())));
	let Some(Value::Object(method_details)) = details.get("details") else {
		panic!("Expected method details");
	};
	assert_eq!(method_details.get("name"), Some(&Value::String("begin".into())));

	// Round-trip
	let parsed = Error::from_value(val).unwrap();
	let details = parsed.not_allowed_details().unwrap();
	assert!(matches!(
		details,
		NotAllowedError::Method { name } if name == "begin"
	));
}

#[test]
fn test_error_snapshot_internal_no_details() {
	// Wire format:
	// {
	//   "code": -32000,
	//   "message": "Unexpected",
	//   "kind": "Internal"
	// }
	let err = Error::internal("Unexpected".to_string());
	let val = err.into_value();

	let Value::Object(ref obj) = val else {
		panic!("Expected object");
	};
	assert_eq!(obj.get("kind"), Some(&Value::String("Internal".into())));
	assert_eq!(obj.get("message"), Some(&Value::String("Unexpected".into())));
	assert!(!obj.contains_key("details"), "No details should be present");
	// cause may be omitted or null when absent
	assert!(obj.get("cause").is_none_or(|v| *v == Value::None));

	// Round-trip
	let parsed = Error::from_value(val).unwrap();
	assert!(parsed.is_internal());
	assert_eq!(parsed.message(), "Unexpected");
	assert!(matches!(parsed.details(), ErrorDetails::Internal));
}

#[test]
fn test_error_snapshot_thrown_no_details() {
	// Wire format:
	// {
	//   "code": -32006,
	//   "message": "custom error",
	//   "kind": "Thrown"
	// }
	let err = Error::thrown("custom error".to_string());
	let val = err.into_value();

	let Value::Object(ref obj) = val else {
		panic!();
	};
	assert_eq!(obj.get("kind"), Some(&Value::String("Thrown".into())));
	assert_eq!(obj.get("message"), Some(&Value::String("custom error".into())));
	assert!(!obj.contains_key("details"));
	// cause may be omitted or null when absent
	assert!(obj.get("cause").is_none_or(|v| *v == Value::None));

	// Round-trip
	let parsed = Error::from_value(val).unwrap();
	assert!(parsed.is_thrown());
	assert_eq!(parsed.message(), "custom error");
	assert!(matches!(parsed.details(), ErrorDetails::Thrown));
}

#[test]
fn test_error_snapshot_not_allowed_scripting_unit() {
	// Wire format:
	// {
	//   "code": -32602,
	//   "message": "Scripting not allowed",
	//   "kind": "NotAllowed",
	//   "details": { "kind": "Scripting" }
	// }
	let err = Error::not_allowed("Scripting not allowed".to_string(), NotAllowedError::Scripting);
	let val = err.into_value();

	let Value::Object(ref obj) = val else {
		panic!();
	};
	assert_eq!(obj.get("kind"), Some(&Value::String("NotAllowed".into())));
	let Some(Value::Object(details)) = obj.get("details") else {
		panic!("Expected details");
	};
	assert_eq!(details.get("kind"), Some(&Value::String("Scripting".into())));
	assert!(!details.contains_key("details"), "Unit variant should not have inner details");

	// Round-trip
	let parsed = Error::from_value(val).unwrap();
	let details = parsed.not_allowed_details().unwrap();
	assert_eq!(details, &NotAllowedError::Scripting);
}

// -----------------------------------------------------------------------------
// Comprehensive error serialization + deserialization tests
// Each test documents the exact JSON wire format in comments.
// -----------------------------------------------------------------------------

#[test]
fn test_error_wire_validation_parse() {
	// Wire format:
	// {
	//   "code": -32700,
	//   "message": "Failed to parse query",
	//   "kind": "Validation",
	//   "details": { "kind": "Parse" }
	// }
	let err = Error::validation("Failed to parse query".into(), ValidationError::Parse);
	let val = err.into_value();

	let Value::Object(ref obj) = val else {
		panic!("Expected object");
	};
	assert_eq!(obj.get("code"), Some(&Value::Number(Number::Int(-32700))));
	assert_eq!(obj.get("message"), Some(&Value::String("Failed to parse query".into())));
	assert_eq!(obj.get("kind"), Some(&Value::String("Validation".into())));
	let Some(Value::Object(details)) = obj.get("details") else {
		panic!("Expected details");
	};
	assert_eq!(details.get("kind"), Some(&Value::String("Parse".into())));
	assert!(!details.contains_key("details"), "Unit variant has no inner details");

	let parsed = Error::from_value(val).unwrap();
	assert!(parsed.is_validation());
	assert_eq!(parsed.validation_details(), Some(&ValidationError::Parse));
	assert_eq!(parsed.message(), "Failed to parse query");
}

#[test]
fn test_error_wire_validation_invalid_params() {
	// Wire format:
	// {
	//   "code": -32603,
	//   "message": "Invalid parameters",
	//   "kind": "Validation",
	//   "details": { "kind": "InvalidParams" }
	// }
	let err = Error::validation("Invalid parameters".into(), ValidationError::InvalidParams);
	let val = err.into_value();

	let Value::Object(ref obj) = val else {
		panic!();
	};
	assert_eq!(obj.get("code"), Some(&Value::Number(Number::Int(-32603))));
	assert_eq!(obj.get("kind"), Some(&Value::String("Validation".into())));

	let parsed = Error::from_value(val).unwrap();
	assert!(parsed.is_validation());
	assert_eq!(parsed.validation_details(), Some(&ValidationError::InvalidParams));
}

#[test]
fn test_error_wire_validation_invalid_parameter_with_name() {
	// Wire format:
	// {
	//   "code": -32600,
	//   "message": "Invalid parameter 'limit'",
	//   "kind": "Validation",
	//   "details": { "kind": "InvalidParameter", "details": { "name": "limit" } }
	// }
	let err = Error::validation(
		"Invalid parameter 'limit'".into(),
		ValidationError::InvalidParameter {
			name: "limit".into(),
		},
	);
	let val = err.into_value();

	let Value::Object(ref obj) = val else {
		panic!();
	};
	assert_eq!(obj.get("kind"), Some(&Value::String("Validation".into())));
	let Some(Value::Object(details)) = obj.get("details") else {
		panic!();
	};
	assert_eq!(details.get("kind"), Some(&Value::String("InvalidParameter".into())));
	let Some(Value::Object(inner)) = details.get("details") else {
		panic!();
	};
	assert_eq!(inner.get("name"), Some(&Value::String("limit".into())));

	let parsed = Error::from_value(val).unwrap();
	assert!(parsed.is_validation());
	assert_eq!(
		parsed.validation_details(),
		Some(&ValidationError::InvalidParameter {
			name: "limit".into()
		})
	);
}

#[test]
fn test_error_wire_validation_no_details() {
	// Wire format:
	// {
	//   "code": -32000,
	//   "message": "Something invalid",
	//   "kind": "Validation"
	// }
	let err = Error::validation("Something invalid".into(), None);
	let val = err.into_value();

	let Value::Object(ref obj) = val else {
		panic!();
	};
	assert_eq!(obj.get("kind"), Some(&Value::String("Validation".into())));
	assert!(!obj.contains_key("details"), "No details when None");

	let parsed = Error::from_value(val).unwrap();
	assert!(parsed.is_validation());
	assert_eq!(parsed.validation_details(), None);
}

#[test]
fn test_error_wire_not_allowed_auth_session_expired() {
	// Wire format:
	// {
	//   "code": -32000,
	//   "message": "Session has expired",
	//   "kind": "NotAllowed",
	//   "details": { "kind": "Auth", "details": { "kind": "SessionExpired" } }
	// }
	let err = Error::not_allowed("Session has expired".into(), AuthError::SessionExpired);
	let val = err.into_value();

	let Value::Object(ref obj) = val else {
		panic!();
	};
	assert_eq!(obj.get("kind"), Some(&Value::String("NotAllowed".into())));
	let Some(Value::Object(details)) = obj.get("details") else {
		panic!();
	};
	assert_eq!(details.get("kind"), Some(&Value::String("Auth".into())));
	let Some(Value::Object(auth)) = details.get("details") else {
		panic!();
	};
	assert_eq!(auth.get("kind"), Some(&Value::String("SessionExpired".into())));

	let parsed = Error::from_value(val).unwrap();
	assert!(parsed.is_not_allowed());
	assert!(matches!(
		parsed.not_allowed_details(),
		Some(NotAllowedError::Auth(AuthError::SessionExpired))
	));
}

#[test]
fn test_error_wire_not_allowed_auth_not_allowed_iam() {
	// Wire format:
	// {
	//   "code": -32002,
	//   "message": "Not enough permissions",
	//   "kind": "NotAllowed",
	//   "details": {
	//     "kind": "Auth",
	//     "details": {
	//       "kind": "NotAllowed",
	//       "details": { "actor": "user:john", "action": "edit", "resource": "table:secrets" }
	//     }
	//   }
	// }
	let err = Error::not_allowed(
		"Not enough permissions".into(),
		AuthError::NotAllowed {
			actor: "user:john".into(),
			action: "edit".into(),
			resource: "table:secrets".into(),
		},
	);
	let val = err.into_value();

	let Value::Object(ref obj) = val else {
		panic!();
	};
	assert_eq!(obj.get("kind"), Some(&Value::String("NotAllowed".into())));

	let parsed = Error::from_value(val).unwrap();
	assert!(parsed.is_not_allowed());
	match parsed.not_allowed_details() {
		Some(NotAllowedError::Auth(AuthError::NotAllowed {
			actor,
			action,
			resource,
		})) => {
			assert_eq!(actor, "user:john");
			assert_eq!(action, "edit");
			assert_eq!(resource, "table:secrets");
		}
		other => panic!("Expected Auth::NotAllowed, got {other:?}"),
	}
}

#[test]
fn test_error_wire_not_allowed_function() {
	// Wire format:
	// {
	//   "code": -32602,
	//   "message": "Function not allowed",
	//   "kind": "NotAllowed",
	//   "details": { "kind": "Function", "details": { "name": "fn::custom" } }
	// }
	let err = Error::not_allowed(
		"Function not allowed".into(),
		NotAllowedError::Function {
			name: "fn::custom".into(),
		},
	);
	let val = err.into_value();

	let parsed = Error::from_value(val).unwrap();
	assert!(parsed.is_not_allowed());
	match parsed.not_allowed_details() {
		Some(NotAllowedError::Function {
			name,
		}) => assert_eq!(name, "fn::custom"),
		other => panic!("Expected Function, got {other:?}"),
	}
}

#[test]
fn test_error_wire_not_allowed_target() {
	// Wire format:
	// {
	//   "code": -32602,
	//   "message": "Net target not allowed",
	//   "kind": "NotAllowed",
	//   "details": { "kind": "Target", "details": { "name": "example.com" } }
	// }
	let err = Error::not_allowed(
		"Net target not allowed".into(),
		NotAllowedError::Target {
			name: "example.com".into(),
		},
	);
	let val = err.into_value();

	let parsed = Error::from_value(val).unwrap();
	assert!(parsed.is_not_allowed());
	match parsed.not_allowed_details() {
		Some(NotAllowedError::Target {
			name,
		}) => assert_eq!(name, "example.com"),
		other => panic!("Expected Target, got {other:?}"),
	}
}

#[test]
fn test_error_wire_not_allowed_no_details() {
	// Wire format:
	// {
	//   "code": -32000,
	//   "message": "Not allowed",
	//   "kind": "NotAllowed"
	// }
	let err = Error::not_allowed("Not allowed".into(), None);
	let val = err.into_value();

	let Value::Object(ref obj) = val else {
		panic!();
	};
	assert!(!obj.contains_key("details"));

	let parsed = Error::from_value(val).unwrap();
	assert!(parsed.is_not_allowed());
	assert_eq!(parsed.not_allowed_details(), None);
}

#[test]
fn test_error_wire_not_found_record() {
	// Wire format:
	// {
	//   "code": -32000,
	//   "message": "Record not found",
	//   "kind": "NotFound",
	//   "details": { "kind": "Record", "details": { "id": "person:jane" } }
	// }
	let err = Error::not_found(
		"Record not found".into(),
		NotFoundError::Record {
			id: "person:jane".into(),
		},
	);
	let val = err.into_value();

	let parsed = Error::from_value(val).unwrap();
	assert!(parsed.is_not_found());
	match parsed.not_found_details() {
		Some(NotFoundError::Record {
			id,
		}) => assert_eq!(id, "person:jane"),
		other => panic!("Expected Record, got {other:?}"),
	}
}

#[test]
fn test_error_wire_not_found_namespace() {
	// Wire format:
	// {
	//   "code": -32000,
	//   "message": "Namespace not found",
	//   "kind": "NotFound",
	//   "details": { "kind": "Namespace", "details": { "name": "test_ns" } }
	// }
	let err = Error::not_found(
		"Namespace not found".into(),
		NotFoundError::Namespace {
			name: "test_ns".into(),
		},
	);
	let val = err.into_value();

	let parsed = Error::from_value(val).unwrap();
	assert!(parsed.is_not_found());
	match parsed.not_found_details() {
		Some(NotFoundError::Namespace {
			name,
		}) => assert_eq!(name, "test_ns"),
		other => panic!("Expected Namespace, got {other:?}"),
	}
}

#[test]
fn test_error_wire_not_found_database() {
	// Wire format:
	// {
	//   "code": -32000,
	//   "message": "Database not found",
	//   "kind": "NotFound",
	//   "details": { "kind": "Database", "details": { "name": "test_db" } }
	// }
	let err = Error::not_found(
		"Database not found".into(),
		NotFoundError::Database {
			name: "test_db".into(),
		},
	);
	let val = err.into_value();

	let parsed = Error::from_value(val).unwrap();
	assert!(parsed.is_not_found());
	match parsed.not_found_details() {
		Some(NotFoundError::Database {
			name,
		}) => assert_eq!(name, "test_db"),
		other => panic!("Expected Database, got {other:?}"),
	}
}

#[test]
fn test_error_wire_not_found_method() {
	// Wire format:
	// {
	//   "code": -32601,
	//   "message": "Method not found",
	//   "kind": "NotFound",
	//   "details": { "kind": "Method", "details": { "name": "unknown_method" } }
	// }
	let err = Error::not_found(
		"Method not found".into(),
		NotFoundError::Method {
			name: "unknown_method".into(),
		},
	);
	let val = err.into_value();

	let Value::Object(ref obj) = val else {
		panic!();
	};
	assert_eq!(obj.get("code"), Some(&Value::Number(Number::Int(-32601))));

	let parsed = Error::from_value(val).unwrap();
	assert!(parsed.is_not_found());
	match parsed.not_found_details() {
		Some(NotFoundError::Method {
			name,
		}) => assert_eq!(name, "unknown_method"),
		other => panic!("Expected Method, got {other:?}"),
	}
}

#[test]
fn test_error_wire_not_found_transaction() {
	// Wire format:
	// {
	//   "code": -32000,
	//   "message": "Transaction not found",
	//   "kind": "NotFound",
	//   "details": { "kind": "Transaction" }
	// }
	let err = Error::not_found("Transaction not found".into(), NotFoundError::Transaction);
	let val = err.into_value();

	let Value::Object(ref obj) = val else {
		panic!();
	};
	let Some(Value::Object(details)) = obj.get("details") else {
		panic!();
	};
	assert_eq!(details.get("kind"), Some(&Value::String("Transaction".into())));
	assert!(!details.contains_key("details"), "Unit variant has no inner details");

	let parsed = Error::from_value(val).unwrap();
	assert!(parsed.is_not_found());
	assert_eq!(parsed.not_found_details(), Some(&NotFoundError::Transaction));
}

#[test]
fn test_error_wire_not_found_session() {
	// Wire format:
	// {
	//   "code": -32000,
	//   "message": "Session not found",
	//   "kind": "NotFound",
	//   "details": { "kind": "Session", "details": { "id": "abc-123" } }
	// }
	let err = Error::not_found(
		"Session not found".into(),
		NotFoundError::Session {
			id: Some("abc-123".into()),
		},
	);
	let val = err.into_value();

	let parsed = Error::from_value(val).unwrap();
	assert!(parsed.is_not_found());
	match parsed.not_found_details() {
		Some(NotFoundError::Session {
			id,
		}) => assert_eq!(id, &Some("abc-123".to_string())),
		other => panic!("Expected Session, got {other:?}"),
	}
}

#[test]
fn test_error_wire_query_cancelled() {
	// Wire format:
	// {
	//   "code": -32005,
	//   "message": "Query was cancelled",
	//   "kind": "Query",
	//   "details": { "kind": "Cancelled" }
	// }
	let err = Error::query("Query was cancelled".into(), QueryError::Cancelled);
	let val = err.into_value();

	let Value::Object(ref obj) = val else {
		panic!();
	};
	assert_eq!(obj.get("code"), Some(&Value::Number(Number::Int(-32005))));

	let parsed = Error::from_value(val).unwrap();
	assert!(parsed.is_query());
	assert_eq!(parsed.query_details(), Some(&QueryError::Cancelled));
}

#[test]
fn test_error_wire_query_transaction_conflict() {
	// Wire format:
	// {
	//   "code": -32009,
	//   "message": "Transaction conflict",
	//   "kind": "Query",
	//   "details": { "kind": "TransactionConflict" }
	// }
	let err = Error::query("Transaction conflict".into(), QueryError::TransactionConflict);
	let val = err.into_value();

	let Value::Object(ref obj) = val else {
		panic!();
	};
	assert_eq!(obj.get("code"), Some(&Value::Number(Number::Int(-32009))));

	let parsed = Error::from_value(val).unwrap();
	assert!(parsed.is_query());
	assert_eq!(parsed.query_details(), Some(&QueryError::TransactionConflict));
}

#[test]
fn test_error_wire_query_not_executed() {
	// Wire format:
	// {
	//   "code": -32003,
	//   "message": "Query not executed",
	//   "kind": "Query",
	//   "details": { "kind": "NotExecuted" }
	// }
	let err = Error::query("Query not executed".into(), QueryError::NotExecuted);
	let val = err.into_value();

	let parsed = Error::from_value(val).unwrap();
	assert!(parsed.is_query());
	assert_eq!(parsed.query_details(), Some(&QueryError::NotExecuted));
}

#[test]
fn test_error_wire_query_timed_out() {
	// Wire format:
	// {
	//   "code": -32004,
	//   "message": "Query timed out",
	//   "kind": "Query",
	//   "details": { "kind": "TimedOut", "details": { "duration": { "secs": 30, "nanos": 0 } } }
	// }
	use std::time::Duration;
	let err = Error::query(
		"Query timed out".into(),
		QueryError::TimedOut {
			duration: Duration::from_secs(30),
		},
	);
	let val = err.into_value();

	let parsed = Error::from_value(val).unwrap();
	assert!(parsed.is_query());
	match parsed.query_details() {
		Some(QueryError::TimedOut {
			duration,
		}) => assert_eq!(*duration, Duration::from_secs(30)),
		other => panic!("Expected TimedOut, got {other:?}"),
	}
}

#[test]
fn test_error_wire_already_exists_table() {
	// Wire format:
	// {
	//   "code": -32000,
	//   "message": "Table already exists",
	//   "kind": "AlreadyExists",
	//   "details": { "kind": "Table", "details": { "name": "users" } }
	// }
	let err = Error::already_exists(
		"Table already exists".into(),
		AlreadyExistsError::Table {
			name: "users".into(),
		},
	);
	let val = err.into_value();

	let parsed = Error::from_value(val).unwrap();
	assert!(parsed.is_already_exists());
	match parsed.already_exists_details() {
		Some(AlreadyExistsError::Table {
			name,
		}) => assert_eq!(name, "users"),
		other => panic!("Expected Table, got {other:?}"),
	}
}

#[test]
fn test_error_wire_already_exists_namespace() {
	// Wire format:
	// {
	//   "code": -32000,
	//   "message": "Namespace already exists",
	//   "kind": "AlreadyExists",
	//   "details": { "kind": "Namespace", "details": { "name": "prod" } }
	// }
	let err = Error::already_exists(
		"Namespace already exists".into(),
		AlreadyExistsError::Namespace {
			name: "prod".into(),
		},
	);
	let val = err.into_value();

	let parsed = Error::from_value(val).unwrap();
	assert!(parsed.is_already_exists());
	match parsed.already_exists_details() {
		Some(AlreadyExistsError::Namespace {
			name,
		}) => assert_eq!(name, "prod"),
		other => panic!("Expected Namespace, got {other:?}"),
	}
}

#[test]
fn test_error_wire_configuration_live_query() {
	// Wire format:
	// {
	//   "code": -32604,
	//   "message": "Live queries not supported",
	//   "kind": "Configuration",
	//   "details": { "kind": "LiveQueryNotSupported" }
	// }
	let err = Error::configuration(
		"Live queries not supported".into(),
		ConfigurationError::LiveQueryNotSupported,
	);
	let val = err.into_value();

	let Value::Object(ref obj) = val else {
		panic!();
	};
	assert_eq!(obj.get("code"), Some(&Value::Number(Number::Int(-32604))));

	let parsed = Error::from_value(val).unwrap();
	assert!(parsed.is_configuration());
	assert_eq!(parsed.configuration_details(), Some(&ConfigurationError::LiveQueryNotSupported));
}

#[test]
fn test_error_wire_configuration_bad_graphql() {
	// Wire format:
	// {
	//   "code": -32606,
	//   "message": "Bad GraphQL config",
	//   "kind": "Configuration",
	//   "details": { "kind": "BadGraphqlConfig" }
	// }
	let err =
		Error::configuration("Bad GraphQL config".into(), ConfigurationError::BadGraphqlConfig);
	let val = err.into_value();

	let parsed = Error::from_value(val).unwrap();
	assert!(parsed.is_configuration());
	assert_eq!(parsed.configuration_details(), Some(&ConfigurationError::BadGraphqlConfig));
}

#[test]
fn test_error_wire_serialization_error() {
	// Wire format:
	// {
	//   "code": -32007,
	//   "message": "Failed to serialize",
	//   "kind": "Serialization",
	//   "details": { "kind": "Serialization" }
	// }
	let err = Error::serialization("Failed to serialize".into(), SerializationError::Serialization);
	let val = err.into_value();

	let parsed = Error::from_value(val).unwrap();
	assert!(parsed.is_serialization());
	assert_eq!(parsed.serialization_details(), Some(&SerializationError::Serialization));
}

#[test]
fn test_error_wire_deserialization_error() {
	// Wire format:
	// {
	//   "code": -32008,
	//   "message": "Failed to deserialize",
	//   "kind": "Serialization",
	//   "details": { "kind": "Deserialization" }
	// }
	let err =
		Error::serialization("Failed to deserialize".into(), SerializationError::Deserialization);
	let val = err.into_value();

	let Value::Object(ref obj) = val else {
		panic!();
	};
	assert_eq!(obj.get("code"), Some(&Value::Number(Number::Int(-32008))));

	let parsed = Error::from_value(val).unwrap();
	assert!(parsed.is_serialization());
	assert_eq!(parsed.serialization_details(), Some(&SerializationError::Deserialization));
}

#[test]
fn test_error_wire_connection_uninitialised() {
	// Wire format:
	// {
	//   "code": -32001,
	//   "message": "Connection not initialised",
	//   "kind": "Connection",
	//   "details": { "kind": "Uninitialised" }
	// }
	let err =
		Error::connection("Connection not initialised".into(), ConnectionError::Uninitialised);
	let val = err.into_value();

	let Value::Object(ref obj) = val else {
		panic!();
	};
	assert_eq!(obj.get("code"), Some(&Value::Number(Number::Int(-32001))));

	let parsed = Error::from_value(val).unwrap();
	assert!(parsed.is_connection());
	assert_eq!(parsed.connection_details(), Some(&ConnectionError::Uninitialised));
}

#[test]
fn test_error_wire_connection_already_connected() {
	// Wire format:
	// {
	//   "code": -32001,
	//   "message": "Already connected",
	//   "kind": "Connection",
	//   "details": { "kind": "AlreadyConnected" }
	// }
	let err = Error::connection("Already connected".into(), ConnectionError::AlreadyConnected);
	let val = err.into_value();

	let parsed = Error::from_value(val).unwrap();
	assert!(parsed.is_connection());
	assert_eq!(parsed.connection_details(), Some(&ConnectionError::AlreadyConnected));
}

#[test]
fn test_error_wire_thrown() {
	// Wire format:
	// {
	//   "code": -32006,
	//   "message": "An error occurred: user validation failed",
	//   "kind": "Thrown"
	// }
	let err = Error::thrown("An error occurred: user validation failed".into());
	let val = err.into_value();

	let Value::Object(ref obj) = val else {
		panic!();
	};
	assert_eq!(obj.get("code"), Some(&Value::Number(Number::Int(-32006))));
	assert_eq!(obj.get("kind"), Some(&Value::String("Thrown".into())));
	assert!(!obj.contains_key("details"));

	let parsed = Error::from_value(val).unwrap();
	assert!(parsed.is_thrown());
	assert_eq!(parsed.message(), "An error occurred: user validation failed");
}

#[test]
fn test_error_wire_internal() {
	// Wire format:
	// {
	//   "code": -32000,
	//   "message": "An unexpected error occurred",
	//   "kind": "Internal"
	// }
	let err = Error::internal("An unexpected error occurred".into());
	let val = err.into_value();

	let Value::Object(ref obj) = val else {
		panic!();
	};
	assert_eq!(obj.get("code"), Some(&Value::Number(Number::Int(-32000))));
	assert_eq!(obj.get("kind"), Some(&Value::String("Internal".into())));
	assert!(!obj.contains_key("details"));

	let parsed = Error::from_value(val).unwrap();
	assert!(parsed.is_internal());
	assert_eq!(parsed.message(), "An unexpected error occurred");
}

// -----------------------------------------------------------------------------
// Forward/backward compatibility
// -----------------------------------------------------------------------------

#[test]
fn test_error_wire_unknown_kind_falls_back_to_internal() {
	// Simulates a future server sending a kind the client doesn't know about.
	// Wire format:
	// {
	//   "kind": "RateLimit",
	//   "message": "Too many requests"
	// }
	let mut obj = Object::new();
	obj.insert("kind", Value::String("RateLimit".into()));
	obj.insert("message", Value::String("Too many requests".into()));
	let val = Value::Object(obj);

	let parsed = Error::from_value(val).unwrap();
	assert!(parsed.is_internal()); // Unknown kinds fall back to Internal
	assert_eq!(parsed.message(), "Too many requests");
}

#[test]
fn test_error_wire_missing_kind_defaults_to_internal() {
	// Old server format without "kind" field.
	// Wire format:
	// {
	//   "code": -32000,
	//   "message": "Legacy error"
	// }
	let mut obj = Object::new();
	obj.insert("code", Value::Number(Number::Int(-32000)));
	obj.insert("message", Value::String("Legacy error".into()));
	let val = Value::Object(obj);

	let parsed = Error::from_value(val).unwrap();
	assert!(parsed.is_internal());
	assert_eq!(parsed.message(), "Legacy error");
}

#[test]
fn test_error_wire_missing_code_defaults_to_internal_code() {
	// Wire format without "code" field — defaults to -32000.
	// {
	//   "kind": "Thrown",
	//   "message": "Custom error"
	// }
	let mut obj = Object::new();
	obj.insert("kind", Value::String("Thrown".into()));
	obj.insert("message", Value::String("Custom error".into()));
	let val = Value::Object(obj);

	let parsed = Error::from_value(val).unwrap();
	assert!(parsed.is_thrown());
	assert_eq!(parsed.message(), "Custom error");
}

#[test]
fn test_error_wire_details_with_unknown_inner_kind() {
	// Details contain an unknown inner variant — the ErrorDetails manual
	// SurrealValue impl handles this by falling back to Internal when the
	// detail variant's kind doesn't match any known variant for that ErrorKind.
	// Wire format:
	// {
	//   "kind": "NotFound",
	//   "message": "Not found",
	//   "details": { "kind": "FutureResource", "details": { "id": "xyz" } }
	// }
	let err = Error::from_parts(
		"Not found".into(),
		Some("NotFound"),
		Some({
			let mut details_obj = Object::new();
			details_obj.insert("kind", Value::String("FutureResource".into()));
			let mut inner = Object::new();
			inner.insert("id", Value::String("xyz".into()));
			details_obj.insert("details", Value::Object(inner));
			Value::Object(details_obj)
		}),
	);
	// from_parts gracefully falls back when details can't be parsed
	assert!(err.is_not_found());
	assert_eq!(err.not_found_details(), None);
}

// -----------------------------------------------------------------------------
// Utility method coverage
// -----------------------------------------------------------------------------

#[test]
fn test_error_utility_methods() {
	let validation = Error::validation("test".into(), None);
	assert!(validation.is_validation());
	assert!(!validation.is_not_allowed());
	assert!(!validation.is_internal());
	assert_eq!(validation.kind_str(), "Validation");

	let not_allowed = Error::not_allowed("test".into(), None);
	assert!(not_allowed.is_not_allowed());
	assert!(!not_allowed.is_validation());
	assert_eq!(not_allowed.kind_str(), "NotAllowed");

	let not_found = Error::not_found("test".into(), None);
	assert!(not_found.is_not_found());
	assert_eq!(not_found.kind_str(), "NotFound");

	let already_exists = Error::already_exists("test".into(), None);
	assert!(already_exists.is_already_exists());
	assert_eq!(already_exists.kind_str(), "AlreadyExists");

	let query = Error::query("test".into(), None);
	assert!(query.is_query());
	assert_eq!(query.kind_str(), "Query");

	let config = Error::configuration("test".into(), None);
	assert!(config.is_configuration());
	assert_eq!(config.kind_str(), "Configuration");

	let serialization = Error::serialization("test".into(), None);
	assert!(serialization.is_serialization());
	assert_eq!(serialization.kind_str(), "Serialization");

	let connection = Error::connection("test".into(), None);
	assert!(connection.is_connection());
	assert_eq!(connection.kind_str(), "Connection");

	let thrown = Error::thrown("test".into());
	assert!(thrown.is_thrown());
	assert_eq!(thrown.kind_str(), "Thrown");

	let internal = Error::internal("test".into());
	assert!(internal.is_internal());
	assert_eq!(internal.kind_str(), "Internal");
}

#[test]
fn test_error_from_parts_with_details() {
	// Simulates how dbs/response.rs reconstructs errors from query results
	let mut details_obj = Object::new();
	details_obj.insert("kind", Value::String("Table".into()));
	let mut inner = Object::new();
	inner.insert("name", Value::String("users".into()));
	details_obj.insert("details", Value::Object(inner));

	let err = Error::from_parts(
		"Table not found".into(),
		Some("NotFound"),
		Some(Value::Object(details_obj)),
	);
	assert!(err.is_not_found());
	assert_eq!(err.message(), "Table not found");
	match err.not_found_details() {
		Some(NotFoundError::Table {
			name,
		}) => assert_eq!(name, "users"),
		other => panic!("Expected Table, got {other:?}"),
	}
}

#[test]
fn test_error_from_parts_without_details() {
	let err = Error::from_parts("Internal error".into(), Some("Internal"), None);
	assert!(err.is_internal());
	assert_eq!(err.message(), "Internal error");
}

#[test]
fn test_error_from_parts_unknown_kind() {
	let err = Error::from_parts("Unknown".into(), Some("FutureKind"), None);
	assert!(err.is_internal()); // Unknown falls back to Internal
}

#[test]
fn test_error_from_parts_no_kind() {
	let err = Error::from_parts("No kind".into(), None, None);
	assert!(err.is_internal()); // Missing kind defaults to Internal
}

// -----------------------------------------------------------------------------
// Error chaining (cause)
// -----------------------------------------------------------------------------

#[test]
fn test_error_cause_accessor() {
	let root = Error::internal("root cause".into());
	let top = Error::validation("validation failed".into(), None).with_cause(root);
	assert!(top.cause().is_some());
	let cause = top.cause().unwrap();
	assert_eq!(cause.message(), "root cause");
	assert!(cause.is_internal());
}

#[test]
fn test_error_cause_wire_roundtrip() {
	use surrealdb_types::SurrealValue;

	let root = Error::internal("root cause".into());
	let top = Error::validation("validation failed".into(), None).with_cause(root);
	let value = top.into_value();
	let parsed = Error::from_value(value).unwrap();
	assert_eq!(parsed.message(), "validation failed");
	let cause = parsed.cause().expect("cause should be present");
	assert_eq!(cause.message(), "root cause");
	assert!(cause.is_internal());
}

#[test]
fn test_error_cause_chain_three_levels() {
	use surrealdb_types::SurrealValue;

	let innermost = Error::not_found("record missing".into(), None);
	let middle = Error::query("query failed".into(), None).with_cause(innermost);
	let top = Error::internal("operation failed".into()).with_cause(middle);
	assert_eq!(top.message(), "operation failed");
	let c1 = top.cause().unwrap();
	assert_eq!(c1.message(), "query failed");
	let c2 = c1.cause().unwrap();
	assert_eq!(c2.message(), "record missing");
	assert!(c2.is_not_found());

	let value = top.clone().into_value();
	let parsed = Error::from_value(value).unwrap();
	assert_eq!(parsed.message(), "operation failed");
	assert_eq!(parsed.cause().unwrap().message(), "query failed");
	assert_eq!(parsed.cause().unwrap().cause().unwrap().message(), "record missing");
}

#[test]
fn test_error_without_cause_omitted_on_wire() {
	use surrealdb_types::SurrealValue;

	let err = Error::internal("no cause".into());
	let value = err.into_value();
	// cause key may be omitted when None (depends on Option serialization)
	let parsed = Error::from_value(value).unwrap();
	assert_eq!(parsed.message(), "no cause");
	assert!(parsed.cause().is_none());
}

#[test]
fn test_error_from_anyhow_does_not_leak_chain() {
	// SECURITY: anyhow source-chain messages can contain raw field/computed
	// values and other unredacted internals. `from_anyhow_with_chain` must
	// surface only the outermost message and must NOT attach inner sources
	// as a serialised cause that would reach clients.
	let root = anyhow::anyhow!("raw internal value: secret=hunter2");
	let middle = root.context("Failed to coerce computed field 'x'");
	let top = middle.context("Operation failed");

	let err = Error::from_anyhow_with_chain(top);
	assert_eq!(err.message(), "Operation failed");
	assert!(err.cause().is_none(), "anyhow source chain must not leak as cause");
}

#[test]
fn test_chain_trait_result() {
	let io_err = std::io::Error::new(std::io::ErrorKind::NotFound, "file missing");
	let result: Result<(), std::io::Error> = Err(io_err);
	let err = result.chain("Failed to load config").unwrap_err();
	assert!(err.is_context());
	assert_eq!(err.message(), "Failed to load config");
	let cause = err.cause().expect("chained error should have cause");
	assert!(cause.is_not_found());
}

#[test]
fn test_chain_trait_result_with_lazy_context() {
	let io_err = std::io::Error::new(std::io::ErrorKind::ConnectionRefused, "connection refused");
	let result: Result<(), std::io::Error> = Err(io_err);
	let err = result.chain_with(|| format!("connecting to host {}", "localhost:8080")).unwrap_err();
	assert!(err.is_context());
	assert_eq!(err.message(), "connecting to host localhost:8080");
	let cause = err.cause().expect("chained error should have cause");
	assert!(cause.is_connection());
}

#[test]
fn test_chain_trait_option() {
	let opt: Option<u32> = None;
	let err = opt.chain("missing user id").unwrap_err();
	assert!(err.is_context());
	assert_eq!(err.message(), "missing user id");
	assert!(err.cause().is_none());
}

#[test]
fn test_chain_trait_option_with_lazy_context() {
	let opt: Option<u32> = None;
	let err = opt.chain_with(|| format!("user {} not found", 42)).unwrap_err();
	assert!(err.is_context());
	assert_eq!(err.message(), "user 42 not found");
	assert!(err.cause().is_none());
}

#[test]
fn test_chain_trait_ok_passthrough() {
	let result: Result<u32, std::io::Error> = Ok(42);
	let val = result.chain("should not trigger").unwrap();
	assert_eq!(val, 42);
}

#[test]
fn test_chain_trait_some_passthrough() {
	let opt: Option<u32> = Some(42);
	let val = opt.chain("should not trigger").unwrap();
	assert_eq!(val, 42);
}

#[test]
fn test_error_query_none_round_trip() {
	use surrealdb_types::SurrealValue;

	let err = Error::query("The record access signup query failed".into(), None);
	assert!(err.is_query(), "before round-trip: expected Query, got {}", err.kind_str());
	let value = err.clone().into_value();
	let parsed = Error::from_value(value).unwrap();
	assert!(parsed.is_query(), "after round-trip: expected Query, got {}", parsed.kind_str());
	assert_eq!(parsed.message(), "The record access signup query failed");

	let encoded = surrealdb_types::encode(&err.into_value()).expect("encode should succeed");
	let decoded: surrealdb_types::Value =
		surrealdb_types::decode(&encoded).expect("decode should succeed");
	let parsed = Error::from_value(decoded).unwrap();
	assert!(
		parsed.is_query(),
		"after flatbuffers round-trip: expected Query, got {}",
		parsed.kind_str()
	);
}