noxu-db 3.2.0

Noxu DB - An embedded transactional database engine
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
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
//! Integration tests: open env → put/get/delete/cursor scan end-to-end.
//!
//! Verifies that the real B-tree backend (EnvironmentImpl → DatabaseImpl →
//! CursorImpl → Tree) is correctly wired through the noxu-db public API.

use noxu_db::{
    DatabaseConfig, DatabaseEntry, EnvironmentConfig, Get, OperationStatus,
};
use tempfile::TempDir;

fn open_env_and_db(dir: &TempDir) -> (noxu_db::Environment, noxu_db::Database) {
    let env_config = EnvironmentConfig::new(dir.path().to_path_buf())
        .with_allow_create(true)
        .with_transactional(true);
    let env = noxu_db::Environment::open(env_config).unwrap();
    let db_config = DatabaseConfig::new().with_allow_create(true);
    let db = env.open_database(None, "test", &db_config).unwrap();
    (env, db)
}

/// Basic put then get round-trip through the real tree.
#[test]
fn test_put_get_round_trip() {
    let dir = TempDir::new().unwrap();
    let (_env, db) = open_env_and_db(&dir);

    let key = DatabaseEntry::from_bytes(b"hello");
    let val = DatabaseEntry::from_bytes(b"world");

    assert_eq!(db.put(None, &key, &val).unwrap(), OperationStatus::Success);

    let mut out = DatabaseEntry::new();
    assert_eq!(db.get(None, &key, &mut out).unwrap(), OperationStatus::Success);
    assert_eq!(out.data(), b"world");
}

/// Put then delete: subsequent get returns NotFound.
#[test]
fn test_put_delete_get() {
    let dir = TempDir::new().unwrap();
    let (_env, db) = open_env_and_db(&dir);

    let key = DatabaseEntry::from_bytes(b"key");
    let val = DatabaseEntry::from_bytes(b"val");

    db.put(None, &key, &val).unwrap();
    assert_eq!(db.delete(None, &key).unwrap(), OperationStatus::Success);

    let mut out = DatabaseEntry::new();
    assert_eq!(
        db.get(None, &key, &mut out).unwrap(),
        OperationStatus::NotFound
    );
}

/// Last put wins (overwrite semantics).
#[test]
fn test_put_overwrite() {
    let dir = TempDir::new().unwrap();
    let (_env, db) = open_env_and_db(&dir);

    let key = DatabaseEntry::from_bytes(b"k");
    let v1 = DatabaseEntry::from_bytes(b"v1");
    let v2 = DatabaseEntry::from_bytes(b"v2");

    db.put(None, &key, &v1).unwrap();
    db.put(None, &key, &v2).unwrap();

    let mut out = DatabaseEntry::new();
    db.get(None, &key, &mut out).unwrap();
    assert_eq!(out.data(), b"v2");
}

/// put_no_overwrite returns KeyExists when key is already present.
#[test]
fn test_put_no_overwrite() {
    let dir = TempDir::new().unwrap();
    let (_env, db) = open_env_and_db(&dir);

    let key = DatabaseEntry::from_bytes(b"k");
    let v1 = DatabaseEntry::from_bytes(b"v1");
    let v2 = DatabaseEntry::from_bytes(b"v2");

    db.put(None, &key, &v1).unwrap();
    let status = db.put_no_overwrite(None, &key, &v2).unwrap();
    assert_eq!(status, OperationStatus::KeyExists);

    // Original value unchanged
    let mut out = DatabaseEntry::new();
    db.get(None, &key, &mut out).unwrap();
    assert_eq!(out.data(), b"v1");
}

/// Cursor scan: First + Next iterates all records in sorted order.
#[test]
fn test_cursor_scan_sorted() {
    let dir = TempDir::new().unwrap();
    let (_env, db) = open_env_and_db(&dir);

    // Insert out of order
    for (k, v) in [(b"c", b"3"), (b"a", b"1"), (b"b", b"2")] {
        db.put(
            None,
            &DatabaseEntry::from_bytes(k),
            &DatabaseEntry::from_bytes(v),
        )
        .unwrap();
    }

    let mut cursor = db.open_cursor(None, None).unwrap();
    let mut dummy_key = DatabaseEntry::new();
    let mut data = DatabaseEntry::new();

    // Collect values in iteration order
    let mut values: Vec<Vec<u8>> = Vec::new();
    let mut status =
        cursor.get(&mut dummy_key, &mut data, Get::First, None).unwrap();
    while status == OperationStatus::Success {
        values.push(data.data().to_vec());
        status =
            cursor.get(&mut dummy_key, &mut data, Get::Next, None).unwrap();
    }

    assert_eq!(values, vec![b"1", b"2", b"3"]);
    cursor.close().unwrap();
}

/// Cursor scan in reverse order: Last + Prev.
#[test]
fn test_cursor_scan_reverse() {
    let dir = TempDir::new().unwrap();
    let (_env, db) = open_env_and_db(&dir);

    for (k, v) in [(b"a", b"1"), (b"b", b"2"), (b"c", b"3")] {
        db.put(
            None,
            &DatabaseEntry::from_bytes(k),
            &DatabaseEntry::from_bytes(v),
        )
        .unwrap();
    }

    let mut cursor = db.open_cursor(None, None).unwrap();
    let mut dummy_key = DatabaseEntry::new();
    let mut data = DatabaseEntry::new();

    let mut values: Vec<Vec<u8>> = Vec::new();
    let mut status =
        cursor.get(&mut dummy_key, &mut data, Get::Last, None).unwrap();
    while status == OperationStatus::Success {
        values.push(data.data().to_vec());
        status =
            cursor.get(&mut dummy_key, &mut data, Get::Prev, None).unwrap();
    }

    assert_eq!(values, vec![b"3", b"2", b"1"]);
    cursor.close().unwrap();
}

/// Cursor Search positions at the exact key.
#[test]
fn test_cursor_search() {
    let dir = TempDir::new().unwrap();
    let (_env, db) = open_env_and_db(&dir);

    for (k, v) in [
        (b"apple".as_ref(), b"a".as_ref()),
        (b"banana".as_ref(), b"b".as_ref()),
        (b"cherry".as_ref(), b"c".as_ref()),
    ] {
        db.put(
            None,
            &DatabaseEntry::from_bytes(k),
            &DatabaseEntry::from_bytes(v),
        )
        .unwrap();
    }

    let mut cursor = db.open_cursor(None, None).unwrap();
    let mut key = DatabaseEntry::from_bytes(b"banana");
    let mut data = DatabaseEntry::new();

    let status = cursor.get(&mut key, &mut data, Get::Search, None).unwrap();
    assert_eq!(status, OperationStatus::Success);
    assert_eq!(data.data(), b"b");
    cursor.close().unwrap();
}

/// Cursor delete removes the record; subsequent search returns NotFound.
#[test]
fn test_cursor_delete() {
    let dir = TempDir::new().unwrap();
    let (_env, db) = open_env_and_db(&dir);

    let mut key = DatabaseEntry::from_bytes(b"k");
    let val = DatabaseEntry::from_bytes(b"v");
    db.put(None, &key, &val).unwrap();

    let mut cursor = db.open_cursor(None, None).unwrap();
    let mut data = DatabaseEntry::new();

    // Position on the record then delete via cursor
    cursor.get(&mut key, &mut data, Get::Search, None).unwrap();
    cursor.delete().unwrap();
    cursor.close().unwrap();

    // Verify gone via Database::get
    let mut out = DatabaseEntry::new();
    assert_eq!(
        db.get(None, &key, &mut out).unwrap(),
        OperationStatus::NotFound
    );
}

/// Database::count() returns the right number of records.
#[test]
fn test_count() {
    let dir = TempDir::new().unwrap();
    let (_env, db) = open_env_and_db(&dir);

    assert_eq!(db.count().unwrap(), 0);

    db.put(
        None,
        &DatabaseEntry::from_bytes(b"k1"),
        &DatabaseEntry::from_bytes(b"v1"),
    )
    .unwrap();
    assert_eq!(db.count().unwrap(), 1);

    db.put(
        None,
        &DatabaseEntry::from_bytes(b"k2"),
        &DatabaseEntry::from_bytes(b"v2"),
    )
    .unwrap();
    assert_eq!(db.count().unwrap(), 2);

    db.delete(None, &DatabaseEntry::from_bytes(b"k1")).unwrap();
    assert_eq!(db.count().unwrap(), 1);
}

/// Multiple databases within the same environment are independent.
#[test]
fn test_multiple_databases_isolated() {
    let dir = TempDir::new().unwrap();
    let env_config = EnvironmentConfig::new(dir.path().to_path_buf())
        .with_allow_create(true);
    let env = noxu_db::Environment::open(env_config).unwrap();
    let db_config = DatabaseConfig::new().with_allow_create(true);

    let db1 = env.open_database(None, "db1", &db_config).unwrap();
    let db2 = env.open_database(None, "db2", &db_config).unwrap();

    let key = DatabaseEntry::from_bytes(b"k");
    db1.put(None, &key, &DatabaseEntry::from_bytes(b"from-db1")).unwrap();
    db2.put(None, &key, &DatabaseEntry::from_bytes(b"from-db2")).unwrap();

    let mut out1 = DatabaseEntry::new();
    let mut out2 = DatabaseEntry::new();
    db1.get(None, &key, &mut out1).unwrap();
    db2.get(None, &key, &mut out2).unwrap();

    assert_eq!(out1.data(), b"from-db1");
    assert_eq!(out2.data(), b"from-db2");
}

/// get_database_names() reflects names registered via open_database.
#[test]
fn test_get_database_names() {
    let dir = TempDir::new().unwrap();
    let env_config = EnvironmentConfig::new(dir.path().to_path_buf())
        .with_allow_create(true);
    let env = noxu_db::Environment::open(env_config).unwrap();
    let db_config = DatabaseConfig::new().with_allow_create(true);

    let _db1 = env.open_database(None, "alpha", &db_config).unwrap();
    let _db2 = env.open_database(None, "beta", &db_config).unwrap();

    let names = env.get_database_names().unwrap();
    assert!(names.contains(&"alpha".to_string()));
    assert!(names.contains(&"beta".to_string()));
    assert_eq!(names.len(), 2);
}

// ─── DatabaseEntry correctness tests ────

/// DatabaseEntry::new() has no data; get_data() returns None and size is 0.
/// Mirrors the null-entry branch of testBasic().
#[test]
fn dbentry_new_is_null() {
    let entry = noxu_db::DatabaseEntry::new();
    assert_eq!(entry.get_data(), None);
    assert_eq!(entry.get_size(), 0);
}

/// from_bytes stores the data and exposes it at offset 0 with the correct size.
/// Mirrors the constructor-with-array branch of testBasic().
#[test]
fn dbentry_from_bytes_stores_data() {
    let data: Vec<u8> = vec![1u8; 10];
    let entry = noxu_db::DatabaseEntry::from_bytes(&data);
    assert_eq!(entry.get_size(), 10);
    assert_eq!(entry.get_data(), Some(data.as_slice()));
}

/// set_data() on an entry replaces content; get_data() reflects new bytes.
/// set_data with a different payload changes data and resets offset to 0.
/// Mirrors the setData() branch of testBasic().
#[test]
fn dbentry_set_data_replaces_content() {
    let mut entry = noxu_db::DatabaseEntry::from_bytes(b"original");
    assert_eq!(entry.get_data(), Some(b"original".as_ref()));

    entry.set_data(b"replaced");
    assert_eq!(entry.get_data(), Some(b"replaced".as_ref()));
    assert_eq!(entry.get_size(), 8);
    assert_eq!(entry.get_offset(), 0);
}

/// After set_data(null equivalent via clear()) the entry is empty.
/// Mirrors dbtA.setData(null) in testBasic().
#[test]
fn dbentry_clear_makes_null() {
    let mut entry = noxu_db::DatabaseEntry::from_bytes(b"data");
    entry.clear();
    assert_eq!(entry.get_data(), None);
    assert_eq!(entry.get_size(), 0);
}

/// Constructing with offset and size exposes only the sub-slice.
/// After calling set_data() the offset resets to 0 and size equals full length.
/// Mirrors the dbtOffset branch of testBasic().
#[test]
fn dbentry_offset_and_size() {
    let data: Vec<u8> = (0u8..10).collect();
    let mut entry = noxu_db::DatabaseEntry::from_bytes(&data);
    entry.set_offset(3);
    entry.set_size(4);
    // get_data() should return bytes [3..7]
    assert_eq!(entry.get_offset(), 3);
    assert_eq!(entry.get_size(), 4);
    assert_eq!(entry.get_data(), Some(&data[3..7]));

    // Calling set_data resets offset to 0 and size to full length.
    let new_data: Vec<u8> = vec![42u8; 6];
    entry.set_data(&new_data);
    assert_eq!(entry.get_offset(), 0);
    assert_eq!(entry.get_size(), 6);
}

/// Two entries with identical byte content compare equal; differing content
/// compares not-equal.  Mirrors testBasic() assertEquals/arrays.equals checks.
#[test]
fn dbentry_equality_based_on_content() {
    let a = noxu_db::DatabaseEntry::from_bytes(b"hello");
    let b = noxu_db::DatabaseEntry::from_bytes(b"hello");
    let c = noxu_db::DatabaseEntry::from_bytes(b"world");
    assert_eq!(a, b);
    assert_ne!(a, c);
}

/// get_data() on an entry with offset reads the correct sub-slice.
/// Mirrors the testOffset() assertions about foundKey/foundData offset=0, size=10.
#[test]
fn dbentry_get_data_respects_offset_and_size() {
    // Build a 30-byte array where byte[i] == i
    let raw: Vec<u8> = (0u8..30).collect();
    let mut entry = noxu_db::DatabaseEntry::from_bytes(&raw);
    entry.set_offset(10);
    entry.set_size(10);
    // Should return bytes 10..20
    let slice = entry.get_data().unwrap();
    assert_eq!(slice.len(), 10);
    for (i, &byte) in slice.iter().enumerate() {
        assert_eq!(byte, (i + 10) as u8);
    }
}

/// is_partial() / set_partial() round-trip.
/// Mirrors the partial flag checks in testPartial().
#[test]
fn dbentry_partial_flag_round_trip() {
    let mut entry = noxu_db::DatabaseEntry::new();
    assert!(!entry.is_partial());

    entry.set_partial(5, 10, true);
    assert!(entry.is_partial());
    assert_eq!(entry.get_partial_offset(), 5);
    assert_eq!(entry.get_partial_length(), 10);

    entry.set_partial(0, 0, false);
    assert!(!entry.is_partial());
}

// ─── Cursor correctness tests ──────────────────

/// Get::First returns the smallest key in the database.
/// Mirrors the getFirst() assertion in insertMultiDb().
#[test]
fn cursor_first_returns_smallest_key() {
    let dir = tempfile::TempDir::new().unwrap();
    let (_env, db) = open_env_and_db(&dir);

    // Insert out-of-order; keys sort lexicographically.
    for (k, v) in
        [(b"dog".as_ref(), b"3".as_ref()), (b"ant", b"1"), (b"bee", b"2")]
    {
        db.put(
            None,
            &noxu_db::DatabaseEntry::from_bytes(k),
            &noxu_db::DatabaseEntry::from_bytes(v),
        )
        .unwrap();
    }

    let mut cursor = db.open_cursor(None, None).unwrap();
    let mut key = noxu_db::DatabaseEntry::new();
    let mut data = noxu_db::DatabaseEntry::new();

    let status =
        cursor.get(&mut key, &mut data, noxu_db::Get::First, None).unwrap();
    assert_eq!(status, noxu_db::OperationStatus::Success);
    assert_eq!(key.data(), b"ant");
    assert_eq!(data.data(), b"1");
    cursor.close().unwrap();
}

/// Get::Last returns the largest key in the database.
/// Mirrors the getLast() assertion pattern from CursorTest.
#[test]
fn cursor_last_returns_largest_key() {
    let dir = tempfile::TempDir::new().unwrap();
    let (_env, db) = open_env_and_db(&dir);

    for (k, v) in
        [(b"dog".as_ref(), b"3".as_ref()), (b"ant", b"1"), (b"bee", b"2")]
    {
        db.put(
            None,
            &noxu_db::DatabaseEntry::from_bytes(k),
            &noxu_db::DatabaseEntry::from_bytes(v),
        )
        .unwrap();
    }

    let mut cursor = db.open_cursor(None, None).unwrap();
    let mut key = noxu_db::DatabaseEntry::new();
    let mut data = noxu_db::DatabaseEntry::new();

    let status =
        cursor.get(&mut key, &mut data, noxu_db::Get::Last, None).unwrap();
    assert_eq!(status, noxu_db::OperationStatus::Success);
    assert_eq!(key.data(), b"dog");
    assert_eq!(data.data(), b"3");
    cursor.close().unwrap();
}

/// Get::Next traverses all keys in ascending sorted order.
/// Mirrors the while(status == SUCCESS) getNext() loop in insertMultiDb().
#[test]
fn cursor_next_traverses_sorted_order() {
    let dir = tempfile::TempDir::new().unwrap();
    let (_env, db) = open_env_and_db(&dir);

    // Insert seven single-byte keys — same alphabet used in CursorTest.dataStrings.
    let pairs: &[(&[u8], &[u8])] = &[
        (b"A", b"1"),
        (b"B", b"2"),
        (b"C", b"3"),
        (b"F", b"4"),
        (b"G", b"5"),
        (b"H", b"6"),
        (b"I", b"7"),
    ];
    for (k, v) in pairs {
        db.put(
            None,
            &noxu_db::DatabaseEntry::from_bytes(k),
            &noxu_db::DatabaseEntry::from_bytes(v),
        )
        .unwrap();
    }

    let mut cursor = db.open_cursor(None, None).unwrap();
    let mut key = noxu_db::DatabaseEntry::new();
    let mut data = noxu_db::DatabaseEntry::new();

    let mut keys_seen: Vec<Vec<u8>> = Vec::new();
    let mut status =
        cursor.get(&mut key, &mut data, noxu_db::Get::First, None).unwrap();
    while status == noxu_db::OperationStatus::Success {
        keys_seen.push(key.data().to_vec());
        status =
            cursor.get(&mut key, &mut data, noxu_db::Get::Next, None).unwrap();
    }

    let expected: Vec<&[u8]> = vec![b"A", b"B", b"C", b"F", b"G", b"H", b"I"];
    assert_eq!(keys_seen, expected);
    cursor.close().unwrap();
}

/// Get::Prev traverses all keys in descending sorted order.
/// Mirrors the reverse-scan invariant implied by CursorTest.
#[test]
fn cursor_prev_traverses_reverse_sorted_order() {
    let dir = tempfile::TempDir::new().unwrap();
    let (_env, db) = open_env_and_db(&dir);

    let pairs: &[(&[u8], &[u8])] = &[(b"A", b"1"), (b"B", b"2"), (b"C", b"3")];
    for (k, v) in pairs {
        db.put(
            None,
            &noxu_db::DatabaseEntry::from_bytes(k),
            &noxu_db::DatabaseEntry::from_bytes(v),
        )
        .unwrap();
    }

    let mut cursor = db.open_cursor(None, None).unwrap();
    let mut key = noxu_db::DatabaseEntry::new();
    let mut data = noxu_db::DatabaseEntry::new();

    let mut keys_seen: Vec<Vec<u8>> = Vec::new();
    let mut status =
        cursor.get(&mut key, &mut data, noxu_db::Get::Last, None).unwrap();
    while status == noxu_db::OperationStatus::Success {
        keys_seen.push(key.data().to_vec());
        status =
            cursor.get(&mut key, &mut data, noxu_db::Get::Prev, None).unwrap();
    }

    let expected: Vec<&[u8]> = vec![b"C", b"B", b"A"];
    assert_eq!(keys_seen, expected);
    cursor.close().unwrap();
}

/// Get::Search finds an exact key and returns its data; cursor is positioned.
/// Mirrors cursor.getSearchKey() == SUCCESS assertions in CursorTest.
#[test]
fn cursor_search_finds_exact_key() {
    let dir = tempfile::TempDir::new().unwrap();
    let (_env, db) = open_env_and_db(&dir);

    for (k, v) in
        [(b"A".as_ref(), b"v1".as_ref()), (b"F", b"v2"), (b"G", b"v3")]
    {
        db.put(
            None,
            &noxu_db::DatabaseEntry::from_bytes(k),
            &noxu_db::DatabaseEntry::from_bytes(v),
        )
        .unwrap();
    }

    let mut cursor = db.open_cursor(None, None).unwrap();
    let mut key = noxu_db::DatabaseEntry::from_bytes(b"F");
    let mut data = noxu_db::DatabaseEntry::new();

    let status =
        cursor.get(&mut key, &mut data, noxu_db::Get::Search, None).unwrap();
    assert_eq!(status, noxu_db::OperationStatus::Success);
    assert_eq!(data.data(), b"v2");
    // Key written back after search must equal the searched key.
    assert_eq!(key.data(), b"F");
    cursor.close().unwrap();
}

/// Get::Search for a missing key returns NotFound.
/// Mirrors OperationStatus.NOTFOUND assertions in CursorTest.
#[test]
fn cursor_search_missing_key_returns_not_found() {
    let dir = tempfile::TempDir::new().unwrap();
    let (_env, db) = open_env_and_db(&dir);

    db.put(
        None,
        &noxu_db::DatabaseEntry::from_bytes(b"A"),
        &noxu_db::DatabaseEntry::from_bytes(b"v"),
    )
    .unwrap();

    let mut cursor = db.open_cursor(None, None).unwrap();
    let mut key = noxu_db::DatabaseEntry::from_bytes(b"Z");
    let mut data = noxu_db::DatabaseEntry::new();

    let status =
        cursor.get(&mut key, &mut data, noxu_db::Get::Search, None).unwrap();
    assert_eq!(status, noxu_db::OperationStatus::NotFound);
    cursor.close().unwrap();
}

/// Get::SearchGte finds the first key >= the search key.
/// Mirrors cursor.getSearchKeyRange() from CursorTest.testDbInternalSearch()
/// (Search.GTE semantics) and insertionDuringGetNextBin test.
#[test]
fn cursor_search_gte_finds_first_ge_key() {
    let dir = tempfile::TempDir::new().unwrap();
    let (_env, db) = open_env_and_db(&dir);

    // Insert keys 1, 3, 5 (as single bytes).
    for k in [1u8, 3, 5] {
        db.put(
            None,
            &noxu_db::DatabaseEntry::from_bytes(&[k]),
            &noxu_db::DatabaseEntry::from_bytes(&[k]),
        )
        .unwrap();
    }

    let mut cursor = db.open_cursor(None, None).unwrap();

    // SearchGte(0) → first key >= 0 is 1.
    let mut key = noxu_db::DatabaseEntry::from_bytes(&[0u8]);
    let mut data = noxu_db::DatabaseEntry::new();
    let status =
        cursor.get(&mut key, &mut data, noxu_db::Get::SearchGte, None).unwrap();
    assert_eq!(status, noxu_db::OperationStatus::Success);
    assert_eq!(key.data(), &[1u8]);

    // SearchGte(3) → exact match, returns 3.
    let mut key = noxu_db::DatabaseEntry::from_bytes(&[3u8]);
    let status =
        cursor.get(&mut key, &mut data, noxu_db::Get::SearchGte, None).unwrap();
    assert_eq!(status, noxu_db::OperationStatus::Success);
    assert_eq!(key.data(), &[3u8]);

    // SearchGte(4) → first key >= 4 is 5.
    let mut key = noxu_db::DatabaseEntry::from_bytes(&[4u8]);
    let status =
        cursor.get(&mut key, &mut data, noxu_db::Get::SearchGte, None).unwrap();
    assert_eq!(status, noxu_db::OperationStatus::Success);
    assert_eq!(key.data(), &[5u8]);

    // SearchGte(6) → no key >= 6, returns NotFound.
    let mut key = noxu_db::DatabaseEntry::from_bytes(&[6u8]);
    let status =
        cursor.get(&mut key, &mut data, noxu_db::Get::SearchGte, None).unwrap();
    assert_eq!(status, noxu_db::OperationStatus::NotFound);

    cursor.close().unwrap();
}

/// After cursor.delete(), the deleted record is gone; the next Get::Next skips it.
/// Mirrors the cursor delete + getNext pattern in CursorTest.
#[test]
fn cursor_delete_removes_record_next_skips_it() {
    let dir = tempfile::TempDir::new().unwrap();
    let (_env, db) = open_env_and_db(&dir);

    for (k, v) in [(b"A".as_ref(), b"1".as_ref()), (b"B", b"2"), (b"C", b"3")] {
        db.put(
            None,
            &noxu_db::DatabaseEntry::from_bytes(k),
            &noxu_db::DatabaseEntry::from_bytes(v),
        )
        .unwrap();
    }

    let mut cursor = db.open_cursor(None, None).unwrap();
    let mut key = noxu_db::DatabaseEntry::from_bytes(b"B");
    let mut data = noxu_db::DatabaseEntry::new();

    // Position on "B".
    let status =
        cursor.get(&mut key, &mut data, noxu_db::Get::Search, None).unwrap();
    assert_eq!(status, noxu_db::OperationStatus::Success);

    // Delete "B".
    let del_status = cursor.delete().unwrap();
    assert_eq!(del_status, noxu_db::OperationStatus::Success);

    // The cursor is no longer initialized; a Get::Next should move to "C".
    // (In after delete the cursor sits on a deleted slot and Next skips it.)
    // Here we re-position at "A" and advance past where "B" was.
    let mut key2 = noxu_db::DatabaseEntry::new();
    let mut data2 = noxu_db::DatabaseEntry::new();
    let status =
        cursor.get(&mut key2, &mut data2, noxu_db::Get::First, None).unwrap();
    assert_eq!(status, noxu_db::OperationStatus::Success);
    assert_eq!(key2.data(), b"A");

    let status =
        cursor.get(&mut key2, &mut data2, noxu_db::Get::Next, None).unwrap();
    assert_eq!(status, noxu_db::OperationStatus::Success);
    // "B" was deleted; next key must be "C".
    assert_eq!(key2.data(), b"C");

    cursor.close().unwrap();
}

/// cursor.put(Put::Overwrite) replaces the existing value for a key.
/// cursor.put(Put::NoOverwrite) returns KeyExists when the key is present.
/// Mirrors put/putNoOverwrite cursor tests in CursorTest.
#[test]
fn cursor_put_overwrite_and_no_overwrite() {
    let dir = tempfile::TempDir::new().unwrap();
    let (_env, db) = open_env_and_db(&dir);

    db.put(
        None,
        &noxu_db::DatabaseEntry::from_bytes(b"K"),
        &noxu_db::DatabaseEntry::from_bytes(b"v1"),
    )
    .unwrap();

    let mut cursor = db.open_cursor(None, None).unwrap();

    // NoOverwrite on existing key → KeyExists.
    let kentry = noxu_db::DatabaseEntry::from_bytes(b"K");
    let v2entry = noxu_db::DatabaseEntry::from_bytes(b"v2");
    let status =
        cursor.put(&kentry, &v2entry, noxu_db::Put::NoOverwrite).unwrap();
    assert_eq!(status, noxu_db::OperationStatus::KeyExists);

    // Overwrite on existing key → Success and value replaced.
    let v3entry = noxu_db::DatabaseEntry::from_bytes(b"v3");
    let status =
        cursor.put(&kentry, &v3entry, noxu_db::Put::Overwrite).unwrap();
    assert_eq!(status, noxu_db::OperationStatus::Success);

    // Verify value is now v3.
    let mut read_key = noxu_db::DatabaseEntry::from_bytes(b"K");
    let mut read_data = noxu_db::DatabaseEntry::new();
    cursor
        .get(&mut read_key, &mut read_data, noxu_db::Get::Search, None)
        .unwrap();
    assert_eq!(read_data.data(), b"v3");

    cursor.close().unwrap();
}

/// Two independent cursors on the same database have separate positions.
/// Mirrors the multi-cursor assertions in CursorTest.insertMultiDb().
#[test]
fn two_cursors_independent_positions() {
    let dir = tempfile::TempDir::new().unwrap();
    let (_env, db) = open_env_and_db(&dir);

    for (k, v) in [(b"A".as_ref(), b"1".as_ref()), (b"B", b"2"), (b"C", b"3")] {
        db.put(
            None,
            &noxu_db::DatabaseEntry::from_bytes(k),
            &noxu_db::DatabaseEntry::from_bytes(v),
        )
        .unwrap();
    }

    let mut c1 = db.open_cursor(None, None).unwrap();
    let mut c2 = db.open_cursor(None, None).unwrap();

    let mut k1 = noxu_db::DatabaseEntry::new();
    let mut d1 = noxu_db::DatabaseEntry::new();
    let mut k2 = noxu_db::DatabaseEntry::new();
    let mut d2 = noxu_db::DatabaseEntry::new();

    // c1 → First (A); c2 → Last (C).
    c1.get(&mut k1, &mut d1, noxu_db::Get::First, None).unwrap();
    c2.get(&mut k2, &mut d2, noxu_db::Get::Last, None).unwrap();

    assert_eq!(k1.data(), b"A");
    assert_eq!(k2.data(), b"C");

    // Advancing c1 does not move c2.
    c1.get(&mut k1, &mut d1, noxu_db::Get::Next, None).unwrap();
    assert_eq!(k1.data(), b"B");
    assert_eq!(k2.data(), b"C"); // c2 still at C

    c1.close().unwrap();
    c2.close().unwrap();
}

/// Get::Current returns the record at the current cursor position.
/// Mirrors the putCurrent / getFirst / getFirst cycle in CursorTest.
#[test]
fn cursor_get_current_after_search() {
    let dir = tempfile::TempDir::new().unwrap();
    let (_env, db) = open_env_and_db(&dir);

    db.put(
        None,
        &noxu_db::DatabaseEntry::from_bytes(b"key"),
        &noxu_db::DatabaseEntry::from_bytes(b"val"),
    )
    .unwrap();

    let mut cursor = db.open_cursor(None, None).unwrap();
    let mut key = noxu_db::DatabaseEntry::from_bytes(b"key");
    let mut data = noxu_db::DatabaseEntry::new();

    cursor.get(&mut key, &mut data, noxu_db::Get::Search, None).unwrap();

    // Get::Current should re-return the same record without moving the cursor.
    let mut cur_key = noxu_db::DatabaseEntry::new();
    let mut cur_data = noxu_db::DatabaseEntry::new();
    let status = cursor
        .get(&mut cur_key, &mut cur_data, noxu_db::Get::Current, None)
        .unwrap();
    assert_eq!(status, noxu_db::OperationStatus::Success);
    assert_eq!(cur_key.data(), b"key");
    assert_eq!(cur_data.data(), b"val");

    cursor.close().unwrap();
}

/// Get::Next from an uninitialized cursor positions at the first record.
/// Mirrors Cursor contract: Next from uninitialized == First.
#[test]
fn cursor_next_from_uninitialized_is_first() {
    let dir = tempfile::TempDir::new().unwrap();
    let (_env, db) = open_env_and_db(&dir);

    for (k, v) in [(b"X".as_ref(), b"1".as_ref()), (b"Y", b"2")] {
        db.put(
            None,
            &noxu_db::DatabaseEntry::from_bytes(k),
            &noxu_db::DatabaseEntry::from_bytes(v),
        )
        .unwrap();
    }

    let mut cursor = db.open_cursor(None, None).unwrap();
    let mut key = noxu_db::DatabaseEntry::new();
    let mut data = noxu_db::DatabaseEntry::new();

    let status =
        cursor.get(&mut key, &mut data, noxu_db::Get::Next, None).unwrap();
    assert_eq!(status, noxu_db::OperationStatus::Success);
    assert_eq!(key.data(), b"X"); // First key
    cursor.close().unwrap();
}

/// Get::Prev from an uninitialized cursor positions at the last record.
/// Mirrors Cursor contract: Prev from uninitialized == Last.
#[test]
fn cursor_prev_from_uninitialized_is_last() {
    let dir = tempfile::TempDir::new().unwrap();
    let (_env, db) = open_env_and_db(&dir);

    for (k, v) in [(b"X".as_ref(), b"1".as_ref()), (b"Y", b"2")] {
        db.put(
            None,
            &noxu_db::DatabaseEntry::from_bytes(k),
            &noxu_db::DatabaseEntry::from_bytes(v),
        )
        .unwrap();
    }

    let mut cursor = db.open_cursor(None, None).unwrap();
    let mut key = noxu_db::DatabaseEntry::new();
    let mut data = noxu_db::DatabaseEntry::new();

    let status =
        cursor.get(&mut key, &mut data, noxu_db::Get::Prev, None).unwrap();
    assert_eq!(status, noxu_db::OperationStatus::Success);
    assert_eq!(key.data(), b"Y"); // Last key
    cursor.close().unwrap();
}

// ─── Database correctness tests ───────────────

/// delete() on a missing key returns NotFound.
/// Mirrors testDeleteNonDup(): second delete of same key returns NOTFOUND.
#[test]
fn db_delete_missing_key_returns_not_found() {
    let dir = tempfile::TempDir::new().unwrap();
    let (_env, db) = open_env_and_db(&dir);

    let key = noxu_db::DatabaseEntry::from_bytes(b"ghost");
    let status = db.delete(None, &key).unwrap();
    assert_eq!(status, noxu_db::OperationStatus::NotFound);
}

/// put() followed by delete() followed by another delete() returns NotFound.
/// Mirrors testDeleteNonDup(): delete then re-delete same key.
#[test]
fn db_double_delete_second_is_not_found() {
    let dir = tempfile::TempDir::new().unwrap();
    let (_env, db) = open_env_and_db(&dir);

    let key = noxu_db::DatabaseEntry::from_bytes(b"k");
    let val = noxu_db::DatabaseEntry::from_bytes(b"v");
    db.put(None, &key, &val).unwrap();

    assert_eq!(
        db.delete(None, &key).unwrap(),
        noxu_db::OperationStatus::Success
    );
    assert_eq!(
        db.delete(None, &key).unwrap(),
        noxu_db::OperationStatus::NotFound
    );
}

/// put_no_overwrite() succeeds for a new key, returns KeyExists on the second call,
/// and leaves the original value intact.
/// Mirrors testPutNoOverwriteInANoDupDb().
#[test]
fn db_put_no_overwrite_semantics() {
    let dir = tempfile::TempDir::new().unwrap();
    let (_env, db) = open_env_and_db(&dir);

    let key = noxu_db::DatabaseEntry::from_bytes(b"key");
    let v1 = noxu_db::DatabaseEntry::from_bytes(b"first");
    let v2 = noxu_db::DatabaseEntry::from_bytes(b"second");

    assert_eq!(
        db.put_no_overwrite(None, &key, &v1).unwrap(),
        noxu_db::OperationStatus::Success
    );
    assert_eq!(
        db.put_no_overwrite(None, &key, &v2).unwrap(),
        noxu_db::OperationStatus::KeyExists
    );

    // Original value must be unchanged.
    let mut out = noxu_db::DatabaseEntry::new();
    db.get(None, &key, &mut out).unwrap();
    assert_eq!(out.data(), b"first");
}

/// count() reflects the exact number of live records as puts and deletes occur.
/// Mirrors testDatabaseCount() and testDatabaseCountWithDeletedEntries().
#[test]
fn db_count_tracks_live_records() {
    let dir = tempfile::TempDir::new().unwrap();
    let (_env, db) = open_env_and_db(&dir);

    assert_eq!(db.count().unwrap(), 0);

    // Insert 10 records.
    for i in 0u8..10 {
        db.put(
            None,
            &noxu_db::DatabaseEntry::from_bytes(&[i]),
            &noxu_db::DatabaseEntry::from_bytes(&[i]),
        )
        .unwrap();
    }
    assert_eq!(db.count().unwrap(), 10);

    // Delete every other record (keys 0,2,4,6,8 → 5 deletions).
    for i in (0u8..10).step_by(2) {
        db.delete(None, &noxu_db::DatabaseEntry::from_bytes(&[i])).unwrap();
    }
    assert_eq!(db.count().unwrap(), 5);
}

/// count() returns 0 for an empty database.
/// Mirrors testDatabaseCountEmptyDB().
#[test]
fn db_count_empty_database_is_zero() {
    let dir = tempfile::TempDir::new().unwrap();
    let (_env, db) = open_env_and_db(&dir);
    assert_eq!(db.count().unwrap(), 0);
}

/// put() with an existing key overwrites the value (OVERWRITE semantics).
/// Mirrors testPutExisting(): second put on same key is an update.
#[test]
fn db_put_overwrites_existing_value() {
    let dir = tempfile::TempDir::new().unwrap();
    let (_env, db) = open_env_and_db(&dir);

    let key = noxu_db::DatabaseEntry::from_bytes(b"dup");
    let v1 = noxu_db::DatabaseEntry::from_bytes(b"one");
    let v2 = noxu_db::DatabaseEntry::from_bytes(b"two");

    db.put(None, &key, &v1).unwrap();
    db.put(None, &key, &v2).unwrap();

    let mut out = noxu_db::DatabaseEntry::new();
    db.get(None, &key, &mut out).unwrap();
    assert_eq!(out.data(), b"two");
}

/// After put_no_overwrite + delete + put_no_overwrite the second insert succeeds.
/// Mirrors the delete-then-putNoOverwrite pattern in testPutNoOverwriteInADupDbTxn().
#[test]
fn db_put_no_overwrite_after_delete_succeeds() {
    let dir = tempfile::TempDir::new().unwrap();
    let (_env, db) = open_env_and_db(&dir);

    let key = noxu_db::DatabaseEntry::from_bytes(b"key");
    let v1 = noxu_db::DatabaseEntry::from_bytes(b"first");
    let v2 = noxu_db::DatabaseEntry::from_bytes(b"third");

    db.put_no_overwrite(None, &key, &v1).unwrap();
    db.delete(None, &key).unwrap();

    // After deletion, put_no_overwrite should succeed again.
    let status = db.put_no_overwrite(None, &key, &v2).unwrap();
    assert_eq!(status, noxu_db::OperationStatus::Success);

    let mut out = noxu_db::DatabaseEntry::new();
    db.get(None, &key, &mut out).unwrap();
    assert_eq!(out.data(), b"third");
}

/// Multiple concurrent cursors on the same database are independent and can scan
/// the full record set without interfering with each other.
/// Mirrors the multi-cursor open + scan pattern from DatabaseTest.testCursor()
/// and CursorTest.insertMultiDb().
#[test]
fn db_multiple_concurrent_cursors_scan_same_records() {
    let dir = tempfile::TempDir::new().unwrap();
    let (_env, db) = open_env_and_db(&dir);

    // Insert 5 records.
    for i in 0u8..5 {
        db.put(
            None,
            &noxu_db::DatabaseEntry::from_bytes(&[i]),
            &noxu_db::DatabaseEntry::from_bytes(&[i * 10]),
        )
        .unwrap();
    }

    let mut c1 = db.open_cursor(None, None).unwrap();
    let mut c2 = db.open_cursor(None, None).unwrap();

    let mut k = noxu_db::DatabaseEntry::new();
    let mut d = noxu_db::DatabaseEntry::new();

    // Count records through c1 (forward).
    let mut count1 = 0usize;
    let mut status = c1.get(&mut k, &mut d, noxu_db::Get::First, None).unwrap();
    while status == noxu_db::OperationStatus::Success {
        count1 += 1;
        status = c1.get(&mut k, &mut d, noxu_db::Get::Next, None).unwrap();
    }

    // Count records through c2 (forward); c1 exhausted but c2 is independent.
    let mut count2 = 0usize;
    let mut status = c2.get(&mut k, &mut d, noxu_db::Get::First, None).unwrap();
    while status == noxu_db::OperationStatus::Success {
        count2 += 1;
        status = c2.get(&mut k, &mut d, noxu_db::Get::Next, None).unwrap();
    }

    assert_eq!(count1, 5);
    assert_eq!(count2, 5);

    c1.close().unwrap();
    c2.close().unwrap();
}

/// get() returns NotFound for a key that was never inserted.
/// Mirrors the testGetNonexistent / NOTFOUND assertions from DatabaseTest.
#[test]
fn db_get_not_found_for_missing_key() {
    let dir = tempfile::TempDir::new().unwrap();
    let (_env, db) = open_env_and_db(&dir);

    let mut out = noxu_db::DatabaseEntry::new();
    let status = db
        .get(None, &noxu_db::DatabaseEntry::from_bytes(b"missing"), &mut out)
        .unwrap();
    assert_eq!(status, noxu_db::OperationStatus::NotFound);
}

/// scan_all_kv() + delete all: count drops to zero.
/// Mirrors the truncate / removeAll pattern implicit in DatabaseTest.
#[test]
fn db_remove_all_records_via_scan() {
    let dir = tempfile::TempDir::new().unwrap();
    let (_env, db) = open_env_and_db(&dir);

    // Insert 20 records.
    for i in 0u8..20 {
        db.put(
            None,
            &noxu_db::DatabaseEntry::from_bytes(&[i]),
            &noxu_db::DatabaseEntry::from_bytes(&[i]),
        )
        .unwrap();
    }
    assert_eq!(db.count().unwrap(), 20);

    // Delete all via scan_all_kv.
    let records = db.scan_all_kv().unwrap();
    assert_eq!(records.len(), 20);
    for (k, _) in records {
        db.delete(None, &noxu_db::DatabaseEntry::from_vec(k)).unwrap();
    }
    assert_eq!(db.count().unwrap(), 0);
}

/// Large number of records inserted and iterated — exercises tree splits.
/// Mirrors CursorTest.insertMultiDb() with NUM_RECS = 257 records.
#[test]
fn db_large_record_set_sorted_iteration() {
    let dir = tempfile::TempDir::new().unwrap();
    let (_env, db) = open_env_and_db(&dir);

    const N: u32 = 257;

    // Insert in reverse order so the tree must sort them.
    for i in (1u32..=N).rev() {
        let key_bytes = i.to_be_bytes();
        let val_bytes = i.to_be_bytes();
        db.put(
            None,
            &noxu_db::DatabaseEntry::from_bytes(&key_bytes),
            &noxu_db::DatabaseEntry::from_bytes(&val_bytes),
        )
        .unwrap();
    }

    assert_eq!(db.count().unwrap(), N as u64);

    // Scan and verify ascending order.
    let mut cursor = db.open_cursor(None, None).unwrap();
    let mut key = noxu_db::DatabaseEntry::new();
    let mut data = noxu_db::DatabaseEntry::new();

    let mut prev_key_val: Option<u32> = None;
    let mut count = 0u32;
    let mut status =
        cursor.get(&mut key, &mut data, noxu_db::Get::First, None).unwrap();
    while status == noxu_db::OperationStatus::Success {
        let k_val = u32::from_be_bytes(key.data().try_into().unwrap());
        let d_val = u32::from_be_bytes(data.data().try_into().unwrap());
        assert_eq!(k_val, d_val, "key and data must match");
        if let Some(prev) = prev_key_val {
            assert!(
                k_val > prev,
                "keys must be strictly ascending: {} <= {}",
                k_val,
                prev
            );
        }
        prev_key_val = Some(k_val);
        count += 1;
        status =
            cursor.get(&mut key, &mut data, noxu_db::Get::Next, None).unwrap();
    }
    assert_eq!(count, N);
    cursor.close().unwrap();
}

// ─── Sequence tests ──────────────────────────

/// Helper: open an environment and a plain database for sequence tests.
fn open_seq_env_db(dir: &TempDir) -> (noxu_db::Environment, noxu_db::Database) {
    let env_config = EnvironmentConfig::new(dir.path().to_path_buf())
        .with_allow_create(true)
        .with_transactional(false);
    let env = noxu_db::Environment::open(env_config).unwrap();
    let db = env
        .open_database(
            None,
            "seqdb",
            &DatabaseConfig::new().with_allow_create(true),
        )
        .unwrap();
    (env, db)
}

/// get(delta=1) returns consecutive integers beginning at initial_value=0.
/// Mirrors SequenceTest.testBasic(): first get returns 0, then 1, 3, 6, 7.
#[test]
fn seq_basic_consecutive_integers() {
    let dir = TempDir::new().unwrap();
    let (_env, db) = open_seq_env_db(&dir);

    let key = DatabaseEntry::from_bytes(b"counter");
    let config = noxu_db::SequenceConfig::new()
        .with_allow_create(true)
        .with_initial_value(0)
        .with_cache_size(0);
    let seq = db.open_sequence(&key, config).unwrap();

    // First get returns initial_value=0.
    assert_eq!(seq.get(None, 1).unwrap(), 0);
    // Deltas > 1: returns the value at the start of the advance.
    assert_eq!(seq.get(None, 2).unwrap(), 1);
    assert_eq!(seq.get(None, 3).unwrap(), 3);
    assert_eq!(seq.get(None, 1).unwrap(), 6);
    assert_eq!(seq.get(None, 1).unwrap(), 7);
    seq.close().unwrap();
}

/// Stats: n_gets and n_cache_hits are tracked correctly.
/// Mirrors SequenceTest.testBasic() stats assertions.
#[test]
fn seq_stats_n_gets_and_cache_hits() {
    let dir = TempDir::new().unwrap();
    let (_env, db) = open_seq_env_db(&dir);

    let key = DatabaseEntry::from_bytes(b"stats_key");
    // cache_size=10 means second and subsequent gets (within the batch) are cache hits.
    let config = noxu_db::SequenceConfig::new()
        .with_allow_create(true)
        .with_initial_value(0)
        .with_cache_size(10);
    let seq = db.open_sequence(&key, config).unwrap();

    // Stats before any get: n_gets=0.
    let s = seq.get_stats();
    assert_eq!(s.n_gets, 0);
    assert_eq!(s.range_min, i64::MIN);
    assert_eq!(s.range_max, i64::MAX);

    // First get — triggers a cache refill (not a cache hit).
    let v0 = seq.get(None, 1).unwrap();
    let s = seq.get_stats();
    assert_eq!(s.n_gets, 1);
    // After one get the stored boundary has advanced.
    assert!(s.current_value > v0 || s.current_value == v0 + 1);

    // Second and third gets — served from cache.
    seq.get(None, 1).unwrap();
    seq.get(None, 1).unwrap();
    let s = seq.get_stats();
    assert_eq!(s.n_gets, 3);
    // At least 2 of the 3 gets were cache hits (first one was a refill).
    assert!(
        s.n_cache_hits >= 2,
        "expected >= 2 cache hits, got {}",
        s.n_cache_hits
    );

    seq.close().unwrap();
}

/// Stats: range_min and range_max reflect the configured range.
/// Mirrors SequenceTest.testBasic(): stats.getMin()/getMax() after creation.
#[test]
fn seq_stats_range_fields() {
    let dir = TempDir::new().unwrap();
    let (_env, db) = open_seq_env_db(&dir);

    let key = DatabaseEntry::from_bytes(b"range_key");
    let config = noxu_db::SequenceConfig::new()
        .with_allow_create(true)
        .with_range(-100, 200)
        .with_initial_value(-100)
        .with_cache_size(0);
    let seq = db.open_sequence(&key, config).unwrap();

    seq.get(None, 1).unwrap();
    let s = seq.get_stats();
    assert_eq!(s.range_min, -100);
    assert_eq!(s.range_max, 200);

    seq.close().unwrap();
}

/// delta > 1 skips values: if current=10 and delta=5, next call returns 15.
/// Mirrors SequenceTest.testBasic(): get(delta=2) => 1, get(delta=3) => 3.
#[test]
fn seq_delta_skips_values() {
    let dir = TempDir::new().unwrap();
    let (_env, db) = open_seq_env_db(&dir);

    let key = DatabaseEntry::from_bytes(b"delta_key");
    let config = noxu_db::SequenceConfig::new()
        .with_allow_create(true)
        .with_initial_value(10)
        .with_cache_size(0);
    let seq = db.open_sequence(&key, config).unwrap();

    let v0 = seq.get(None, 5).unwrap();
    let v1 = seq.get(None, 5).unwrap();
    assert_eq!(v0, 10);
    assert_eq!(v1, 15);

    seq.close().unwrap();
}

/// Decrement: sequence counts downward.
/// Mirrors SequenceTest.testIllegal() decrement overflow section and
/// testMultipleHandles() with decrement=true.
#[test]
fn seq_decrement_counts_down() {
    let dir = TempDir::new().unwrap();
    let (_env, db) = open_seq_env_db(&dir);

    let key = DatabaseEntry::from_bytes(b"decr_key");
    let config = noxu_db::SequenceConfig::new()
        .with_allow_create(true)
        .with_range(1, 10)
        .with_initial_value(10)
        .with_decrement(true)
        .with_cache_size(0);
    let seq = db.open_sequence(&key, config).unwrap();

    // Values must strictly decrease.
    let mut prev = seq.get(None, 1).unwrap();
    assert_eq!(prev, 10);
    for _ in 0..9 {
        let next = seq.get(None, 1).unwrap();
        assert!(next < prev, "decrement: next={next} should be < prev={prev}");
        prev = next;
    }
    // After exhausting the range (10 down to 1, 10 values total) overflow.
    let overflow = seq.get(None, 1);
    assert!(overflow.is_err(), "expected overflow error, got ok");
    let msg = format!("{}", overflow.err().unwrap());
    assert!(msg.contains("overflow"), "error should mention overflow: {msg}");

    seq.close().unwrap();
}

/// range enforcement: get() never returns a value outside [min, max].
/// Mirrors SequenceTest.doRange() forward increment path.
#[test]
fn seq_range_values_stay_in_bounds() {
    let dir = TempDir::new().unwrap();
    let (_env, db) = open_seq_env_db(&dir);

    let key = DatabaseEntry::from_bytes(b"range_bounds");
    let min: i64 = -5;
    let max: i64 = 5;
    let config = noxu_db::SequenceConfig::new()
        .with_allow_create(true)
        .with_range(min, max)
        .with_initial_value(min)
        .with_cache_size(0);
    let seq = db.open_sequence(&key, config).unwrap();

    // Drain the whole range (11 values: -5 .. 5 inclusive).
    for expected in min..=max {
        let v = seq.get(None, 1).unwrap();
        assert_eq!(v, expected, "expected {expected}, got {v}");
        assert!(v >= min && v <= max, "value {v} outside [{min}, {max}]");
    }

    // One more call should overflow (wrap=false).
    let overflow = seq.get(None, 1);
    assert!(overflow.is_err(), "expected overflow after exhausting range");
    let msg = format!("{}", overflow.err().unwrap());
    assert!(msg.contains("overflow"), "error should mention overflow: {msg}");

    seq.close().unwrap();
}

/// Wrapping: when max is reached and wrap=true, the sequence wraps to min.
/// Mirrors SequenceTest.doRange() wrap=true path.
#[test]
fn seq_wrap_resets_to_min() {
    let dir = TempDir::new().unwrap();
    let (_env, db) = open_seq_env_db(&dir);

    let key = DatabaseEntry::from_bytes(b"wrap_key");
    let min: i64 = 0;
    let max: i64 = 4;
    let config = noxu_db::SequenceConfig::new()
        .with_allow_create(true)
        .with_range(min, max)
        .with_initial_value(min)
        .with_wrap(true)
        .with_cache_size(0);
    let seq = db.open_sequence(&key, config).unwrap();

    // Drain 0..=4.
    for expected in min..=max {
        let v = seq.get(None, 1).unwrap();
        assert_eq!(v, expected);
    }

    // After wrap the value should be back at min=0.
    let wrapped = seq.get(None, 1).unwrap();
    assert_eq!(
        wrapped, min,
        "after wrap should return min={min}, got {wrapped}"
    );

    seq.close().unwrap();
}

/// Cache refills: first N calls come from cache; when exhausted, the database
/// record (stored_value) is updated.
/// Mirrors SequenceTest.doRange() cache hit tracking.
#[test]
fn seq_cache_refill_pattern() {
    let dir = TempDir::new().unwrap();
    let (_env, db) = open_seq_env_db(&dir);

    let key = DatabaseEntry::from_bytes(b"cache_key");
    let cache = 5;
    let config = noxu_db::SequenceConfig::new()
        .with_allow_create(true)
        .with_initial_value(0)
        .with_cache_size(cache);
    let seq = db.open_sequence(&key, config).unwrap();

    // First get: refill (not a cache hit).
    seq.get(None, 1).unwrap();
    let s0 = seq.get_stats();
    assert_eq!(s0.n_gets, 1);
    assert_eq!(s0.n_cache_hits, 0, "first get should not be a cache hit");

    // Gets 2..=cache: should all be cache hits.
    for _ in 1..cache {
        seq.get(None, 1).unwrap();
    }
    let s1 = seq.get_stats();
    assert_eq!(s1.n_gets, cache as u64);
    assert_eq!(
        s1.n_cache_hits,
        (cache - 1) as u64,
        "gets 2..cache should be cache hits"
    );

    seq.close().unwrap();
}

/// Exclusive create fails if the sequence key already exists.
/// Mirrors SequenceTest.testIllegal(): ExclusiveCreate + existing key.
#[test]
fn seq_exclusive_create_fails_when_exists() {
    let dir = TempDir::new().unwrap();
    let (_env, db) = open_seq_env_db(&dir);

    let key = DatabaseEntry::from_bytes(b"excl_key");
    // First open creates the sequence.
    db.open_sequence(
        &key,
        noxu_db::SequenceConfig::new()
            .with_allow_create(true)
            .with_range(1, 2)
            .with_initial_value(1)
            .with_cache_size(0),
    )
    .unwrap();

    // Second open with exclusive_create=true must fail.
    let result = db.open_sequence(
        &key,
        noxu_db::SequenceConfig::new()
            .with_allow_create(true)
            .with_exclusive_create(true)
            .with_range(1, 2)
            .with_initial_value(1)
            .with_cache_size(0),
    );
    assert!(result.is_err(), "exclusive_create should fail when key exists");
    let msg = format!("{}", result.err().unwrap());
    assert!(
        msg.contains("already exists") || msg.contains("ExclusiveCreate"),
        "unexpected error: {msg}"
    );
}

/// allow_create=false fails when the key does not exist.
/// Mirrors SequenceTest.testIllegal(): AllowCreate=false + missing key.
#[test]
fn seq_no_create_fails_when_missing() {
    let dir = TempDir::new().unwrap();
    let (_env, db) = open_seq_env_db(&dir);

    let key = DatabaseEntry::from_bytes(b"missing_seq");
    let result = db.open_sequence(
        &key,
        noxu_db::SequenceConfig::new().with_allow_create(false),
    );
    assert!(
        result.is_err(),
        "should fail with allow_create=false on missing key"
    );
    let msg = format!("{}", result.err().unwrap());
    assert!(
        msg.contains("does not exist")
            || msg.contains("NotFound")
            || msg.to_lowercase().contains("not found"),
        "unexpected error: {msg}"
    );
}

/// Range validation: min must be strictly less than max.
/// Mirrors SequenceTest.testIllegal(): setRange(0,0) must throw.
#[test]
fn seq_invalid_range_min_equals_max() {
    let dir = TempDir::new().unwrap();
    let (_env, db) = open_seq_env_db(&dir);

    let key = DatabaseEntry::from_bytes(b"bad_range");
    let result = db.open_sequence(
        &key,
        noxu_db::SequenceConfig::new()
            .with_allow_create(true)
            .with_range(5, 5)
            .with_initial_value(5),
    );
    assert!(result.is_err(), "equal min/max must be rejected");
    let msg = format!("{}", result.err().unwrap());
    assert!(
        msg.contains("less than the maximum") || msg.contains("range"),
        "unexpected error: {msg}"
    );
}

/// Initial value out of range must be rejected.
/// Mirrors SequenceTest.testIllegal(): initial value above/below range.
#[test]
fn seq_initial_value_out_of_range() {
    let dir = TempDir::new().unwrap();
    let (_env, db) = open_seq_env_db(&dir);

    let key = DatabaseEntry::from_bytes(b"bad_init");

    // initial_value below range_min
    let result = db.open_sequence(
        &key,
        noxu_db::SequenceConfig::new()
            .with_allow_create(true)
            .with_range(-10, 10)
            .with_initial_value(-11),
    );
    assert!(result.is_err(), "initial value below range_min must be rejected");
    let msg = format!("{}", result.err().unwrap());
    assert!(msg.contains("out of range"), "unexpected error: {msg}");

    // initial_value above range_max
    let result2 = db.open_sequence(
        &key,
        noxu_db::SequenceConfig::new()
            .with_allow_create(true)
            .with_range(-10, 10)
            .with_initial_value(11),
    );
    assert!(result2.is_err(), "initial value above range_max must be rejected");
    let msg2 = format!("{}", result2.err().unwrap());
    assert!(msg2.contains("out of range"), "unexpected error: {msg2}");
}

/// Cache size larger than the range must be rejected.
/// Mirrors SequenceTest.testIllegal(): cache larger than range.
#[test]
fn seq_cache_larger_than_range_rejected() {
    let dir = TempDir::new().unwrap();
    let (_env, db) = open_seq_env_db(&dir);

    let key = DatabaseEntry::from_bytes(b"big_cache");
    let result = db.open_sequence(
        &key,
        noxu_db::SequenceConfig::new()
            .with_allow_create(true)
            .with_range(-10, 10)
            .with_initial_value(0)
            .with_cache_size(21), // range span = 20, cache = 21
    );
    assert!(result.is_err(), "cache larger than range must be rejected");
    let msg = format!("{}", result.err().unwrap());
    assert!(
        msg.contains("cache size is larger") || msg.contains("cache"),
        "unexpected error: {msg}"
    );
}

/// delta=0 must be rejected (delta must be > 0).
/// Mirrors SequenceTest.testIllegal(): delta < 1.
#[test]
fn seq_delta_zero_rejected() {
    let dir = TempDir::new().unwrap();
    let (_env, db) = open_seq_env_db(&dir);

    let key = DatabaseEntry::from_bytes(b"zero_delta");
    let config = noxu_db::SequenceConfig::new()
        .with_allow_create(true)
        .with_range(-5, 5)
        .with_initial_value(-5)
        .with_cache_size(0);
    let seq = db.open_sequence(&key, config).unwrap();

    let result = seq.get(None, 0);
    assert!(result.is_err(), "delta=0 must be rejected");
    let msg = format!("{}", result.unwrap_err());
    assert!(
        msg.contains("greater than zero") || msg.contains("delta"),
        "unexpected error: {msg}"
    );

    seq.close().unwrap();
}

/// delta larger than the range must be rejected.
/// Mirrors SequenceTest.testIllegal(): delta > (max - min).
#[test]
fn seq_delta_larger_than_range_rejected() {
    let dir = TempDir::new().unwrap();
    let (_env, db) = open_seq_env_db(&dir);

    let key = DatabaseEntry::from_bytes(b"big_delta");
    let config = noxu_db::SequenceConfig::new()
        .with_allow_create(true)
        .with_range(-5, 5)
        .with_initial_value(-5)
        .with_cache_size(0);
    let seq = db.open_sequence(&key, config).unwrap();

    let result = seq.get(None, 11); // range = 10, delta = 11
    assert!(result.is_err(), "delta larger than range must be rejected");
    let msg = format!("{}", result.unwrap_err());
    assert!(
        msg.contains("larger than the range") || msg.contains("range"),
        "unexpected error: {msg}"
    );

    seq.close().unwrap();
}

/// Positive and negative ranges: increment through [-10, -1].
/// Mirrors SequenceTest.doRange(db, -10, -1, 1, 0).
#[test]
fn seq_negative_range_increment() {
    let dir = TempDir::new().unwrap();
    let (_env, db) = open_seq_env_db(&dir);

    let key = DatabaseEntry::from_bytes(b"neg_range");
    let min: i64 = -10;
    let max: i64 = -1;
    let config = noxu_db::SequenceConfig::new()
        .with_allow_create(true)
        .with_range(min, max)
        .with_initial_value(min)
        .with_cache_size(0);
    let seq = db.open_sequence(&key, config).unwrap();

    for expected in min..=max {
        let v = seq.get(None, 1).unwrap();
        assert_eq!(v, expected, "expected {expected}, got {v}");
    }

    // Overflow after exhausting.
    assert!(seq.get(None, 1).is_err());
    seq.close().unwrap();
}

/// Multiple handles on the same sequence share a single counter.
/// Mirrors SequenceTest.testMultipleHandles(): seq and seq2 share state.
#[test]
fn seq_multiple_handles_share_counter() {
    let dir = TempDir::new().unwrap();
    let (_env, db) = open_seq_env_db(&dir);

    let key = DatabaseEntry::from_bytes(b"shared_seq");
    let config = noxu_db::SequenceConfig::new()
        .with_allow_create(true)
        .with_initial_value(0)
        .with_cache_size(0);

    let seq1 = db.open_sequence(&key, config.clone()).unwrap();
    let v1 = seq1.get(None, 1).unwrap();
    seq1.close().unwrap();

    // Second handle must pick up where the first left off.
    let seq2 = db.open_sequence(&key, config).unwrap();
    let v2 = seq2.get(None, 1).unwrap();
    assert!(v2 > v1, "seq2 must continue from seq1: v2={v2} v1={v1}");
    seq2.close().unwrap();
}

/// Extreme ranges: Long.MIN_VALUE to Long.MIN_VALUE + 10.
/// Mirrors SequenceTest.testRanges() extreme min/max section.
#[test]
fn seq_extreme_range_i64_min() {
    let dir = TempDir::new().unwrap();
    let (_env, db) = open_seq_env_db(&dir);

    let key = DatabaseEntry::from_bytes(b"i64_min_range");
    let min = i64::MIN;
    let max = i64::MIN + 10;
    let config = noxu_db::SequenceConfig::new()
        .with_allow_create(true)
        .with_range(min, max)
        .with_initial_value(min)
        .with_cache_size(0);
    let seq = db.open_sequence(&key, config).unwrap();

    for expected in min..=max {
        let v = seq.get(None, 1).unwrap();
        assert_eq!(v, expected);
    }
    assert!(seq.get(None, 1).is_err());
    seq.close().unwrap();
}

/// Extreme ranges: Long.MAX_VALUE - 10 to Long.MAX_VALUE.
/// Mirrors SequenceTest.testRanges() extreme min/max section.
#[test]
fn seq_extreme_range_i64_max() {
    let dir = TempDir::new().unwrap();
    let (_env, db) = open_seq_env_db(&dir);

    let key = DatabaseEntry::from_bytes(b"i64_max_range");
    let min = i64::MAX - 10;
    let max = i64::MAX;
    let config = noxu_db::SequenceConfig::new()
        .with_allow_create(true)
        .with_range(min, max)
        .with_initial_value(min)
        .with_cache_size(0);
    let seq = db.open_sequence(&key, config).unwrap();

    for expected in min..=max {
        let v = seq.get(None, 1).unwrap();
        assert_eq!(v, expected);
    }
    assert!(seq.get(None, 1).is_err());
    seq.close().unwrap();
}

// ─── Secondary database tests ───────────────

use noxu_db::{
    SecondaryConfig, SecondaryDatabase, SecondaryKeyCreator,
    SecondaryMultiKeyCreator,
};
use noxu_sync::Mutex;
use std::sync::Arc;

/// A simple secondary key creator: sec_key = data[0..1] (first byte).
/// Equivalent to SecondaryTest's numeric offset pattern adapted to bytes.
struct FirstByteCreator;

impl SecondaryKeyCreator for FirstByteCreator {
    fn create_secondary_key(
        &self,
        _db: &noxu_db::Database,
        _key: &DatabaseEntry,
        data: &DatabaseEntry,
        result: &mut DatabaseEntry,
    ) -> bool {
        if let Some(d) = data.get_data()
            && !d.is_empty()
        {
            result.set_data(&d[..1]);
            return true;
        }
        false
    }
}

/// A multi-key creator that treats each byte of data as its own secondary key.
/// Enables testing MultiKeyCreator semantics (multiple sec keys per primary).
struct EachByteCreator;

impl SecondaryMultiKeyCreator for EachByteCreator {
    fn create_secondary_keys(
        &self,
        _db: &noxu_db::Database,
        _key: &DatabaseEntry,
        data: &DatabaseEntry,
        results: &mut Vec<DatabaseEntry>,
    ) {
        if let Some(d) = data.get_data() {
            for &byte in d {
                results.push(DatabaseEntry::from_bytes(&[byte]));
            }
        }
    }
}

/// Helper: set up a primary + secondary for integration tests.
fn open_pri_sec(
    dir: &TempDir,
) -> (noxu_db::Environment, Arc<Mutex<noxu_db::Database>>, SecondaryDatabase) {
    let env_config = EnvironmentConfig::new(dir.path().to_path_buf())
        .with_allow_create(true)
        .with_transactional(true);
    let env = noxu_db::Environment::open(env_config).unwrap();

    let db_config = DatabaseConfig::new().with_allow_create(true);
    let primary_db = env.open_database(None, "primary", &db_config).unwrap();
    let primary = Arc::new(Mutex::new(primary_db));

    let sec_db = env
        .open_database(
            None,
            "secondary",
            &DatabaseConfig::new()
                .with_allow_create(true)
                .with_sorted_duplicates(true),
        )
        .unwrap();
    let sec_config = SecondaryConfig::new()
        .with_allow_create(true)
        .with_key_creator(Box::new(FirstByteCreator));
    let secondary =
        SecondaryDatabase::open(Arc::clone(&primary), sec_db, sec_config)
            .unwrap();

    (env, primary, secondary)
}

/// Helper: write to primary then manually update the secondary.
fn pri_put_and_index(
    primary: &Arc<Mutex<noxu_db::Database>>,
    secondary: &SecondaryDatabase,
    k: &[u8],
    v: &[u8],
    old_v: Option<&[u8]>,
) {
    let pk = DatabaseEntry::from_bytes(k);
    let new_data = DatabaseEntry::from_bytes(v);
    primary.lock().put(None, &pk, &new_data).unwrap();
    let old_entry = old_v.map(DatabaseEntry::from_bytes);
    secondary
        .update_secondary(None, &pk, old_entry.as_ref(), Some(&new_data))
        .unwrap();
}

/// put to primary → get from secondary returns primary_key + data.
/// Mirrors SecondaryTest.testPutAndDelete(): Database.put() / secDb.get().
#[test]
fn sec_put_primary_get_by_secondary_key() {
    let dir = TempDir::new().unwrap();
    let (_env, primary, secondary) = open_pri_sec(&dir);

    pri_put_and_index(&primary, &secondary, b"pk1", b"Apple", None);

    // Lookup by secondary key 'A' (first byte of "Apple").
    let sec_key = DatabaseEntry::from_bytes(b"A");
    let mut p_key = DatabaseEntry::new();
    let mut data = DatabaseEntry::new();
    let status = secondary.get(None, &sec_key, &mut p_key, &mut data).unwrap();
    assert_eq!(status, OperationStatus::Success);
    assert_eq!(p_key.get_data().unwrap(), b"pk1");
    assert_eq!(data.get_data().unwrap(), b"Apple");
}

/// Delete from primary removes secondary entry; subsequent get returns NotFound.
/// Mirrors SecondaryTest.testPutAndDelete(): Database.delete() removes sec entry.
/// We use SecondaryDatabase::delete() (deletes via secondary key) since
/// delete_all_for_primary is crate-internal.
#[test]
fn sec_delete_primary_removes_secondary() {
    let dir = TempDir::new().unwrap();
    let (_env, primary, secondary) = open_pri_sec(&dir);

    pri_put_and_index(&primary, &secondary, b"pk1", b"Cherry", None);

    // Delete via secondary key 'C' (first byte of "Cherry").
    // SecondaryDatabase::delete() removes the primary record and its secondary entries.
    let sec_key = DatabaseEntry::from_bytes(b"C");
    let del_status = secondary.delete(None, &sec_key).unwrap();
    assert_eq!(del_status, OperationStatus::Success);

    // Secondary lookup should now return NotFound.
    let mut p_key = DatabaseEntry::new();
    let mut data = DatabaseEntry::new();
    let status = secondary.get(None, &sec_key, &mut p_key, &mut data).unwrap();
    assert_eq!(status, OperationStatus::NotFound);

    // Primary record is also gone.
    let mut pri_data = DatabaseEntry::new();
    let pri_status = primary
        .lock()
        .get(None, &DatabaseEntry::from_bytes(b"pk1"), &mut pri_data)
        .unwrap();
    assert_eq!(pri_status, OperationStatus::NotFound);
}

/// Searching secondary with non-existent key returns NotFound.
/// Mirrors SecondaryTest.testPutAndDelete(): get on missing sec key.
#[test]
fn sec_get_nonexistent_key_returns_not_found() {
    let dir = TempDir::new().unwrap();
    let (_env, primary, secondary) = open_pri_sec(&dir);

    pri_put_and_index(&primary, &secondary, b"pk1", b"Banana", None);

    // 'Z' does not map to any primary record.
    let sec_key = DatabaseEntry::from_bytes(b"Z");
    let mut p_key = DatabaseEntry::new();
    let mut data = DatabaseEntry::new();
    let status = secondary.get(None, &sec_key, &mut p_key, &mut data).unwrap();
    assert_eq!(status, OperationStatus::NotFound);
}

/// Update primary value changes secondary key mapping.
/// Mirrors SecondaryTest.testPutAndDelete(): Database.put() overwrite removes
/// old sec entry (102→NotFound) and inserts new one (103→Success).
#[test]
fn sec_update_primary_changes_secondary_key() {
    let dir = TempDir::new().unwrap();
    let (_env, primary, secondary) = open_pri_sec(&dir);

    // Insert with data "Banana" → sec key 'B'.
    pri_put_and_index(&primary, &secondary, b"pk1", b"Banana", None);

    // Overwrite with "Cherry" → sec key should change to 'C'.
    pri_put_and_index(&primary, &secondary, b"pk1", b"Cherry", Some(b"Banana"));

    // Old sec key 'B' must be gone.
    let sec_key_b = DatabaseEntry::from_bytes(b"B");
    let mut pk = DatabaseEntry::new();
    let mut data = DatabaseEntry::new();
    let status = secondary.get(None, &sec_key_b, &mut pk, &mut data).unwrap();
    assert_eq!(
        status,
        OperationStatus::NotFound,
        "old sec key 'B' should be removed"
    );

    // New sec key 'C' must be present.
    let sec_key_c = DatabaseEntry::from_bytes(b"C");
    let status = secondary.get(None, &sec_key_c, &mut pk, &mut data).unwrap();
    assert_eq!(status, OperationStatus::Success);
    assert_eq!(data.get_data().unwrap(), b"Cherry");
}

/// Delete via secondary database deletes the primary record.
/// Mirrors SecondaryTest.testPutAndDelete(): SecondaryDatabase.delete().
#[test]
fn sec_delete_via_secondary_removes_primary() {
    let dir = TempDir::new().unwrap();
    let (_env, primary, secondary) = open_pri_sec(&dir);

    pri_put_and_index(&primary, &secondary, b"pk1", b"Durian", None);

    // Delete by secondary key 'D'.
    let sec_key = DatabaseEntry::from_bytes(b"D");
    let status = secondary.delete(None, &sec_key).unwrap();
    assert_eq!(status, OperationStatus::Success);

    // Second delete on same key returns NotFound.
    let status2 = secondary.delete(None, &sec_key).unwrap();
    assert_eq!(status2, OperationStatus::NotFound);

    // Primary record is gone.
    let mut data = DatabaseEntry::new();
    let get_status = primary
        .lock()
        .get(None, &DatabaseEntry::from_bytes(b"pk1"), &mut data)
        .unwrap();
    assert_eq!(get_status, OperationStatus::NotFound);
}

/// SecondaryCursor::get_first/next iterates all records in secondary key order.
/// Mirrors SecondaryTest.testGet(): cursor.getFirst()/getNext() loop.
#[test]
fn sec_cursor_first_next_sorted_order() {
    let dir = TempDir::new().unwrap();
    let (_env, primary, secondary) = open_pri_sec(&dir);

    // Insert 5 records with sec keys C, A, E, B, D.
    let records: &[(&[u8], &[u8])] = &[
        (b"pk0", b"Cherry"),
        (b"pk1", b"Apple"),
        (b"pk2", b"Elderberry"),
        (b"pk3", b"Banana"),
        (b"pk4", b"Date"),
    ];
    for (k, v) in records {
        pri_put_and_index(&primary, &secondary, k, v, None);
    }

    let mut cursor = secondary.open_cursor(None, None).unwrap();
    let mut sec_key = DatabaseEntry::new();
    let mut p_key = DatabaseEntry::new();
    let mut data = DatabaseEntry::new();

    let mut got: Vec<(Vec<u8>, Vec<u8>)> = Vec::new();
    let mut status =
        cursor.get_first(&mut sec_key, &mut p_key, &mut data).unwrap();
    while status == OperationStatus::Success {
        got.push((
            sec_key.get_data().unwrap().to_vec(),
            data.get_data().unwrap().to_vec(),
        ));
        status = cursor.get_next(&mut sec_key, &mut p_key, &mut data).unwrap();
    }
    cursor.close().unwrap();

    // Must be in secondary key order: A, B, C, D, E.
    assert_eq!(got.len(), 5);
    assert_eq!(got[0].0, b"A");
    assert_eq!(got[0].1, b"Apple");
    assert_eq!(got[1].0, b"B");
    assert_eq!(got[1].1, b"Banana");
    assert_eq!(got[2].0, b"C");
    assert_eq!(got[2].1, b"Cherry");
    assert_eq!(got[3].0, b"D");
    assert_eq!(got[3].1, b"Date");
    assert_eq!(got[4].0, b"E");
    assert_eq!(got[4].1, b"Elderberry");
}

/// SecondaryCursor::get_last/prev returns records in reverse secondary key order.
/// Mirrors SecondaryTest.testGet(): cursor.getLast()/getPrev() loop.
#[test]
fn sec_cursor_last_prev_reverse_order() {
    let dir = TempDir::new().unwrap();
    let (_env, primary, secondary) = open_pri_sec(&dir);

    let records: &[(&[u8], &[u8])] =
        &[(b"pk1", b"Apple"), (b"pk2", b"Banana"), (b"pk3", b"Cherry")];
    for (k, v) in records {
        pri_put_and_index(&primary, &secondary, k, v, None);
    }

    let mut cursor = secondary.open_cursor(None, None).unwrap();
    let mut sec_key = DatabaseEntry::new();
    let mut p_key = DatabaseEntry::new();
    let mut data = DatabaseEntry::new();

    let mut got_data: Vec<Vec<u8>> = Vec::new();
    let mut status =
        cursor.get_last(&mut sec_key, &mut p_key, &mut data).unwrap();
    while status == OperationStatus::Success {
        got_data.push(data.get_data().unwrap().to_vec());
        status = cursor.get_prev(&mut sec_key, &mut p_key, &mut data).unwrap();
    }
    cursor.close().unwrap();

    assert_eq!(got_data.len(), 3);
    assert_eq!(got_data[0], b"Cherry");
    assert_eq!(got_data[1], b"Banana");
    assert_eq!(got_data[2], b"Apple");
}

/// SecondaryCursor::get_search_key returns (sec_key, pri_key, data) correctly.
/// Mirrors SecondaryTest.testGet(): cursor.getSearchKey() with known sec keys.
#[test]
fn sec_cursor_search_key_returns_tuple() {
    let dir = TempDir::new().unwrap();
    let (_env, primary, secondary) = open_pri_sec(&dir);

    let records: &[(&[u8], &[u8])] =
        &[(b"pk0", b"Apricot"), (b"pk1", b"Banana"), (b"pk2", b"Citrus")];
    for (k, v) in records {
        pri_put_and_index(&primary, &secondary, k, v, None);
    }

    let mut cursor = secondary.open_cursor(None, None).unwrap();
    let search = DatabaseEntry::from_bytes(b"B");
    let mut p_key = DatabaseEntry::new();
    let mut data = DatabaseEntry::new();

    let status = cursor.get_search_key(&search, &mut p_key, &mut data).unwrap();
    assert_eq!(status, OperationStatus::Success);
    assert_eq!(p_key.get_data().unwrap(), b"pk1");
    assert_eq!(data.get_data().unwrap(), b"Banana");

    cursor.close().unwrap();
}

/// SecondaryCursor::get_search_key with non-existent key returns NotFound.
/// Mirrors SecondaryTest.testGet(): getSearchKey on KEY_OFFSET-1 → NOTFOUND.
#[test]
fn sec_cursor_search_key_not_found() {
    let dir = TempDir::new().unwrap();
    let (_env, primary, secondary) = open_pri_sec(&dir);

    pri_put_and_index(&primary, &secondary, b"pk1", b"Apple", None);

    let mut cursor = secondary.open_cursor(None, None).unwrap();
    let search = DatabaseEntry::from_bytes(b"Z");
    let mut p_key = DatabaseEntry::new();
    let mut data = DatabaseEntry::new();

    let status = cursor.get_search_key(&search, &mut p_key, &mut data).unwrap();
    assert_eq!(status, OperationStatus::NotFound);

    cursor.close().unwrap();
}

/// SecondaryCursor::get_search_key_range finds first sec key >= search key.
/// Mirrors SecondaryTest.testGet(): cursor.getSearchKeyRange(KEY_OFFSET-1) → first record.
#[test]
fn sec_cursor_search_key_range_gte() {
    let dir = TempDir::new().unwrap();
    let (_env, primary, secondary) = open_pri_sec(&dir);

    // Insert keys with first bytes C and E (no B/D).
    pri_put_and_index(&primary, &secondary, b"pk1", b"Cherry", None);
    pri_put_and_index(&primary, &secondary, b"pk2", b"Elderberry", None);

    let mut cursor = secondary.open_cursor(None, None).unwrap();
    // 'D' is between C and E; GTE should return 'E' (Elderberry).
    let mut search = DatabaseEntry::from_bytes(b"D");
    let mut p_key = DatabaseEntry::new();
    let mut data = DatabaseEntry::new();

    let status = cursor
        .get_search_key_range(&mut search, &mut p_key, &mut data)
        .unwrap();
    assert_eq!(status, OperationStatus::Success);
    assert_eq!(data.get_data().unwrap(), b"Elderberry");

    // 'A' → should land on first entry 'C' (Cherry).
    let mut search2 = DatabaseEntry::from_bytes(b"A");
    let status2 = cursor
        .get_search_key_range(&mut search2, &mut p_key, &mut data)
        .unwrap();
    assert_eq!(status2, OperationStatus::Success);
    assert_eq!(data.get_data().unwrap(), b"Cherry");

    // 'Z' → beyond all entries, NotFound.
    let mut search3 = DatabaseEntry::from_bytes(b"Z");
    let status3 = cursor
        .get_search_key_range(&mut search3, &mut p_key, &mut data)
        .unwrap();
    assert_eq!(status3, OperationStatus::NotFound);

    cursor.close().unwrap();
}

/// SecondaryCursor::get_current returns the current (sec_key, pri_key, data).
/// Mirrors SecondaryTest.testGet(): cursor.getCurrent() after getFirst.
#[test]
fn sec_cursor_get_current_after_position() {
    let dir = TempDir::new().unwrap();
    let (_env, primary, secondary) = open_pri_sec(&dir);

    pri_put_and_index(&primary, &secondary, b"pk1", b"Mango", None);

    let mut cursor = secondary.open_cursor(None, None).unwrap();
    let mut sk = DatabaseEntry::new();
    let mut pk = DatabaseEntry::new();
    let mut data = DatabaseEntry::new();

    cursor.get_first(&mut sk, &mut pk, &mut data).unwrap();

    // get_current should return the same position.
    let mut sk2 = DatabaseEntry::new();
    let mut pk2 = DatabaseEntry::new();
    let mut data2 = DatabaseEntry::new();
    let status = cursor.get_current(&mut sk2, &mut pk2, &mut data2).unwrap();
    assert_eq!(status, OperationStatus::Success);
    assert_eq!(sk2.get_data(), sk.get_data());
    assert_eq!(pk2.get_data(), pk.get_data());
    assert_eq!(data2.get_data().unwrap(), b"Mango");

    cursor.close().unwrap();
}

/// Multiple secondary keys per primary record (MultiKeyCreator).
/// Each byte of data becomes an independent secondary index entry.
/// Mirrors SecondaryTest's useMultiKey=true behaviour.
#[test]
fn sec_multi_key_creator_multiple_keys_per_record() {
    let dir = TempDir::new().unwrap();
    let env_config = EnvironmentConfig::new(dir.path().to_path_buf())
        .with_allow_create(true)
        .with_transactional(true);
    let env = noxu_db::Environment::open(env_config).unwrap();

    let primary_db = env
        .open_database(
            None,
            "pri_mk",
            &DatabaseConfig::new().with_allow_create(true),
        )
        .unwrap();
    let primary = Arc::new(Mutex::new(primary_db));

    let sec_db = env
        .open_database(
            None,
            "sec_mk",
            &DatabaseConfig::new()
                .with_allow_create(true)
                .with_sorted_duplicates(true),
        )
        .unwrap();
    let sec_config = SecondaryConfig::new()
        .with_allow_create(true)
        .with_multi_key_creator(Box::new(EachByteCreator));
    let secondary =
        SecondaryDatabase::open(Arc::clone(&primary), sec_db, sec_config)
            .unwrap();

    // Primary record: key="pk1", data=[0x41, 0x42] = "AB"
    let pk = DatabaseEntry::from_bytes(b"pk1");
    let pv = DatabaseEntry::from_bytes(b"AB");
    primary.lock().put(None, &pk, &pv).unwrap();
    secondary.update_secondary(None, &pk, None, Some(&pv)).unwrap();

    // Both 'A' and 'B' should map to pk1.
    for sec_byte in [b"A" as &[u8], b"B"] {
        let sec_key = DatabaseEntry::from_bytes(sec_byte);
        let mut found_pk = DatabaseEntry::new();
        let mut found_data = DatabaseEntry::new();
        let status = secondary
            .get(None, &sec_key, &mut found_pk, &mut found_data)
            .unwrap();
        assert_eq!(
            status,
            OperationStatus::Success,
            "sec key {:?} not found",
            sec_byte
        );
        assert_eq!(found_pk.get_data().unwrap(), b"pk1");
        assert_eq!(found_data.get_data().unwrap(), b"AB");
    }

    // 'C' should not exist.
    let sec_key_c = DatabaseEntry::from_bytes(b"C");
    let mut pk_out = DatabaseEntry::new();
    let mut data_out = DatabaseEntry::new();
    let status =
        secondary.get(None, &sec_key_c, &mut pk_out, &mut data_out).unwrap();
    assert_eq!(status, OperationStatus::NotFound);
}

/// auto-populate: opening secondary with allow_populate=true on an existing
/// primary fills the index from all existing primary records.
/// Mirrors SecondaryTest's secondary open on a non-empty primary.
#[test]
fn sec_auto_populate_on_open() {
    let dir = TempDir::new().unwrap();
    let env_config = EnvironmentConfig::new(dir.path().to_path_buf())
        .with_allow_create(true)
        .with_transactional(true);
    let env = noxu_db::Environment::open(env_config).unwrap();

    let primary_db = env
        .open_database(
            None,
            "pri_pop",
            &DatabaseConfig::new().with_allow_create(true),
        )
        .unwrap();
    let primary = Arc::new(Mutex::new(primary_db));

    // Pre-populate primary with 3 records.
    for (k, v) in [
        (b"pk1" as &[u8], b"Grape" as &[u8]),
        (b"pk2", b"Kiwi"),
        (b"pk3", b"Lemon"),
    ] {
        primary
            .lock()
            .put(
                None,
                &DatabaseEntry::from_bytes(k),
                &DatabaseEntry::from_bytes(v),
            )
            .unwrap();
    }

    // Open secondary with allow_populate=true.
    let sec_db = env
        .open_database(
            None,
            "sec_pop",
            &DatabaseConfig::new()
                .with_allow_create(true)
                .with_sorted_duplicates(true),
        )
        .unwrap();
    let sec_config = SecondaryConfig::new()
        .with_allow_create(true)
        .with_allow_populate(true)
        .with_key_creator(Box::new(FirstByteCreator));
    let secondary =
        SecondaryDatabase::open(Arc::clone(&primary), sec_db, sec_config)
            .unwrap();

    // All three records should be indexed.
    for (sec_b, expected_data) in
        [(b"G" as &[u8], b"Grape" as &[u8]), (b"K", b"Kiwi"), (b"L", b"Lemon")]
    {
        let sec_key = DatabaseEntry::from_bytes(sec_b);
        let mut pk = DatabaseEntry::new();
        let mut data = DatabaseEntry::new();
        let status = secondary.get(None, &sec_key, &mut pk, &mut data).unwrap();
        assert_eq!(
            status,
            OperationStatus::Success,
            "sec key {:?} missing after auto-populate",
            sec_b
        );
        assert_eq!(data.get_data().unwrap(), expected_data);
    }
}

/// NUM_RECS put/get round trip through secondary matching SecondaryTest.testGet()
/// structure: 5 records with sec_key = pri_key + KEY_OFFSET encoded as big-endian u32.
/// Integer-based pattern.
#[test]
fn sec_num_recs_put_get_round_trip() {
    const NUM_RECS: u32 = 5;
    const KEY_OFFSET: u32 = 100;

    let dir = TempDir::new().unwrap();
    let env_config = EnvironmentConfig::new(dir.path().to_path_buf())
        .with_allow_create(true)
        .with_transactional(true);
    let env = noxu_db::Environment::open(env_config).unwrap();

    // Use a key creator that extracts bytes [4..8] of data as the secondary key
    // (the second u32 field, simulating the "value = i, sec_key = i+100" pattern).
    struct SecondU32Creator;
    impl SecondaryKeyCreator for SecondU32Creator {
        fn create_secondary_key(
            &self,
            _db: &noxu_db::Database,
            _key: &DatabaseEntry,
            data: &DatabaseEntry,
            result: &mut DatabaseEntry,
        ) -> bool {
            if let Some(d) = data.get_data()
                && d.len() >= 8
            {
                result.set_data(&d[4..8]);
                return true;
            }
            false
        }
    }

    let primary_db = env
        .open_database(
            None,
            "pri_nr",
            &DatabaseConfig::new().with_allow_create(true),
        )
        .unwrap();
    let primary = Arc::new(Mutex::new(primary_db));

    let sec_db = env
        .open_database(
            None,
            "sec_nr",
            &DatabaseConfig::new()
                .with_allow_create(true)
                .with_sorted_duplicates(true),
        )
        .unwrap();
    let sec_config = SecondaryConfig::new()
        .with_allow_create(true)
        .with_key_creator(Box::new(SecondU32Creator));
    let secondary =
        SecondaryDatabase::open(Arc::clone(&primary), sec_db, sec_config)
            .unwrap();

    // Insert records: pri_key = i (be_u32), data = i ++ (i+KEY_OFFSET) packed as 8 bytes.
    for i in 0u32..NUM_RECS {
        let pri_key_bytes = i.to_be_bytes();
        let sec_key_val = i + KEY_OFFSET;
        // data = 4 bytes primary value + 4 bytes secondary key value
        let mut data_bytes = [0u8; 8];
        data_bytes[..4].copy_from_slice(&i.to_be_bytes());
        data_bytes[4..].copy_from_slice(&sec_key_val.to_be_bytes());

        let pk = DatabaseEntry::from_bytes(&pri_key_bytes);
        let pv = DatabaseEntry::from_bytes(&data_bytes);
        primary.lock().put(None, &pk, &pv).unwrap();
        secondary.update_secondary(None, &pk, None, Some(&pv)).unwrap();
    }

    // SecondaryDatabase.get(): look up by sec_key = i + KEY_OFFSET for i in 0..NUM_RECS.
    for i in 0u32..NUM_RECS {
        let sec_key_val = (i + KEY_OFFSET).to_be_bytes();
        let sec_key = DatabaseEntry::from_bytes(&sec_key_val);
        let mut p_key = DatabaseEntry::new();
        let mut data = DatabaseEntry::new();
        let status =
            secondary.get(None, &sec_key, &mut p_key, &mut data).unwrap();
        assert_eq!(status, OperationStatus::Success, "i={i}: sec get failed");
        // Primary key should be i
        assert_eq!(
            p_key.get_data().unwrap(),
            &i.to_be_bytes(),
            "i={i}: wrong pri key"
        );
    }

    // Look up sec_key = NUM_RECS + KEY_OFFSET → NotFound.
    let missing_sec = (NUM_RECS + KEY_OFFSET).to_be_bytes();
    let mut pk_out = DatabaseEntry::new();
    let mut data_out = DatabaseEntry::new();
    let status = secondary
        .get(
            None,
            &DatabaseEntry::from_bytes(&missing_sec),
            &mut pk_out,
            &mut data_out,
        )
        .unwrap();
    assert_eq!(status, OperationStatus::NotFound);

    // SecondaryCursor First/Next scan: collect all in order.
    let mut cursor = secondary.open_cursor(None, None).unwrap();
    let mut sk = DatabaseEntry::new();
    let mut pk = DatabaseEntry::new();
    let mut d = DatabaseEntry::new();

    let mut count = 0u32;
    let mut prev_sec_key: Option<u32> = None;
    let mut status = cursor.get_first(&mut sk, &mut pk, &mut d).unwrap();
    while status == OperationStatus::Success {
        let sk_val =
            u32::from_be_bytes(sk.get_data().unwrap().try_into().unwrap());
        let pk_val =
            u32::from_be_bytes(pk.get_data().unwrap().try_into().unwrap());
        // sec_key = pri_key + KEY_OFFSET
        assert_eq!(
            sk_val,
            pk_val + KEY_OFFSET,
            "count={count}: sec key mismatch"
        );
        if let Some(prev) = prev_sec_key {
            assert!(sk_val > prev, "count={count}: sec keys not ascending");
        }
        prev_sec_key = Some(sk_val);
        count += 1;
        status = cursor.get_next(&mut sk, &mut pk, &mut d).unwrap();
    }
    assert_eq!(count, NUM_RECS);

    // SecondaryCursor Last/Prev scan: verify reverse order.
    let mut count_rev = 0u32;
    let mut prev_sk_val: Option<u32> = None;
    let mut status = cursor.get_last(&mut sk, &mut pk, &mut d).unwrap();
    while status == OperationStatus::Success {
        let sk_val =
            u32::from_be_bytes(sk.get_data().unwrap().try_into().unwrap());
        if let Some(prev) = prev_sk_val {
            assert!(
                sk_val < prev,
                "count_rev={count_rev}: sec keys not descending"
            );
        }
        prev_sk_val = Some(sk_val);
        count_rev += 1;
        status = cursor.get_prev(&mut sk, &mut pk, &mut d).unwrap();
    }
    assert_eq!(count_rev, NUM_RECS);

    // SecondaryCursor get_search_key: find each entry, confirm NotFound outside range.
    for i in 0u32..NUM_RECS {
        let sec_key_bytes = (i + KEY_OFFSET).to_be_bytes();
        let search = DatabaseEntry::from_bytes(&sec_key_bytes);
        let mut p_key = DatabaseEntry::new();
        let mut data = DatabaseEntry::new();
        let s = cursor.get_search_key(&search, &mut p_key, &mut data).unwrap();
        assert_eq!(s, OperationStatus::Success, "i={i}: search failed");
        assert_eq!(
            p_key.get_data().unwrap(),
            &i.to_be_bytes(),
            "i={i}: wrong pri key from cursor search"
        );
    }

    // Just outside range (KEY_OFFSET - 1) → NotFound.
    let before_range = (KEY_OFFSET - 1).to_be_bytes();
    let status = cursor
        .get_search_key(
            &DatabaseEntry::from_bytes(&before_range),
            &mut DatabaseEntry::new(),
            &mut DatabaseEntry::new(),
        )
        .unwrap();
    assert_eq!(status, OperationStatus::NotFound);

    cursor.close().unwrap();
}

// ─── Cursor search tests ────────────────
//
// DbCursorSearchTest verifies GetSearchKey / GetSearchKeyRange behaviour across
// single- and multi-BIN trees (uses N_KEYS = 50 to force at least one split).

///
/// Put a small number of string key-value pairs then verify that Get::Search
/// finds each one and the returned data matches the stored value.
#[test]
fn cursor_search_simple_exact_match() {
    let dir = TempDir::new().unwrap();
    let (_env, db) = open_env_and_db(&dir);

    let pairs: &[(&[u8], &[u8])] = &[
        (b"bar", b"two"),
        (b"baz", b"three"),
        (b"foo", b"one"),
        (b"quux", b"four"),
    ];

    for (k, v) in pairs {
        db.put(
            None,
            &DatabaseEntry::from_bytes(k),
            &DatabaseEntry::from_bytes(v),
        )
        .unwrap();
    }

    let mut cursor = db.open_cursor(None, None).unwrap();
    for (k, v) in pairs {
        let mut key = DatabaseEntry::from_bytes(k);
        let mut data = DatabaseEntry::new();
        let status =
            cursor.get(&mut key, &mut data, Get::Search, None).unwrap();
        assert_eq!(
            status,
            OperationStatus::Success,
            "Get::Search must succeed for key {:?}",
            k
        );
        assert_eq!(data.data(), *v, "data must match for key {:?}", k);
    }
    cursor.close().unwrap();
}

///
/// Put records, search for each one successfully, delete via cursor, then
/// verify that a subsequent Get::Search returns NotFound.
#[test]
fn cursor_search_after_delete_returns_not_found() {
    let dir = TempDir::new().unwrap();
    let (_env, db) = open_env_and_db(&dir);

    let pairs: &[(&[u8], &[u8])] =
        &[(b"alpha", b"1"), (b"beta", b"2"), (b"gamma", b"3")];

    for (k, v) in pairs {
        db.put(
            None,
            &DatabaseEntry::from_bytes(k),
            &DatabaseEntry::from_bytes(v),
        )
        .unwrap();
    }

    let mut cursor = db.open_cursor(None, None).unwrap();

    for (k, _v) in pairs {
        // Search must succeed before deletion.
        let mut key = DatabaseEntry::from_bytes(k);
        let mut data = DatabaseEntry::new();
        let status =
            cursor.get(&mut key, &mut data, Get::Search, None).unwrap();
        assert_eq!(
            status,
            OperationStatus::Success,
            "Get::Search must succeed before deletion for {:?}",
            k
        );

        cursor.delete().unwrap();

        // Searching again must return NotFound.
        let mut key2 = DatabaseEntry::from_bytes(k);
        let mut data2 = DatabaseEntry::new();
        let status2 =
            cursor.get(&mut key2, &mut data2, Get::Search, None).unwrap();
        assert_eq!(
            status2,
            OperationStatus::NotFound,
            "Get::Search must return NotFound after deletion for {:?}",
            k
        );
    }

    cursor.close().unwrap();
}

///
/// Insert enough records to force at least one BIN split (N_KEYS = 50) then
/// verify that Get::Search finds every key.
#[test]
fn cursor_search_large_tree_exact_match() {
    let dir = TempDir::new().unwrap();
    let (_env, db) = open_env_and_db(&dir);

    const N_KEYS: u32 = 50;

    for i in 0..N_KEYS {
        let key_bytes = format!("{:08}", i).into_bytes();
        let val_bytes = i.to_be_bytes().to_vec();
        db.put(
            None,
            &DatabaseEntry::from_vec(key_bytes),
            &DatabaseEntry::from_vec(val_bytes),
        )
        .unwrap();
    }

    let mut cursor = db.open_cursor(None, None).unwrap();
    for i in 0..N_KEYS {
        let key_bytes = format!("{:08}", i).into_bytes();
        let expected_val = i.to_be_bytes().to_vec();

        let mut key = DatabaseEntry::from_vec(key_bytes.clone());
        let mut data = DatabaseEntry::new();
        let status =
            cursor.get(&mut key, &mut data, Get::Search, None).unwrap();
        assert_eq!(
            status,
            OperationStatus::Success,
            "Get::Search must succeed for key {:?} in large tree",
            key_bytes
        );
        assert_eq!(
            data.data(),
            expected_val.as_slice(),
            "data must match for key {:?}",
            key_bytes
        );
    }

    cursor.close().unwrap();
}

///
/// Insert many records (forcing splits), search for each one, delete it, then
/// verify subsequent searches return NotFound.
#[test]
fn cursor_search_large_tree_delete_and_search() {
    let dir = TempDir::new().unwrap();
    let (_env, db) = open_env_and_db(&dir);

    const N_KEYS: u32 = 50;

    for i in 0..N_KEYS {
        let key_bytes = format!("{:08}", i).into_bytes();
        let val_bytes = i.to_be_bytes().to_vec();
        db.put(
            None,
            &DatabaseEntry::from_vec(key_bytes),
            &DatabaseEntry::from_vec(val_bytes),
        )
        .unwrap();
    }

    let mut cursor = db.open_cursor(None, None).unwrap();

    for i in 0..N_KEYS {
        let key_bytes = format!("{:08}", i).into_bytes();

        let mut key = DatabaseEntry::from_vec(key_bytes.clone());
        let mut data = DatabaseEntry::new();
        let s = cursor.get(&mut key, &mut data, Get::Search, None).unwrap();
        assert_eq!(
            s,
            OperationStatus::Success,
            "Get::Search must succeed for key {:?} before deletion",
            key_bytes
        );

        cursor.delete().unwrap();

        let mut key2 = DatabaseEntry::from_vec(key_bytes.clone());
        let mut data2 = DatabaseEntry::new();
        let s2 = cursor.get(&mut key2, &mut data2, Get::Search, None).unwrap();
        assert_eq!(
            s2,
            OperationStatus::NotFound,
            "Get::Search must return NotFound after deletion for key {:?}",
            key_bytes
        );
    }

    cursor.close().unwrap();
}

/// Get::SearchGte finds the first key >= the
/// search key in a multi-BIN tree.
///
/// Sets key to the found key (which may be >=
/// the search key) and returns SUCCESS, or NOTFOUND if all keys are < query.
#[test]
fn cursor_search_range_finds_first_gte_key() {
    let dir = TempDir::new().unwrap();
    let (_env, db) = open_env_and_db(&dir);

    for k in [b"a".as_ref(), b"c", b"e", b"g"] {
        db.put(
            None,
            &DatabaseEntry::from_bytes(k),
            &DatabaseEntry::from_bytes(b"val"),
        )
        .unwrap();
    }

    let mut cursor = db.open_cursor(None, None).unwrap();

    // Exact match: SearchRange on "a" must find "a".
    let mut key = DatabaseEntry::from_bytes(b"a");
    let mut data = DatabaseEntry::new();
    let s = cursor.get(&mut key, &mut data, Get::SearchGte, None).unwrap();
    assert_eq!(s, OperationStatus::Success);
    assert_eq!(key.data(), b"a");

    // Range miss: "b" not in tree → should find "c".
    let mut key = DatabaseEntry::from_bytes(b"b");
    let mut data = DatabaseEntry::new();
    let s = cursor.get(&mut key, &mut data, Get::SearchGte, None).unwrap();
    assert_eq!(
        s,
        OperationStatus::Success,
        "SearchRange must find the first key >= 'b'"
    );
    assert_eq!(
        key.data(),
        b"c",
        "SearchRange on 'b' must return 'c' (the next present key)"
    );

    // Range beyond all keys: "z" → NotFound.
    let mut key = DatabaseEntry::from_bytes(b"z");
    let mut data = DatabaseEntry::new();
    let s = cursor.get(&mut key, &mut data, Get::SearchGte, None).unwrap();
    assert_eq!(
        s,
        OperationStatus::NotFound,
        "SearchRange beyond all keys must return NotFound"
    );

    cursor.close().unwrap();
}

/// Get::Search on an empty database returns NotFound.
#[test]
fn cursor_search_empty_database_returns_not_found() {
    let dir = TempDir::new().unwrap();
    let (_env, db) = open_env_and_db(&dir);

    let mut cursor = db.open_cursor(None, None).unwrap();
    let mut key = DatabaseEntry::from_bytes(b"anything");
    let mut data = DatabaseEntry::new();

    let status = cursor.get(&mut key, &mut data, Get::Search, None).unwrap();
    assert_eq!(
        status,
        OperationStatus::NotFound,
        "Get::Search on an empty database must return NotFound"
    );

    cursor.close().unwrap();
}

/// Get::SearchGte on an empty database returns NotFound.
#[test]
fn cursor_search_range_empty_database_returns_not_found() {
    let dir = TempDir::new().unwrap();
    let (_env, db) = open_env_and_db(&dir);

    let mut cursor = db.open_cursor(None, None).unwrap();
    let mut key = DatabaseEntry::from_bytes(b"anything");
    let mut data = DatabaseEntry::new();

    let status = cursor.get(&mut key, &mut data, Get::SearchGte, None).unwrap();
    assert_eq!(
        status,
        OperationStatus::NotFound,
        "Get::SearchGte on an empty database must return NotFound"
    );

    cursor.close().unwrap();
}

/// After tree splits, Get::Search still works
/// for all inserted keys.
///
/// : forces splits by inserting N = 80 records; after splits every key must
/// still be findable, exercising the multi-BIN tree traversal path.
#[test]
fn cursor_search_after_tree_splits_all_keys_findable() {
    let dir = TempDir::new().unwrap();
    let (_env, db) = open_env_and_db(&dir);

    const N: u32 = 80;

    for i in 0..N {
        let key_bytes = i.to_be_bytes().to_vec();
        let val_bytes = (i * 2).to_be_bytes().to_vec();
        db.put(
            None,
            &DatabaseEntry::from_vec(key_bytes),
            &DatabaseEntry::from_vec(val_bytes),
        )
        .unwrap();
    }

    assert_eq!(db.count().unwrap(), N as u64);

    let mut cursor = db.open_cursor(None, None).unwrap();

    for i in 0..N {
        let key_bytes = i.to_be_bytes().to_vec();
        let expected_val = (i * 2).to_be_bytes().to_vec();

        let mut key = DatabaseEntry::from_vec(key_bytes.clone());
        let mut data = DatabaseEntry::new();
        let status =
            cursor.get(&mut key, &mut data, Get::Search, None).unwrap();
        assert_eq!(
            status,
            OperationStatus::Success,
            "Get::Search must find key {:?} after tree splits",
            key_bytes
        );
        assert_eq!(
            data.data(),
            expected_val.as_slice(),
            "data must match for key {:?}",
            key_bytes
        );
    }

    cursor.close().unwrap();
}

// ─────────────────────────────────────────────────────────────────────────────
// Crash-recovery integrity tests (Keith Bostic / Margo Seltzer reviewer concern)
// ─────────────────────────────────────────────────────────────────────────────

/// Verify that all committed records survive a clean close + reopen (recovery
/// run on open).  This is the base case: write N records, close, reopen,
/// assert every key is still present with the correct value.
#[test]
fn recovery_committed_records_survive_reopen() {
    let dir = TempDir::new().unwrap();
    const N: u32 = 200;

    // Phase 1: write N records and close.
    {
        let (env, db) = open_env_and_db(&dir);
        for i in 0..N {
            let k = DatabaseEntry::from_vec(i.to_be_bytes().to_vec());
            let v = DatabaseEntry::from_vec((i * 3 + 7).to_be_bytes().to_vec());
            db.put(None, &k, &v).unwrap();
        }
        drop(db);
        drop(env);
    }

    // Phase 2: reopen (runs recovery) and verify all N records.
    {
        let (env, db) = open_env_and_db(&dir);
        assert_eq!(
            db.count().unwrap(),
            N as u64,
            "all committed records must survive reopen"
        );
        for i in 0..N {
            let k = DatabaseEntry::from_vec(i.to_be_bytes().to_vec());
            let mut v = DatabaseEntry::new();
            let status = db.get(None, &k, &mut v).unwrap();
            assert_eq!(
                status,
                OperationStatus::Success,
                "key {} must be present after recovery",
                i
            );
            assert_eq!(
                v.data(),
                (i * 3 + 7).to_be_bytes(),
                "value for key {} must be correct after recovery",
                i
            );
        }
        drop(db);
        drop(env);
    }
}

/// Verify that concurrent writes from multiple threads all survive close +
/// reopen: the Jepsen-style check — concurrent writes + recovery = all
/// committed data intact, no phantom records, no corrupted values.
#[test]
fn recovery_concurrent_writes_all_survive_reopen() {
    use std::sync::Arc;
    use std::thread;

    let dir = TempDir::new().unwrap();
    let dir_path = dir.path().to_path_buf();
    const THREADS: usize = 8;
    const PER_THREAD: u32 = 50;

    // Phase 1: concurrent writes from THREADS threads.
    {
        let (env, db) = open_env_and_db(&dir);
        let env = Arc::new(env);
        let db = Arc::new(db);

        let handles: Vec<_> = (0..THREADS)
            .map(|t| {
                let db = Arc::clone(&db);
                thread::spawn(move || {
                    for i in 0..PER_THREAD {
                        let global_key = (t as u32) * PER_THREAD + i;
                        let k = DatabaseEntry::from_vec(
                            global_key.to_be_bytes().to_vec(),
                        );
                        let v = DatabaseEntry::from_vec(
                            global_key.to_be_bytes().to_vec(),
                        );
                        db.put(None, &k, &v).unwrap();
                    }
                })
            })
            .collect();

        for h in handles {
            h.join().unwrap();
        }
        drop(db);
        drop(env);
    }

    // Phase 2: reopen and verify all THREADS*PER_THREAD records.
    {
        let env_config = noxu_db::EnvironmentConfig::new(dir_path)
            .with_allow_create(false) // Must already exist.
            .with_transactional(true);
        let env = noxu_db::Environment::open(env_config).unwrap();
        // allow_create=true: the database name is not persisted in the log yet;
        // recovery transplants the recovered tree into the newly opened handle.
        let db = env
            .open_database(
                None,
                "test",
                &DatabaseConfig::new().with_allow_create(true),
            )
            .unwrap();

        let total = THREADS as u32 * PER_THREAD;
        assert_eq!(
            db.count().unwrap(),
            total as u64,
            "all {} records from {} threads must survive reopen",
            total,
            THREADS
        );

        for global_key in 0..total {
            let k = DatabaseEntry::from_vec(global_key.to_be_bytes().to_vec());
            let mut v = DatabaseEntry::new();
            let status = db.get(None, &k, &mut v).unwrap();
            assert_eq!(
                status,
                OperationStatus::Success,
                "key {} (from thread {}) must be present after recovery",
                global_key,
                global_key / PER_THREAD
            );
            assert_eq!(
                v.data(),
                global_key.to_be_bytes(),
                "value for key {} must be correct (no corruption)",
                global_key
            );
        }
    }
}

/// Verify that uncommitted transactions are correctly undone on reopen.
///
/// Write N committed records, then write M records inside a transaction that
/// is never committed (simulated by dropping the transaction without commit).
/// Reopen: recovery must undo the M uncommitted records.  Only N records
/// should be present.
#[test]
fn recovery_uncommitted_transactions_are_undone_on_reopen() {
    let dir = TempDir::new().unwrap();
    const N_COMMITTED: u32 = 50;
    const M_UNCOMMITTED: u32 = 20;

    // Phase 1: write N committed + M uncommitted records.
    {
        let (env, db) = open_env_and_db(&dir);

        // Committed writes (no txn = auto-commit).
        for i in 0..N_COMMITTED {
            let k = DatabaseEntry::from_vec(i.to_be_bytes().to_vec());
            let v = DatabaseEntry::from_vec(b"committed".to_vec());
            db.put(None, &k, &v).unwrap();
        }

        // Uncommitted writes: start a txn, write M records, then abort.
        let txn = env.begin_transaction(None).unwrap();
        for i in N_COMMITTED..N_COMMITTED + M_UNCOMMITTED {
            let k = DatabaseEntry::from_vec(i.to_be_bytes().to_vec());
            let v = DatabaseEntry::from_vec(b"uncommitted".to_vec());
            db.put(Some(&txn), &k, &v).unwrap();
        }
        txn.abort().unwrap(); // Explicitly abort — simulates crash scenario.

        drop(db);
        drop(env);
    }

    // Phase 2: reopen and verify only N_COMMITTED records.
    {
        let (_, db) = open_env_and_db(&dir);
        assert_eq!(
            db.count().unwrap(),
            N_COMMITTED as u64,
            "only {} committed records must be present; {} uncommitted must be absent",
            N_COMMITTED,
            M_UNCOMMITTED
        );

        // Committed records must be present.
        for i in 0..N_COMMITTED {
            let k = DatabaseEntry::from_vec(i.to_be_bytes().to_vec());
            let mut v = DatabaseEntry::new();
            assert_eq!(
                db.get(None, &k, &mut v).unwrap(),
                OperationStatus::Success,
                "committed key {} must be present",
                i
            );
        }

        // Uncommitted records must be absent.
        for i in N_COMMITTED..N_COMMITTED + M_UNCOMMITTED {
            let k = DatabaseEntry::from_vec(i.to_be_bytes().to_vec());
            let mut v = DatabaseEntry::new();
            assert_eq!(
                db.get(None, &k, &mut v).unwrap(),
                OperationStatus::NotFound,
                "aborted key {} must NOT be present after recovery",
                i
            );
        }
    }
}

/// Multi-database recovery: two named databases in one environment survive
/// reopen with all committed records intact and in separate key spaces.
///
/// Exercises the multi-DB routing in RecoveryManager — each database must
/// reconstruct its own B-tree from the shared log.
#[test]
fn recovery_multi_db_both_databases_survive_reopen() {
    let dir = TempDir::new().unwrap();
    const N: u32 = 20;

    // Phase 1: write to two separate databases and close cleanly.
    {
        let env_config = EnvironmentConfig::new(dir.path().to_path_buf())
            .with_allow_create(true)
            .with_transactional(true);
        let env = noxu_db::Environment::open(env_config).unwrap();
        let db_cfg = DatabaseConfig::new().with_allow_create(true);
        let db_alpha = env.open_database(None, "alpha", &db_cfg).unwrap();
        let db_beta = env.open_database(None, "beta", &db_cfg).unwrap();

        for i in 0u32..N {
            let k = DatabaseEntry::from_vec(i.to_be_bytes().to_vec());
            let v_alpha = DatabaseEntry::from_vec(b"alpha".to_vec());
            let v_beta = DatabaseEntry::from_vec(b"beta".to_vec());
            db_alpha.put(None, &k, &v_alpha).unwrap();
            db_beta.put(None, &k, &v_beta).unwrap();
        }

        drop(db_alpha);
        drop(db_beta);
        drop(env);
    }

    // Phase 2: reopen (runs recovery) and verify both databases are intact.
    // Use allow_create(true) consistent with other recovery tests; correctness
    // is verified via record counts and values, not by whether the DB opens.
    {
        let env_config = EnvironmentConfig::new(dir.path().to_path_buf())
            .with_allow_create(true)
            .with_transactional(true);
        let env = noxu_db::Environment::open(env_config).unwrap();
        let db_cfg = DatabaseConfig::new().with_allow_create(true);
        let db_alpha = env.open_database(None, "alpha", &db_cfg).unwrap();
        let db_beta = env.open_database(None, "beta", &db_cfg).unwrap();

        for i in 0u32..N {
            let k = DatabaseEntry::from_vec(i.to_be_bytes().to_vec());
            let mut v = DatabaseEntry::new();

            assert_eq!(
                db_alpha.get(None, &k, &mut v).unwrap(),
                OperationStatus::Success,
                "alpha: key {} missing after recovery",
                i
            );
            assert_eq!(v.data(), b"alpha", "alpha: key {} has wrong value", i);

            assert_eq!(
                db_beta.get(None, &k, &mut v).unwrap(),
                OperationStatus::Success,
                "beta: key {} missing after recovery",
                i
            );
            assert_eq!(v.data(), b"beta", "beta: key {} has wrong value", i);
        }

        assert_eq!(db_alpha.count().unwrap(), N as u64, "alpha count mismatch");
        assert_eq!(db_beta.count().unwrap(), N as u64, "beta count mismatch");
    }
}

/// UtilizationTracker wiring: log files grow on disk as records are written,
/// confirming that the write path routes through LogManager (and therefore the
/// UtilizationTracker receives write notifications from `count_new_log_entry`).
///
/// We verify this through observable disk state: after 20 puts + 10 deletes the
/// log directory must contain at least one `.ndb` file with non-trivial size,
/// proving the LogManager is active and the UtilizationTracker's wire-in point
/// (`count_new_log_entry` called from LogManager::log()) has been exercised.
#[test]
fn utilization_tracker_write_path_produces_log_entries_on_disk() {
    let dir = TempDir::new().unwrap();
    let env_config = EnvironmentConfig::new(dir.path().to_path_buf())
        .with_allow_create(true)
        .with_transactional(true);
    let env = noxu_db::Environment::open(env_config).unwrap();
    let db_cfg = DatabaseConfig::new().with_allow_create(true);
    let db = env.open_database(None, "util_test", &db_cfg).unwrap();

    // Write 20 records, delete 10 — each operation produces a log entry that
    // must pass through LogManager::log() where count_new_log_entry is called.
    for i in 0u8..20 {
        let k = DatabaseEntry::from_vec(vec![i]);
        let v = DatabaseEntry::from_vec(b"payload".to_vec());
        db.put(None, &k, &v).unwrap();
    }
    for i in 0u8..10 {
        let k = DatabaseEntry::from_vec(vec![i]);
        db.delete(None, &k).unwrap();
    }

    // Force the write buffer to disk before inspecting the directory.
    drop(db);
    drop(env);

    // At least one .ndb file must exist and have meaningful content.
    let log_files: Vec<_> = std::fs::read_dir(dir.path())
        .unwrap()
        .filter_map(|e| e.ok())
        .filter(|e| e.path().extension().map(|x| x == "ndb").unwrap_or(false))
        .collect();

    assert!(!log_files.is_empty(), "no .ndb log files found after writes");

    let total_log_bytes: u64 = log_files
        .iter()
        .map(|e| e.metadata().map(|m| m.len()).unwrap_or(0))
        .sum();

    // 30 operations × ~50 bytes/op minimum; anything under 500 bytes means the
    // log manager didn't actually write entries.
    assert!(
        total_log_bytes >= 500,
        "total log size {} bytes is suspiciously small — LogManager may not be wired",
        total_log_bytes
    );
}