foldpass-keepass-rs 0.1.10

Foldpass-maintained fork of the keepass (keepass-rs) KDBX parser, with fixes on top of upstream
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
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
//! Merging two versions of the same database.
//!
//! See [`Database::merge`][crate::Database::merge] for the entry point. The
//! types in this module describe what a merge changed, via the returned
//! [`MergeLog`].

use std::{
    collections::{BTreeMap, BTreeSet, HashSet},
    ops::Deref,
};

use chrono::NaiveDateTime;
use thiserror::Error;

use crate::{
    db::{CustomIconId, Entry, EntryId, Group, GroupId, GroupRef, History, MoveGroupError, Times},
    Database,
};

/// The kind of change a merge applied to an object.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum MergeEventType {
    /// The object existed only in the source and was created in the destination.
    Created,
    /// The object was deleted as a result of the merge.
    Deleted,
    /// The object was moved to a different location (parent group).
    LocationUpdated,
    /// The object's contents were updated from the source.
    Updated,
}

/// The object a [`MergeEvent`] applies to.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum MergeEventTarget {
    /// An entry, identified by its UUID.
    Entry(EntryId),
    /// A group, identified by its UUID.
    Group(GroupId),
    /// A custom icon, identified by its UUID.
    Icon(CustomIconId),
}

/// A single change applied to the destination database during a merge.
#[derive(Debug, Clone)]
pub struct MergeEvent {
    /// The object that was changed.
    pub target: MergeEventTarget,
    /// The kind of change that was applied.
    pub event_type: MergeEventType,
}

/// Errors while merge two databases
#[derive(Error, Debug)]
#[non_exhaustive]
pub enum MergeError {
    /// Two entries with the same UUID have the same modification time but different contents.
    #[error("Entries with UUID {0} have the same modification time but have diverged.")]
    EntryModificationTimeNotUpdated(EntryId),

    /// Two groups with the same UUID have the same modification time but different contents.
    #[error("Groups with UUID {0} have the same modification time but have diverged.")]
    GroupModificationTimeNotUpdated(GroupId),

    /// An entry has two history items sharing the same timestamp, so their order is ambiguous.
    #[error("Found history entries with the same timestamp ({0}) for entry {1}.")]
    DuplicateHistoryEntries(NaiveDateTime, EntryId),

    /// A group could not be moved to its merged location.
    #[error(transparent)]
    MoveGroupError(#[from] MoveGroupError),
}

/// Record of everything a merge changed, returned by [`Database::merge`].
#[derive(Debug, Default, Clone)]
pub struct MergeLog {
    /// Non-fatal issues encountered during the merge.
    pub warnings: Vec<String>,
    /// The changes that were applied to the destination database.
    pub events: Vec<MergeEvent>,
}

impl Database {
    /// Merge a database with another version of the same database and a common ancestor.
    ///
    /// Providing the common ancestor allows the merge to distinguish one-sided changes from true
    /// conflicts:
    ///
    /// - Changed in `self` only → keep `self` (no conflict).
    /// - Changed in `other` only → take `other` (no conflict).
    /// - Changed identically in both → trivially resolved.
    /// - Changed differently in both → real conflict; resolved by newest-wins and surfaced in
    ///   [`MergeLog::warnings`].
    ///
    /// Use [`Database::merge`] when no common ancestor is available; it falls back to two-way
    /// (newest-wins) semantics by treating every object as changed since an empty ancestor.
    pub fn merge_with_ancestor(
        &mut self,
        other: &Database,
        ancestor: &Database,
    ) -> Result<MergeLog, MergeError> {
        let mut log = MergeLog::default();
        merge_icons(self, other, ancestor, &mut log)?;
        merge_groups(self, other, ancestor, &mut log)?;
        Ok(log)
    }

    /// Merge a database with another version of the same database, applying the changes to self.
    ///
    /// This is a two-way merge that uses timestamps alone to resolve conflicts. When a common
    /// ancestor is available, [`Database::merge_with_ancestor`] can resolve one-sided changes
    /// automatically and surface true conflicts more precisely.
    pub fn merge(&mut self, other: &Database) -> Result<MergeLog, MergeError> {
        self.merge_with_ancestor(other, &Database::new())
    }
}

/// Get the last update time (modification or location change) of a group, considering its entries and subgroups.
fn get_last_update(group: GroupRef<'_>) -> Option<NaiveDateTime> {
    let last_update = group.times.last_modification.or(group.times.location_changed);

    group
        .entries()
        .filter_map(|e| e.times.last_modification.or(e.times.location_changed))
        .chain(
            group
                .groups()
                .filter_map(|g| g.times.last_modification.or(g.times.location_changed)),
        )
        .chain(last_update)
        .max()
}

/// Merge groups from `source` into `dest`, appending to a log of the merge process.
///
/// NOTE: this function will also call `merge_entries` to handle entries within the groups.
fn merge_groups(
    dest_db: &mut Database,
    source_db: &Database,
    base_db: &Database,
    log: &mut MergeLog,
) -> Result<(), MergeError> {
    let dest_groups = dest_db.groups.keys().cloned().collect::<HashSet<_>>();
    let source_groups = source_db.groups.keys().cloned().collect::<HashSet<_>>();

    // Handle groups that exist only in source and might need to be added.
    let mut groups_to_add = HashSet::new();
    for &id in source_groups.difference(&dest_groups) {
        #[allow(clippy::unwrap_used)] // id is guaranteed to exist
        let source = source_db.group(id).unwrap();

        // was the group deleted in dest?
        if let Some(deletion_time) = dest_db.deleted_objects.get(&id.uuid()) {
            // get the last modification time of the group in source.
            let source_last_update = get_last_update(source);

            // compare deletion time and last update time to decide whether to re-add the group
            match (deletion_time, source_last_update) {
                (Some(deletion_time), Some(source_last_update)) => {
                    // if the group was deleted after its last modification time in source,
                    // do not re-add it, otherwise we can re-add the group
                    if *deletion_time >= source_last_update {
                        continue;
                    }
                }
                (Some(_), None) => {
                    // blank last update time in source - do not re-add the group
                    continue;
                }
                (None, Some(_)) => {
                    // blank deletion time is probably older than concrete update time - re-add the
                    // group
                }
                (None, None) => {
                    // both times are blank - do not re-add the group
                    continue;
                }
            }
        }

        groups_to_add.insert(id);
    }

    // actually add groups from groups_to_add. Use a stack to ensure that parent groups are added as needed
    let mut add_stack = Vec::new();
    loop {
        // refill the stack if it's empty
        if add_stack.is_empty() {
            if let Some(&next) = groups_to_add.iter().next() {
                // refill the stack with an arbitrary group to re-add
                add_stack.push(next);
                groups_to_add.remove(&next);
            } else {
                // no more groups to re-add
                break;
            }
        }

        // get the current group from the stack
        #[allow(clippy::expect_used)] // stack is guaranteed to be non-empty
        let &id = add_stack.last().expect("non-empty queue");

        // get the desired parent of the group to be re-added
        #[allow(clippy::expect_used)] // id is guaranteed to exist in source
        let source = source_db.group(id).expect("source group exists");

        #[allow(clippy::expect_used)] // this would be a severe issue with the algorithm
        let parent_id = source.parent().expect("cannot re-add root").id();

        // does the parent exist in dest?
        if let Some(mut parent) = dest_db.group_mut(parent_id) {
            // yes - re-add the group
            #[allow(clippy::expect_used)] // id was selected from source_groups.difference(dest_groups)
            let mut dest_group = parent
                .add_group_with_id(id)
                .expect("group to be re-added should not exist yet");
            dest_group.times = source.times.clone();
            dest_group.name = source.name.clone();
            dest_group.notes = source.notes.clone();
            dest_group.icon = source.icon.clone();
            dest_group.custom_data = source.custom_data.clone();
            dest_group.is_expanded = source.is_expanded;
            dest_group.default_autotype_sequence = source.default_autotype_sequence.clone();
            dest_group.enable_autotype = source.enable_autotype;
            dest_group.enable_searching = source.enable_searching;
            dest_group.last_top_visible_entry = source.last_top_visible_entry;

            log.events.push(MergeEvent {
                target: MergeEventTarget::Group(id),
                event_type: MergeEventType::Created,
            });

            // success - remove the current item from the stack (it was already removed from the set)
            add_stack.pop();
        } else {
            // the parent does not exist yet - add it to the stack to be re-added first
            add_stack.push(parent_id);

            // since we will deal with the parent now, it doesn't need to be handled later
            groups_to_add.remove(&parent_id);
        }
    }

    // Handle groups that exist only in destination. These groups might need to be deleted.
    let mut to_delete = Vec::new();
    for &id in dest_groups.difference(&source_groups) {
        #[allow(clippy::unwrap_used)] // id is guaranteed to exist
        let dest = dest_db.group_mut(id).unwrap();

        // was the group deleted in source?
        if let Some(deletion_time) = source_db.deleted_objects.get(&id.uuid()) {
            let dest_last_updated = get_last_update(dest.as_ref());
            if let (Some(deletion_time), Some(dest_last_updated)) = (deletion_time, dest_last_updated) {
                // if the group was deleted and then later modified in dest, do not delete it
                if *deletion_time < dest_last_updated {
                    continue;
                }
            }

            // queue the deletion so that all subgroups will also emit a deletion event
            to_delete.push(id);
            dest_db.deleted_objects.insert(id.uuid(), *deletion_time);

            log.events.push(MergeEvent {
                target: MergeEventTarget::Group(id),
                event_type: MergeEventType::Deleted,
            });
        }
    }

    // perform the entry merges now that all groups that need adding are added but the groups that
    // need deleting still haven't been deleted, so that the entries can still be accessed and
    // generate events
    merge_entries(dest_db, source_db, base_db, log)?;

    // perform all group deletions
    while let Some(id) = to_delete.pop() {
        if let Some(group) = dest_db.group_mut(id) {
            group.remove();
        }
    }

    // re-compute the group set after additions and deletions
    let dest_groups = dest_db.groups.keys().cloned().collect::<HashSet<_>>();

    // Handle groups that exist in both source and destination.
    let mut moves = Vec::new();
    let root_id = dest_db.root().id();
    for &id in dest_groups.intersection(&source_groups) {
        #[allow(clippy::unwrap_used)] // id is guaranteed to exist
        let mut dest = dest_db.group_mut(id).unwrap();

        #[allow(clippy::unwrap_used)] // id is guaranteed to exist
        let source = source_db.group(id).unwrap();

        let dest_parent_id = dest.as_ref().parent().map(|p| p.id());
        let source_parent_id = source.parent().map(|p| p.id());

        // was the group moved?
        if dest_parent_id != source_parent_id {
            let dest_location_changed = dest.times.location_changed;
            let source_location_changed = source.times.location_changed;

            if let (Some(dlc), Some(slc)) = (dest_location_changed, source_location_changed) {
                if slc > dlc {
                    // the source group has been moved more recently than the destination group.
                    // try to move the destination group to the new location.

                    let Some(parent_id) = source.parent().map(|p| p.id()) else {
                        log.warnings.push(format!("Cannot move root group {}", id,));
                        continue;
                    };

                    if !dest_groups.contains(&parent_id) {
                        log.warnings.push(format!(
                            "Cannot move group {} to group {} because the group does not exist in the destination database.",
                            id,
                            parent_id,
                        ));
                        continue;
                    };

                    // to avoid creating cycles in situations where two groups swap their parent-child
                    // relationship, move all groups to root first and then to their final destination
                    moves.push((id, parent_id));
                    dest.move_to(root_id)?;
                    dest.times.location_changed = Some(slc);

                    log.events.push(MergeEvent {
                        target: MergeEventTarget::Group(id),
                        event_type: MergeEventType::LocationUpdated,
                    });
                }
            } else {
                log.warnings.push(format!(
                    "Cannot determine which group {} move is more recent because one of the groups does not have a location changed timestamp.",
                    id,
                ));
            }
        }

        let dest_last_modification = dest.times.last_modification.unwrap_or_else(|| {
            log.warnings.push(format!(
                "Destination group {} did not have a last modification timestamp",
                id
            ));
            Times::now()
        });

        let source_last_modification = source.times.last_modification.unwrap_or_else(|| {
            log.warnings.push(format!(
                "Source group {} did not have a last modification timestamp",
                id
            ));
            Times::epoch()
        });

        if dest_last_modification == source_last_modification {
            if have_groups_diverged(&dest, &source) {
                // This should never happen.
                //
                // A group was updated without updating the last modification timestamp.
                return Err(MergeError::GroupModificationTimeNotUpdated(id));
            }
            continue;
        }

        // Three-way check: compare both sides against the common ancestor to distinguish
        // one-sided changes (auto-resolved) from true conflicts (warned and newest-wins).
        let base_last_modification = base_db.group(id).and_then(|g| g.times.last_modification);
        let dest_changed = base_last_modification.map_or(true, |b| dest_last_modification > b);
        let source_changed = base_last_modification.map_or(true, |b| source_last_modification > b);

        if !source_changed {
            // source did not change since the common ancestor; keep dest
            continue;
        }

        if dest_changed && have_groups_diverged(&dest, &source) && base_last_modification.is_some() {
            // both sides changed since the ancestor and content diverged — real conflict
            log.warnings.push(format!(
                "Group {id} was modified in both databases since the common ancestor. \
                 Resolving by keeping the most recently modified version.",
            ));
        }

        if dest_last_modification > source_last_modification {
            // The destination group is more recent than the source group. Nothing to do.
            continue;
        }

        // The source group is more recent than the destination group. Update dest with source.
        dest.name = source.name.clone();
        dest.notes = source.notes.clone();
        dest.icon = source.icon.clone();
        dest.custom_data = source.custom_data.clone();
        dest.times.last_modification = source.times.last_modification.or(dest.times.last_modification);
        dest.is_expanded = source.is_expanded;
        dest.default_autotype_sequence = source.default_autotype_sequence.clone();
        dest.enable_autotype = source.enable_autotype;
        dest.enable_searching = source.enable_searching;
        dest.last_top_visible_entry = source.last_top_visible_entry;

        log.events.push(MergeEvent {
            target: MergeEventTarget::Group(id),
            event_type: MergeEventType::Updated,
        });
    }

    // perform all the moves that were queued up
    for (group_id, parent_id) in moves {
        #[allow(clippy::unwrap_used)] // group_id and parent_id are guaranteed to exist
        let mut group = dest_db.group_mut(group_id).unwrap();
        group.move_to(parent_id)?;
    }

    Ok(())
}

/// Merge entries from `source` into `dest`, appending to a log of the merge process.
fn merge_entries(
    dest_db: &mut Database,
    source_db: &Database,
    base_db: &Database,
    log: &mut MergeLog,
) -> Result<(), MergeError> {
    let dest_entries = dest_db.entries.keys().cloned().collect::<HashSet<_>>();
    let source_entries = source_db.entries.keys().cloned().collect::<HashSet<_>>();

    // Handle entries that exist only in source and might need to be added.
    for &id in source_entries.difference(&dest_entries) {
        #[allow(clippy::unwrap_used)] // id is guaranteed to exist
        let source_entry = source_db.entry(id).unwrap();

        // was the entry deleted in dest?
        if let Some(deletion_time) = dest_db.deleted_objects.get(&id.uuid()) {
            // get the last modification or location change time in source.
            let source_update_time = source_entry
                .times
                .last_modification
                .or(source_entry.times.location_changed);

            match (deletion_time, source_update_time) {
                (Some(deletion_time), Some(source_update_time)) => {
                    // if the entry was deleted after its last modification time in source,
                    // do not re-add it
                    if *deletion_time >= source_update_time {
                        continue;
                    }
                }
                (Some(_), None) => {
                    // blank last update time in source - do not re-add the entry
                    continue;
                }
                (None, Some(_)) => {
                    // blank deletion time is probably older than concrete update time - re-add the
                    // entry
                }
                (None, None) => {
                    // both times are blank - do not re-add the entry
                    continue;
                }
            }

            // otherwise, we can re-add the entry
        }

        let parent_id = source_entry.parent().id();

        let Some(mut parent) = dest_db.group_mut(parent_id) else {
            log.warnings.push(format!(
                "Cannot add entry {} because its parent group {} does not exist in the destination database.",
                id, parent_id,
            ));
            continue;
        };

        #[allow(clippy::expect_used)] // id was selected from source_entries.difference(dest_entries)
        let mut entry = parent
            .add_entry_with_id(id)
            .expect("entry to be (re-)added should not exist yet");

        *entry = source_entry.deref().clone();

        log.events.push(MergeEvent {
            target: MergeEventTarget::Entry(id),
            event_type: MergeEventType::Created,
        });
    }

    // Handle entries that exist only in destination. These entries might need to be deleted.
    for &id in dest_entries.difference(&source_entries) {
        #[allow(clippy::unwrap_used)] // id is guaranteed to exist
        let dest_entry = dest_db.entry_mut(id).unwrap();

        // was the entry deleted in source?
        if let Some(deletion_time) = source_db.deleted_objects.get(&id.uuid()) {
            let dest_update_time = dest_entry
                .times
                .last_modification
                .or(dest_entry.times.location_changed);

            if let (Some(deletion_time), Some(dest_update_time)) = (deletion_time, dest_update_time) {
                // if the entry was deleted and then later modified in dest, do not delete it
                if *deletion_time < dest_update_time {
                    continue;
                }
            }

            dest_entry.remove();
            dest_db.deleted_objects.insert(id.uuid(), *deletion_time);

            log.events.push(MergeEvent {
                target: MergeEventTarget::Entry(id),
                event_type: MergeEventType::Deleted,
            });
        }
    }

    // Handle entries that exist in both source and destination.
    for &id in dest_entries.intersection(&source_entries) {
        #[allow(clippy::unwrap_used)] // id is guaranteed to exist in both dest and source
        let mut dest_entry = dest_db.entry_mut(id).unwrap();

        #[allow(clippy::unwrap_used)] // id is guaranteed to exist in both dest and source
        let source_entry = source_db.entry(id).unwrap();

        let dest_parent_id = dest_entry.as_ref().parent().id();
        let source_parent_id = source_entry.parent().id();

        // has the entry moved?
        if dest_parent_id != source_parent_id {
            // which move is more recent?
            let source_location_changed = source_entry.times.location_changed;
            let dest_location_changed = dest_entry.times.location_changed;
            if let (Some(slc), Some(dlc)) = (source_location_changed, dest_location_changed) {
                if slc > dlc {
                    // the source entry has been moved more recently than the destination entry.
                    // try to move the destination entry to the new location.

                    if dest_entry.move_to(source_parent_id).is_ok() {
                        log.events.push(MergeEvent {
                            target: MergeEventTarget::Entry(id),
                            event_type: MergeEventType::LocationUpdated,
                        });
                        dest_entry.times.location_changed = Some(slc);
                    } else {
                        log.warnings.push(format!(
                            "Cannot move entry {} to group {} because the group does not exist in the destination database.",
                            id,
                            source_parent_id,
                        ));
                    }
                }
            } else {
                log.warnings.push(format!(
                    "Cannot determine which entry {} move is more recent because one of the entries does not have a location changed timestamp.",
                    id,
                ));
            }
        }

        let source_last_modification = source_entry.times.last_modification.unwrap_or_else(|| {
            log.warnings.push(format!(
                "Source entry {} did not have a last modification timestamp",
                id
            ));
            Times::epoch()
        });

        let dest_last_modification = dest_entry.times.last_modification.unwrap_or_else(|| {
            log.warnings.push(format!(
                "Destination entry {} did not have a last modification timestamp",
                id
            ));
            Times::now()
        });

        if dest_last_modification == source_last_modification {
            if have_entries_diverged(&dest_entry, &source_entry) {
                // This should never happen.
                //
                // An entry was updated without updating the last modification timestamp.
                return Err(MergeError::EntryModificationTimeNotUpdated(id));
            }
            continue;
        }

        // Three-way check: compare both sides against the common ancestor to distinguish
        // one-sided changes (auto-resolved) from true conflicts (warned and newest-wins).
        let base_last_modification = base_db.entry(id).and_then(|e| e.times.last_modification);
        let dest_changed = base_last_modification.map_or(true, |b| dest_last_modification > b);
        let source_changed = base_last_modification.map_or(true, |b| source_last_modification > b);

        if !source_changed {
            // source did not change since the common ancestor; keep dest
            continue;
        }

        if dest_changed && have_entries_diverged(&dest_entry, &source_entry) && base_last_modification.is_some()
        {
            // both sides changed since the ancestor and content diverged — real conflict
            log.warnings.push(format!(
                "Entry {id} was modified in both databases since the common ancestor. \
                 Resolving by keeping the most recently modified version.",
            ));
        }

        let source_history = source_entry.history.clone().unwrap_or_else(|| {
            log.warnings.push(format!("Source entry {} had no history.", id));
            History::default()
        });

        let dest_history = dest_entry.history.clone().unwrap_or_else(|| {
            log.warnings
                .push(format!("Destination entry {} had no history.", id));
            History::default()
        });

        let mut merged_history = merge_history(&dest_history, &source_history, log)?;
        let merged_location_timestamp = dest_entry
            .times
            .location_changed
            .or(source_entry.times.location_changed);

        if source_last_modification > dest_last_modification {
            // add the previous dest entry to history if it has diverged
            if let Some(last_history_entry) = merged_history.entries.first() {
                if have_entries_diverged(&dest_entry, last_history_entry) {
                    let mut dest_entry_for_history = dest_entry.deref().clone();
                    dest_entry_for_history.history = None;
                    merged_history.add_entry(dest_entry_for_history);
                }
            }

            // The source entry is more recent than the destination entry. Replace dest with source.
            dest_entry.times.last_modification = source_entry.times.last_modification;
            dest_entry.fields = source_entry.fields.clone();
            dest_entry.autotype = source_entry.autotype.clone();
            dest_entry.tags = source_entry.tags.clone();
            dest_entry.custom_data = source_entry.custom_data.clone();
            dest_entry.icon = source_entry.icon.clone();
            dest_entry.foreground_color = source_entry.foreground_color.clone();
            dest_entry.background_color = source_entry.background_color.clone();
            dest_entry.override_url = source_entry.override_url.clone();
            dest_entry.quality_check = source_entry.quality_check;

            // TODO: attachments and custom_icons_id

            log.events.push(MergeEvent {
                target: MergeEventTarget::Entry(id),
                event_type: MergeEventType::Updated,
            });
        } else if have_entries_diverged(&dest_entry, &source_entry) {
            // The destination entry is more recent and wins — but unlike the
            // branch above, the source's losing state is in NEITHER side's
            // history (a tracked edit records the PRE-edit state, never the
            // live one), so without this it would survive nowhere. Skip only
            // when the newest history row already equals it.
            let already_recorded = merged_history
                .entries
                .first()
                .is_some_and(|h| !have_entries_diverged(&source_entry, h));
            if !already_recorded {
                let mut source_entry_for_history = source_entry.deref().clone();
                source_entry_for_history.history = None;
                merged_history.add_entry(source_entry_for_history);
            }
        }

        dest_entry.history = Some(merged_history);
        dest_entry.times.location_changed = merged_location_timestamp;
    }

    Ok(())
}

/// Merge two histories together, returning the merged history.
fn merge_history(dest: &History, source: &History, log: &mut MergeLog) -> Result<History, MergeError> {
    let mut entries: Vec<Entry> = Vec::new();

    let mut entries_dest: Vec<Entry> = dest.entries.to_vec();
    let mut entries_source: Vec<Entry> = source.entries.to_vec();

    for e in entries_dest.iter_mut() {
        if e.times.last_modification.is_none() {
            log.warnings.push(format!(
                "Destination history entry {} did not have a last modification timestamp",
                e.id()
            ));
            e.times.last_modification = Some(Times::epoch());
        }
    }

    for e in entries_source.iter_mut() {
        if e.times.last_modification.is_none() {
            log.warnings.push(format!(
                "Source history entry {} did not have a last modification timestamp",
                e.id()
            ));
            e.times.last_modification = Some(Times::epoch());
        }
    }

    entries_dest.sort_by_key(|e| e.times.last_modification);
    entries_source.sort_by_key(|e| e.times.last_modification);

    // perform a merge of both histories, which are sorted by last modification time.
    //
    // this code has a lot of unwraps but they are all checked - entry lists are checked for
    // emptiness, and times are made not-none before sorting, so the unwraps should never panic.
    #[allow(clippy::unwrap_used)]
    loop {
        match (entries_dest.is_empty(), entries_source.is_empty()) {
            (false, false) => {
                // Both histories have entries left to process.
                let dest_entry = entries_dest.last().unwrap();
                let source_entry = entries_source.last().unwrap();

                let dest_time = dest_entry.times.last_modification.unwrap();

                let source_time = source_entry.times.last_modification.unwrap();

                if dest_time > source_time {
                    entries.push(entries_dest.pop().unwrap());
                } else if source_time > dest_time {
                    entries.push(entries_source.pop().unwrap());
                } else if have_entries_diverged(dest_entry, source_entry) {
                    log.warnings.push(format!(
                        "History entries for {} have the same modification timestamp {} but have diverged.",
                        dest_entry.id(),
                        source_time,
                    ));

                    // Both entries have the same timestamp but are different.
                    entries.push(entries_dest.pop().unwrap());
                    entries.push(entries_source.pop().unwrap());
                } else {
                    // The entries are the same, so we can just take one of them.
                    entries.push(entries_dest.pop().unwrap());
                    entries_source.pop();
                }
            }

            (true, false) => {
                // Only the source history has entries left to process - just take them all.
                entries.push(entries_source.pop().unwrap());
            }
            (false, true) => {
                // Only the destination history has entries left to process - just take them all.
                entries.push(entries_dest.pop().unwrap());
            }
            (true, true) => break,
        }
    }

    Ok(History { entries })
}

/// Merge custom icons, returning the merged history
fn merge_icons(
    dest_db: &mut Database,
    source_db: &Database,
    base_db: &Database,
    log: &mut MergeLog,
) -> Result<(), MergeError> {
    let dest_icons = dest_db.custom_icons.keys().cloned().collect::<HashSet<_>>();
    let source_icons = source_db.custom_icons.keys().cloned().collect::<HashSet<_>>();

    // Handle icons that exist only in source and might need to be added.
    for &id in source_icons.difference(&dest_icons) {
        #[allow(clippy::unwrap_used)] // id is guaranteed to exist
        let source_icon = source_db.custom_icons.get(&id).unwrap();

        if let Some(deletion_time) = dest_db.deleted_objects.get(&id.uuid()) {
            let source_last_modification = source_icon.last_modification_time;

            if let (Some(deletion_time), Some(source_last_modification)) =
                (deletion_time, source_last_modification)
            {
                // if the icon was deleted after its last modification time in source,
                // do not re-add it
                if *deletion_time >= source_last_modification {
                    continue;
                }
            } else if deletion_time.is_some() && source_last_modification.is_none() {
                // blank last modification time in source - do not re-add the icon
                continue;
            } else if deletion_time.is_none() && source_last_modification.is_some() {
                // blank deletion time is probably older than concrete update time - re-add the icon
            } else {
                // both times are blank - do not re-add the icon
                continue;
            }
        }

        dest_db.custom_icons.insert(id, source_icon.clone());

        log.events.push(MergeEvent {
            target: MergeEventTarget::Icon(id),
            event_type: MergeEventType::Created,
        });
    }

    // Handle icons that exist only in destination. These icons might need to be deleted.
    for &id in dest_icons.difference(&source_icons) {
        #[allow(clippy::unwrap_used)] // id is guaranteed to exist
        let dest_icon = dest_db.custom_icons.get(&id).unwrap();

        if let Some(deletion_time) = source_db.deleted_objects.get(&id.uuid()) {
            let dest_last_modification = dest_icon.last_modification_time;

            if let (Some(deletion_time), Some(dest_last_modification)) = (deletion_time, dest_last_modification)
            {
                // if the icon was deleted and then later modified in dest, do not delete it
                if *deletion_time < dest_last_modification {
                    continue;
                }
            }

            dest_db.custom_icons.remove(&id);
            dest_db.deleted_objects.insert(id.uuid(), *deletion_time);

            log.events.push(MergeEvent {
                target: MergeEventTarget::Icon(id),
                event_type: MergeEventType::Deleted,
            });
        }
    }

    for &id in dest_icons.intersection(&source_icons) {
        #[allow(clippy::unwrap_used)] // id is guaranteed to exist in both dest and source
        let dest_icon = dest_db.custom_icons.get(&id).unwrap();

        #[allow(clippy::unwrap_used)] // id is guaranteed to exist in both dest and source
        let source_icon = source_db.custom_icons.get(&id).unwrap();

        let dest_last_modification = dest_icon.last_modification_time.unwrap_or_else(|| {
            log.warnings.push(format!(
                "Destination custom icon {} did not have a last modification timestamp",
                id
            ));
            Times::epoch()
        });

        let source_last_modification = source_icon.last_modification_time.unwrap_or_else(|| {
            log.warnings.push(format!(
                "Source custom icon {} did not have a last modification timestamp",
                id
            ));
            Times::epoch()
        });

        if dest_last_modification == source_last_modification {
            if have_icons_diverged(dest_icon, source_icon) {
                log.warnings.push(format!(
                    "Custom icons with UUID {} have the same modification time but have diverged.",
                    id,
                ));
            }
            continue;
        }

        // Three-way check: compare both sides against the common ancestor to distinguish
        // one-sided changes (auto-resolved) from true conflicts (warned and newest-wins).
        let base_last_modification = base_db
            .custom_icons
            .get(&id)
            .and_then(|i| i.last_modification_time)
            .unwrap_or(Times::epoch());
        let dest_changed = dest_last_modification > base_last_modification;
        let source_changed = source_last_modification > base_last_modification;

        if !source_changed {
            // source did not change since the common ancestor; keep dest
            continue;
        }

        if dest_changed && have_icons_diverged(dest_icon, source_icon) && base_db.custom_icons.contains_key(&id)
        {
            // both sides changed since the ancestor and content diverged — real conflict
            log.warnings.push(format!(
                "Custom icon {id} was modified in both databases since the common ancestor. \
                 Resolving by keeping the most recently modified version.",
            ));
        }

        if dest_last_modification > source_last_modification {
            // The destination icon is more recent than the source icon. Nothing to do.
            continue;
        }

        // The source icon is more recent than the destination icon. Update dest with source.
        dest_db.custom_icons.insert(id, source_icon.clone());

        log.events.push(MergeEvent {
            target: MergeEventTarget::Icon(id),
            event_type: MergeEventType::Updated,
        });
    }

    Ok(())
}

/// The group content the divergence check compares: name, non-empty notes,
/// and tags. Anything else may differ between serializers without a timestamp
/// change and must not read as divergence.
fn group_content(g: &Group) -> (&str, Option<&str>, BTreeSet<&str>) {
    (
        g.name.as_str(),
        g.notes.as_deref().filter(|n| !n.is_empty()),
        g.tags.iter().map(String::as_str).collect(),
    )
}

/// Check if two groups are dissimilar in content.
fn have_groups_diverged(a: &Group, b: &Group) -> bool {
    group_content(a) != group_content(b)
}

/// The entry content the divergence check compares: non-empty field values
/// (an empty field equals an absent one; protection is not content) and tags.
fn entry_content(e: &Entry) -> (BTreeMap<&str, &str>, BTreeSet<&str>) {
    (
        e.fields
            .iter()
            .filter(|(_, v)| !v.get().is_empty())
            .map(|(k, v)| (k.as_str(), v.get().as_str()))
            .collect(),
        e.tags.iter().map(String::as_str).collect(),
    )
}

/// Check if two entries are dissimilar in content.
fn have_entries_diverged(a: &Entry, b: &Entry) -> bool {
    entry_content(a) != entry_content(b)
}

/// Check if two custom icons are dissimilar in content: name and image data.
/// The entry/group sets are derived back-references, not content.
fn have_icons_diverged(a: &crate::db::CustomIcon, b: &crate::db::CustomIcon) -> bool {
    a.name != b.name || a.data != b.data
}

#[allow(clippy::indexing_slicing, clippy::unwrap_used, clippy::expect_used)]
#[cfg(test)]
mod merge_tests {
    use uuid::uuid;

    use super::{MergeError, MergeEventType};
    use crate::db::{fields, AutoType, DataTransferObfuscation, EntryId, GroupId, History, Icon, Times, Value};
    use crate::Database;

    const ROOT_GROUP_ID: GroupId = GroupId::from_uuid(uuid!("00000000-0000-0000-0000-000000000001"));
    const GROUP1_ID: GroupId = GroupId::from_uuid(uuid!("00000000-0000-0000-0000-000000000002"));
    const GROUP2_ID: GroupId = GroupId::from_uuid(uuid!("00000000-0000-0000-0000-000000000003"));
    const SUBGROUP1_ID: GroupId = GroupId::from_uuid(uuid!("00000000-0000-0000-0000-000000000004"));
    const SUBGROUP2_ID: GroupId = GroupId::from_uuid(uuid!("00000000-0000-0000-0000-000000000005"));
    const ENTRY1_ID: EntryId = EntryId::from_uuid(uuid!("00000000-0000-0000-0000-000000000006"));
    const ENTRY2_ID: EntryId = EntryId::from_uuid(uuid!("00000000-0000-0000-0000-000000000007"));

    /// Build up an example database for testing
    ///
    /// The database structure is as follows:
    ///
    /// root (ROOT_GROUP_ID)
    /// ├── entry1 (ENTRY1_ID)
    /// ├── group1 (GROUP1_ID)
    /// │   └── subgroup1 (SUBGROUP1_ID)
    /// │       └── entry2 (ENTRY2_ID)
    /// └── group2 (GROUP2_ID)
    ///    └── subgroup2 (SUBGROUP2_ID)
    ///
    fn create_test_database() -> Database {
        let mut db = Database::new_with_root_id(ROOT_GROUP_ID);

        // build up root -> group1 -> subgroup1 -> entry2
        db.root_mut()
            .add_group_with_id(GROUP1_ID)
            .unwrap()
            .edit(|g| g.name = "group1".to_string())
            .add_group_with_id(SUBGROUP1_ID)
            .unwrap()
            .edit(|sg| sg.name = "subgroup1".to_string())
            .add_entry_with_id(ENTRY2_ID)
            .unwrap()
            .edit(|e| e.set_unprotected("Title", "entry2"));

        // build up root -> group2 -> subgroup2
        db.root_mut()
            .add_group_with_id(GROUP2_ID)
            .unwrap()
            .edit(|g| g.name = "group2".to_string())
            .add_group_with_id(SUBGROUP2_ID)
            .unwrap()
            .edit(|sg| sg.name = "subgroup2".to_string());

        // Placing the first entry in the root group
        db.root_mut()
            .add_entry_with_id(ENTRY1_ID)
            .unwrap()
            .edit(|e| e.set_unprotected("Title", "entry1"));

        db
    }

    /// sleep for 1 second to ensure different timestamps
    fn sleep() {
        std::thread::sleep(std::time::Duration::from_secs(1));
    }

    fn assert_history_ordered(history: &History) {
        let mut last_modification_time: Option<&chrono::NaiveDateTime> = None;
        for entry in &history.entries {
            if last_modification_time.is_none() {
                last_modification_time = entry.times.last_modification.as_ref();
            }

            if let Some(entry_modification_time) = entry.times.last_modification.as_ref() {
                if last_modification_time.unwrap() < entry_modification_time {
                    panic!(
                        "History entries are not ordered by last modification time: {:?} came after {:?}",
                        last_modification_time, entry_modification_time
                    );
                }
                last_modification_time = Some(entry_modification_time);
            }
        }
    }

    /// Test that merging a database with itself results in no changes.
    #[test]
    fn test_idempotence() {
        let mut destination_db = create_test_database();
        let source_db = destination_db.clone();

        let entry_count_before = destination_db.entries.len();
        let group_count_before = destination_db.groups.len();

        let merge_result = destination_db.merge(&source_db).unwrap();
        assert_eq!(merge_result.warnings.len(), 0);
        assert_eq!(merge_result.events.len(), 0);
        assert_eq!(destination_db.root().entries().count(), 1);
        assert_eq!(destination_db.root().groups().count(), 2);

        assert_eq!(destination_db.entries.len(), entry_count_before);
        assert_eq!(destination_db.groups.len(), group_count_before);

        // The two groups should be exactly the same after merging, since
        // nothing was performed during the merge.
        assert_eq!(destination_db, source_db);

        sleep();

        // Now modify an entry in the destination database, and merge again.
        destination_db
            .entry_mut(ENTRY1_ID)
            .unwrap()
            .edit_tracking(|e| e.set_unprotected("Title", "entry1_updated"));

        // Merging should ignore the change, since destination is more recent.
        let merge_result = destination_db.merge(&source_db).unwrap();
        assert_eq!(merge_result.warnings.len(), 0);
        assert_eq!(merge_result.events.len(), 0);
        let destination_db_just_after_merge = destination_db.clone();

        let merge_result = destination_db.merge(&source_db).unwrap();
        assert_eq!(merge_result.warnings.len(), 0);
        assert_eq!(merge_result.events.len(), 0);

        // Merging twice in a row, even if the first merge updated the destination group,
        // should not create more changes.
        assert_eq!(destination_db_just_after_merge, destination_db);
    }

    /// Test that a new entry in source is added to destination when merging.
    #[test]
    fn test_add_new_entry() {
        let mut destination_db = create_test_database();
        let mut source_db = destination_db.clone();

        let entry_count_before = destination_db.entries.len();
        let group_count_before = destination_db.groups.len();

        // create a new entry in source_db and retain its id
        let new_entry_id = source_db
            .root_mut()
            .add_entry()
            .edit_tracking(|e| e.set_unprotected("Title", "new_entry"))
            .id();

        // merge source_db into destination_db -- this should add the new entry
        let merge_result = destination_db.merge(&source_db).unwrap();
        assert_eq!(merge_result.warnings.len(), 0);
        assert_eq!(merge_result.events.len(), 1);

        let entry_count_after = destination_db.entries.len();
        let group_count_after = destination_db.groups.len();
        assert_eq!(entry_count_after, entry_count_before + 1);
        assert_eq!(group_count_after, group_count_before);

        let root_entries_count = destination_db.root().entries().count();
        assert_eq!(root_entries_count, 2);

        let new_entry = destination_db
            .entry(new_entry_id)
            .expect("New entry should exist");
        assert_eq!(new_entry.get(fields::TITLE), Some("new_entry"));

        // Merging the same group again should not create a duplicate entry.
        let merge_result = destination_db.merge(&source_db).unwrap();
        assert_eq!(merge_result.warnings.len(), 0);
        assert_eq!(merge_result.events.len(), 0);

        let entry_count_after = destination_db.entries.len();
        let group_count_after = destination_db.groups.len();
        assert_eq!(entry_count_after, entry_count_before + 1);
        assert_eq!(group_count_after, group_count_before);

        let root_entries_count = destination_db.root().entries().count();
        assert_eq!(root_entries_count, 2);
    }

    /// Test that an entry that is marked as deleted in the destination database is not re-added
    /// when merging from source
    #[test]
    fn test_deleted_entry_in_destination() {
        let mut destination_db = create_test_database();
        let mut source_db = destination_db.clone();

        let entry_count_before = destination_db.entries.len();
        let group_count_before = destination_db.groups.len();

        // add a new entry in source_db that will be marked as deleted in destination_db
        let deleted_entry_id = source_db
            .root_mut()
            .add_entry()
            .edit_tracking(|e| {
                e.set_unprotected("Title", "deleted_entry");
            })
            .id();

        // mark the entry as deleted in destination_db
        destination_db
            .deleted_objects
            .insert(deleted_entry_id.uuid(), Some(Times::now()));

        // merge source_db into destination_db -- the entry should not be added
        let merge_result = destination_db.merge(&source_db).unwrap();
        assert_eq!(merge_result.warnings.len(), 0);
        assert_eq!(merge_result.events.len(), 0);

        let entry_count_after = destination_db.entries.len();
        let group_count_after = destination_db.groups.len();
        assert_eq!(entry_count_after, entry_count_before);
        assert_eq!(group_count_after, group_count_before);

        assert!(destination_db.entry(deleted_entry_id).is_none());
    }

    /// Test that an entry that is updated and moved to a group in source but that group is deleted
    /// later in dest should cause the group to be re-added and the entry to be moved there.
    #[test]
    fn test_updated_entry_under_deleted_group() {
        let mut destination_db = create_test_database();

        let modified_entry_id = destination_db
            .root_mut()
            .add_entry()
            .edit(|e| e.set_unprotected("Title", "original_title"))
            .id();

        let deleted_group_id = destination_db
            .root_mut()
            .add_group()
            .edit(|g| g.name = "deleted_group".to_string())
            .id();

        let mut source_db = destination_db.clone();

        sleep();

        // perform the update of the entry in source_db and move it to the group that will be
        // deleted
        source_db
            .entry_mut(modified_entry_id)
            .unwrap()
            .track_changes()
            .edit(|e| {
                e.set_unprotected("Title", "modified_title");
            })
            .move_to(deleted_group_id)
            .unwrap();

        sleep();

        // delete the group in destination_db
        destination_db.group_mut(deleted_group_id).unwrap().remove();

        let entry_count_before = destination_db.entries.len();
        let group_count_before = destination_db.groups.len();

        // perform the merge - the group should be re-added and the entry moved there
        let merge_result = destination_db.merge(&source_db).unwrap();
        assert_eq!(merge_result.warnings.len(), 0);
        assert_eq!(merge_result.events.len(), 3); // recreate group, move entry, update entry

        let entry_count_after = destination_db.entries.len();
        let group_count_after = destination_db.groups.len();
        assert_eq!(entry_count_after, entry_count_before);
        assert_eq!(group_count_after, group_count_before + 1);

        assert!(destination_db.group(deleted_group_id).is_some());
        assert!(destination_db.entry(modified_entry_id).is_some());
    }

    /// Test that a group that is marked as deleted in the destination database is not re-added
    /// when merging from source
    #[test]
    fn test_deleted_group_in_destination() {
        let mut destination_db = create_test_database();
        let mut source_db = destination_db.clone();

        let entry_count_before = destination_db.entries.len();
        let group_count_before = destination_db.groups.len();

        // add a new group in source_db
        let deleted_group_id = source_db
            .root_mut()
            .add_group()
            .edit(|g| g.name = "deleted_group".to_string())
            .id();

        // mark the group as deleted in destination_db
        destination_db
            .deleted_objects
            .insert(deleted_group_id.uuid(), Some(Times::now()));

        let merge_result = destination_db.merge(&source_db).unwrap();
        assert_eq!(merge_result.warnings.len(), 0);
        assert_eq!(merge_result.events.len(), 0);

        let entry_count_after = destination_db.entries.len();
        let group_count_after = destination_db.groups.len();
        assert_eq!(entry_count_after, entry_count_before);
        assert_eq!(group_count_after, group_count_before);

        assert!(destination_db.group(deleted_group_id).is_none());
    }

    /// Test that an entry that is marked as deleted in the source database is deleted from destination
    #[test]
    fn test_deleted_entry_in_source() {
        let mut destination_db = create_test_database();

        let deleted_entry_id = destination_db
            .root_mut()
            .add_entry()
            .edit_tracking(|e| e.set_unprotected("Title", "deleted_entry"))
            .id();

        let mut source_db = destination_db.clone();

        let entry_count_before = destination_db.entries.len();
        let group_count_before = destination_db.groups.len();

        // mark the entry as deleted in source_db
        source_db
            .entry_mut(deleted_entry_id)
            .unwrap()
            .track_changes()
            .remove();

        // perform the merge - the entry should be deleted
        let merge_result = destination_db.merge(&source_db).unwrap();
        assert_eq!(merge_result.warnings.len(), 0);
        assert_eq!(merge_result.events.len(), 1);

        // verify that the entry was deleted
        let entry_count_after = destination_db.entries.len();
        let group_count_after = destination_db.groups.len();
        assert_eq!(entry_count_after, entry_count_before - 1);
        assert_eq!(group_count_after, group_count_before);

        assert!(destination_db.entry(deleted_entry_id).is_none());
        assert!(destination_db
            .deleted_objects
            .contains_key(&deleted_entry_id.uuid()));
    }

    /// Test that a group that is marked as deleted in the source database is deleted from destination
    #[test]
    fn test_deleted_group_in_source() {
        let mut destination_db = create_test_database();

        let deleted_group_id = destination_db
            .root_mut()
            .add_group()
            .edit(|g| g.name = "deleted_group".to_string())
            .id();

        let mut source_db = destination_db.clone();

        let entry_count_before = destination_db.entries.len();
        let group_count_before = destination_db.groups.len();

        // mark the entry as deleted in source_db
        source_db
            .group_mut(deleted_group_id)
            .unwrap()
            .track_changes()
            .remove()
            .unwrap();

        // perform the merge - the entry should be deleted
        let merge_result = destination_db.merge(&source_db).unwrap();
        assert_eq!(merge_result.warnings.len(), 0);
        assert_eq!(merge_result.events.len(), 1);

        // verify that the entry was deleted
        let entry_count_after = destination_db.entries.len();
        let group_count_after = destination_db.groups.len();
        assert_eq!(entry_count_after, entry_count_before);
        assert_eq!(group_count_after, group_count_before - 1);

        assert!(destination_db.group(deleted_group_id).is_none());
        assert!(destination_db
            .deleted_objects
            .contains_key(&deleted_group_id.uuid()));
    }

    /// Test that an entry that is marked as deleted in the source database but modified in
    /// destination is not deleted
    #[test]
    fn test_deleted_entry_in_source_modified_in_destination() {
        let mut destination_db = create_test_database();

        let deleted_entry_id = destination_db
            .root_mut()
            .add_entry()
            .edit_tracking(|e| e.set_unprotected("Title", "deleted_entry"))
            .id();

        let entry_count_before = destination_db.entries.len();
        let group_count_before = destination_db.groups.len();

        let mut source_db = destination_db.clone();

        // mark the entry as deleted in source_db
        source_db
            .entry_mut(deleted_entry_id)
            .unwrap()
            .track_changes()
            .remove();

        sleep();

        // modify the entry in destination_db
        destination_db
            .entry_mut(deleted_entry_id)
            .unwrap()
            .edit_tracking(|e| e.set_unprotected("Title", "modified_in_destination"));

        let merge_result = destination_db.merge(&source_db).unwrap();
        assert_eq!(merge_result.warnings.len(), 0);
        assert_eq!(merge_result.events.len(), 0);

        let entry_count_after = destination_db.entries.len();
        let group_count_after = destination_db.groups.len();
        assert_eq!(entry_count_after, entry_count_before);
        assert_eq!(group_count_after, group_count_before);

        assert!(destination_db.entry(deleted_entry_id).is_some());
        assert!(!destination_db
            .deleted_objects
            .contains_key(&deleted_entry_id.uuid()));
    }

    /// Test that a group subtree that is marked as deleted in the source database is deleted from
    /// destination
    #[test]
    fn test_group_subtree_deletion() {
        let mut destination_db = create_test_database();

        let deleted_group_id = destination_db
            .root_mut()
            .add_group()
            .edit(|g| {
                g.name = "deleted_group".to_string();
            })
            .id();

        let deleted_subgroup_id = destination_db
            .group_mut(deleted_group_id)
            .unwrap()
            .add_group()
            .edit(|g| {
                g.name = "deleted_subgroup".to_string();
            })
            .id();

        let deleted_entry_id = destination_db
            .group_mut(deleted_subgroup_id)
            .unwrap()
            .add_entry()
            .edit_tracking(|e| {
                e.set_unprotected("Title", "deleted_entry");
            })
            .id();

        let mut source_db = destination_db.clone();

        // mark the entire group subtree as deleted in source_db
        source_db
            .root_mut()
            .group_mut(deleted_group_id)
            .unwrap()
            .track_changes()
            .remove()
            .unwrap();

        let entry_count_before = destination_db.entries.len();
        let group_count_before = destination_db.groups.len();

        // perform the merge - the entire subtree should be deleted
        let merge_result = destination_db.merge(&source_db).unwrap();
        assert_eq!(merge_result.warnings.len(), 0);
        assert_eq!(merge_result.events.len(), 3);

        let entry_count_after = destination_db.entries.len();
        let group_count_after = destination_db.groups.len();
        assert_eq!(entry_count_after, entry_count_before - 1);
        assert_eq!(group_count_after, group_count_before - 2);

        assert!(destination_db.entry(deleted_entry_id).is_none());
        assert!(destination_db.group(deleted_subgroup_id).is_none());
        assert!(destination_db.group(deleted_group_id).is_none());

        assert!(destination_db
            .deleted_objects
            .contains_key(&deleted_entry_id.uuid()));
        assert!(destination_db
            .deleted_objects
            .contains_key(&deleted_subgroup_id.uuid()));
        assert!(destination_db
            .deleted_objects
            .contains_key(&deleted_group_id.uuid()));
    }

    /// Test that a tree that was deleted in source, but contains a group that is newer in
    /// destination is only partially deleted.
    #[test]
    fn test_group_subtree_partial_deletion() {
        let mut destination_db = create_test_database();

        let deleted_group_id = destination_db
            .root_mut()
            .add_group()
            .edit(|g| {
                g.name = "deleted_group".to_string();
            })
            .id();

        let deleted_subgroup_id = destination_db
            .group_mut(deleted_group_id)
            .unwrap()
            .add_group()
            .edit(|g| {
                g.name = "deleted_subgroup".to_string();
            })
            .id();

        let deleted_entry_id = destination_db
            .group_mut(deleted_subgroup_id)
            .unwrap()
            .add_entry()
            .edit(|e| {
                e.set_unprotected("Title", "deleted_entry");
            })
            .id();

        let mut source_db = destination_db.clone();

        sleep();

        // mark the entire group subtree as deleted in source_db
        source_db
            .group_mut(deleted_group_id)
            .unwrap()
            .track_changes()
            .remove()
            .unwrap();

        sleep();

        // modify the deleted subgroup in destination_db to be newer than the deletion time
        destination_db
            .group_mut(deleted_group_id)
            .unwrap()
            .track_changes()
            .edit(|g| {
                g.notes = Some("modified in destination".to_string());
            });

        let entry_count_before = destination_db.entries.len();
        let group_count_before = destination_db.groups.len();

        // perform the merge - the entry and subgroup should be deleted, but the group should
        // remain
        let merge_result = destination_db.merge(&source_db).unwrap();
        assert_eq!(merge_result.warnings.len(), 0);
        assert_eq!(merge_result.events.len(), 2);

        let entry_count_after = destination_db.entries.len();
        let group_count_after = destination_db.groups.len();
        assert_eq!(entry_count_after, entry_count_before - 1);
        assert_eq!(group_count_after, group_count_before - 1);

        assert!(destination_db.entry(deleted_entry_id).is_none());
        assert!(destination_db.group(deleted_subgroup_id).is_none());
        assert!(destination_db.group(deleted_group_id).is_some());

        assert!(destination_db
            .deleted_objects
            .contains_key(&deleted_entry_id.uuid()));
        assert!(destination_db
            .deleted_objects
            .contains_key(&deleted_subgroup_id.uuid()));
        assert!(!destination_db
            .deleted_objects
            .contains_key(&deleted_group_id.uuid()));
    }

    /// Test that a group that is marked as deleted in the source database but modified in
    /// destination is not deleted
    #[test]
    fn test_deleted_group_in_source_modified_in_destination() {
        let mut destination_db = create_test_database();

        let deleted_group_id = destination_db
            .root_mut()
            .add_group()
            .edit(|g| g.name = "deleted_group".to_string())
            .id();

        let mut source_db = destination_db.clone();

        // mark the group as deleted in source_db
        source_db
            .group_mut(deleted_group_id)
            .unwrap()
            .track_changes()
            .remove()
            .unwrap();

        sleep();

        // modify the group in destination_db
        destination_db
            .group_mut(deleted_group_id)
            .unwrap()
            .track_changes()
            .edit(|g| g.notes = Some("modified_in_destination".to_string()));

        let entry_count_before = destination_db.entries.len();
        let group_count_before = destination_db.groups.len();

        // perform the merge - the group should not be deleted
        let merge_result = destination_db.merge(&source_db).unwrap();
        assert_eq!(merge_result.warnings.len(), 0);
        assert_eq!(merge_result.events.len(), 0);

        let entry_count_after = destination_db.entries.len();
        let group_count_after = destination_db.groups.len();
        assert_eq!(entry_count_after, entry_count_before);
        assert_eq!(group_count_after, group_count_before);

        assert!(destination_db.group(deleted_group_id).is_some());

        assert!(!destination_db
            .deleted_objects
            .contains_key(&deleted_group_id.uuid()));
    }

    /// Test that a group that is marked as deleted in the source database but has new entries
    /// added in destination is not deleted
    #[test]
    fn test_deleted_group_has_new_entries() {
        let mut destination_db = create_test_database();

        let deleted_group_id = destination_db
            .root_mut()
            .add_group()
            .edit(|g| g.name = "deleted_group".to_string())
            .id();

        let mut source_db = destination_db.clone();

        // mark the group as deleted in source_db
        source_db
            .group_mut(deleted_group_id)
            .unwrap()
            .track_changes()
            .remove()
            .unwrap();

        sleep();

        // add a new entry to the deleted group in destination_db
        let new_entry_id = destination_db
            .group_mut(deleted_group_id)
            .unwrap()
            .add_entry()
            .edit_tracking(|e| {
                e.set_unprotected("Title", "new_entry_in_deleted_group");
            })
            .id();

        let entry_count_before = destination_db.entries.len();
        let group_count_before = destination_db.groups.len();

        // perform the merge - the group should not be deleted
        let merge_result = destination_db.merge(&source_db).unwrap();
        assert_eq!(merge_result.warnings.len(), 0);
        assert_eq!(merge_result.events.len(), 0);

        let entry_count_after = destination_db.entries.len();
        let group_count_after = destination_db.groups.len();
        assert_eq!(entry_count_after, entry_count_before);
        assert_eq!(group_count_after, group_count_before);

        assert!(destination_db.group(deleted_group_id).is_some());
        assert!(destination_db.entry(new_entry_id).is_some());

        assert!(!destination_db
            .deleted_objects
            .contains_key(&deleted_group_id.uuid()));
        assert!(!destination_db.deleted_objects.contains_key(&new_entry_id.uuid()));
    }

    /// Test that a new entry in a non-root group in source is added to destination when merging.
    #[test]
    fn test_add_new_non_root_entry() {
        let mut destination_db = create_test_database();
        let mut source_db = destination_db.clone();

        let entry_count_before = destination_db.entries.len();
        let group_count_before = destination_db.groups.len();

        let new_entry_id = source_db
            .group_mut(GROUP1_ID)
            .unwrap()
            .add_entry()
            .edit_tracking(|e| {
                e.set_unprotected("Title", "new_entry");
            })
            .id();

        // perform the merge - this should add the new entry
        let merge_result = destination_db.merge(&source_db).unwrap();
        assert_eq!(merge_result.warnings.len(), 0);
        assert_eq!(merge_result.events.len(), 1);

        let entry_count_after = destination_db.entries.len();
        let group_count_after = destination_db.groups.len();
        assert_eq!(entry_count_after, entry_count_before + 1);
        assert_eq!(group_count_after, group_count_before);

        assert!(destination_db.entry(new_entry_id).is_some());
    }

    // Test that a new entry in source under a new group/subgroup is added to destination when
    // merging.
    #[test]
    fn test_add_new_entry_new_group() {
        let mut destination_db = create_test_database();
        let mut source_db = destination_db.clone();

        let entry_count_before = destination_db.entries.len();
        let group_count_before = destination_db.groups.len();

        let new_group_id = source_db
            .root_mut()
            .add_group()
            .edit(|g| g.name = "new_group".to_string())
            .id();

        let new_subgroup_id = source_db
            .group_mut(new_group_id)
            .unwrap()
            .add_group()
            .edit(|g| g.name = "new_subgroup".to_string())
            .id();

        let new_entry_id = source_db
            .group_mut(new_subgroup_id)
            .unwrap()
            .add_entry()
            .edit_tracking(|e| {
                e.set_unprotected("Title", "new_entry");
            })
            .id();

        // perform the merge - this should add the new entry along with the new group and subgroup
        let merge_result = destination_db.merge(&source_db).unwrap();
        assert_eq!(merge_result.warnings.len(), 0);
        assert_eq!(merge_result.events.len(), 3);

        let entry_count_after = destination_db.entries.len();
        let group_count_after = destination_db.groups.len();
        assert_eq!(entry_count_after, entry_count_before + 1);
        assert_eq!(group_count_after, group_count_before + 2);

        assert!(destination_db.group(new_group_id).is_some());
        assert!(destination_db.group(new_subgroup_id).is_some());
        assert!(destination_db.entry(new_entry_id).is_some());
    }

    /// Test that an entry is relocated from one group to another in source and the relocation
    /// is reflected in destination when merging.
    #[test]
    fn test_entry_relocation_existing_group() {
        let mut destination_db = create_test_database();
        let mut source_db = destination_db.clone();

        let entry_count_before = destination_db.entries.len();
        let group_count_before = destination_db.groups.len();

        sleep();

        // before
        // root (ROOT_GROUP_ID)
        // ├── entry1 (ENTRY1_ID)
        // ├── group1 (GROUP1_ID)
        // │   └── subgroup1 (SUBGROUP1_ID)
        // │       └── entry2 (ENTRY2_ID)   <-- this entry
        // └── group2 (GROUP2_ID)
        //    └── subgroup2 (SUBGROUP2_ID)
        //
        // after
        // root (ROOT_GROUP_ID)
        // ├── entry1 (ENTRY1_ID)
        // ├── group1 (GROUP1_ID)
        // │   └── subgroup1 (SUBGROUP1_ID)
        // └── group2 (GROUP2_ID)
        //     ├── entry2 (ENTRY2_ID)   <-- moved here
        //     └── subgroup2 (SUBGROUP2_ID)
        //
        source_db
            .entry_mut(ENTRY2_ID)
            .unwrap()
            .track_changes()
            .move_to(GROUP2_ID)
            .expect("move successful");

        let location_changed_timestamp = source_db
            .entry(ENTRY2_ID)
            .unwrap()
            .times
            .location_changed
            .unwrap();

        // perform the merge - this should relocate the entry in destination_db
        let merge_result = destination_db.merge(&source_db).unwrap();
        assert_eq!(merge_result.warnings.len(), 0);
        assert_eq!(merge_result.events.len(), 1);

        let entry_count_after = destination_db.entries.len();
        let group_count_after = destination_db.groups.len();
        assert_eq!(group_count_after, group_count_before);
        assert_eq!(entry_count_after, entry_count_before);

        assert!(destination_db.entry(ENTRY2_ID).is_some());

        let entry = destination_db.entry(ENTRY2_ID).unwrap();
        assert_eq!(entry.parent().id(), GROUP2_ID);
        assert_eq!(entry.times.location_changed, Some(location_changed_timestamp));
    }

    /// Test that an entry is relocated in source and modified in both source and destination
    /// and the correct content is kept after merging.
    #[test]
    fn test_entry_relocation_and_update() {
        let mut destination_db = create_test_database();
        let mut source_db = destination_db.clone();

        let entry_count_before = destination_db.entries.len();
        let group_count_before = destination_db.groups.len();

        sleep();

        // perform first edit of entry in source
        source_db.entry_mut(ENTRY2_ID).unwrap().edit_tracking(|e| {
            e.set_unprotected("Title", "entry2_modified_in_source");
        });

        // relocate entry in source
        source_db
            .entry_mut(ENTRY2_ID)
            .unwrap()
            .track_changes()
            .move_to(GROUP2_ID)
            .expect("move successful");

        let location_changed_timestamp = source_db
            .entry(ENTRY2_ID)
            .unwrap()
            .times
            .location_changed
            .unwrap();

        sleep();

        // perform second edit of entry in destination
        destination_db.entry_mut(ENTRY2_ID).unwrap().edit_tracking(|e| {
            e.set_unprotected("Title", "entry2_modified_in_destination");
        });

        let entry_modified_timestamp = destination_db
            .entry(ENTRY2_ID)
            .unwrap()
            .times
            .last_modification
            .unwrap();

        // perform the merge - this should relocate the entry in destination_db and keep the
        // content from destination_db since it was modified later
        let merge_result = destination_db.merge(&source_db).unwrap();
        assert_eq!(merge_result.warnings.len(), 0);
        assert_eq!(merge_result.events.len(), 1);

        let entry_count_after = destination_db.entries.len();
        let group_count_after = destination_db.groups.len();
        assert_eq!(group_count_after, group_count_before);
        assert_eq!(entry_count_after, entry_count_before);

        // check that move occurred
        assert!(destination_db.entry(ENTRY2_ID).is_some());
        let entry = destination_db.entry(ENTRY2_ID).unwrap();
        assert_eq!(entry.parent().id(), GROUP2_ID);
        assert_eq!(entry.times.location_changed, Some(location_changed_timestamp));

        // check that content from destination is kept
        assert_eq!(entry.get(fields::TITLE), Some("entry2_modified_in_destination"));
        assert_eq!(entry.times.last_modification, Some(entry_modified_timestamp));
    }

    /// Test that if an entry is moved in source and modified in destination, the entry stays
    /// in the new location and gets the modifications.
    #[test]
    fn test_entry_relocation_in_destination_and_update() {
        let mut destination_db = create_test_database();
        let mut source_db = destination_db.clone();

        let entry_count_before = destination_db.entries.len();
        let group_count_before = destination_db.groups.len();

        sleep();

        // edit entry in source
        source_db.entry_mut(ENTRY2_ID).unwrap().edit_tracking(|e| {
            e.set_unprotected(fields::TITLE, "entry2_modified_in_source");
        });

        let entry_modified_timestamp = source_db
            .entry(ENTRY2_ID)
            .unwrap()
            .times
            .last_modification
            .unwrap();

        // relocate entry in destination
        destination_db
            .entry_mut(ENTRY2_ID)
            .unwrap()
            .track_changes()
            .move_to(GROUP2_ID)
            .expect("move successful");

        let location_changed_timestamp = destination_db
            .entry(ENTRY2_ID)
            .unwrap()
            .times
            .location_changed
            .unwrap();

        // perform the merge - this should keep the location from destination and the content from
        // source
        let merge_result = destination_db.merge(&source_db).unwrap();
        assert_eq!(merge_result.warnings.len(), 0);
        assert_eq!(merge_result.events.len(), 1);

        let entry_count_after = destination_db.entries.len();
        let group_count_after = destination_db.groups.len();
        assert_eq!(group_count_after, group_count_before);
        assert_eq!(entry_count_after, entry_count_before);

        // check that move occurred
        assert!(destination_db.entry(ENTRY2_ID).is_some());

        let entry = destination_db.entry(ENTRY2_ID).unwrap();
        assert_eq!(entry.parent().id(), GROUP2_ID);
        assert_eq!(entry.times.location_changed, Some(location_changed_timestamp));

        // check that content from source is kept
        assert_eq!(entry.get(fields::TITLE), Some("entry2_modified_in_source"));
        assert_eq!(entry.times.last_modification, Some(entry_modified_timestamp));
    }

    /// Test that an entry can be relocated into a newly created group
    #[test]
    fn test_entry_relocation_new_group() {
        let mut destination_db = create_test_database();

        let new_entry_id = destination_db
            .root_mut()
            .add_entry()
            .edit(|e| {
                e.set_unprotected("Title", "new_entry");
            })
            .id();

        let entry_count_before = destination_db.entries.len();
        let group_count_before = destination_db.groups.len();

        let mut source_db = destination_db.clone();

        let new_group_id = source_db
            .root_mut()
            .add_group()
            .edit(|g| g.name = "new_group".to_string())
            .id();

        sleep();

        // modify the entry in source
        source_db.entry_mut(new_entry_id).unwrap().edit_tracking(|e| {
            e.set_unprotected("Title", "new_entry_modified_in_source");
        });

        // relocate the entry to the new group in source
        source_db
            .entry_mut(new_entry_id)
            .unwrap()
            .track_changes()
            .move_to(new_group_id)
            .expect("move successful");

        // perform the merge - this should create the new group and update and relocate the entry there
        let merge_result = destination_db.merge(&source_db).unwrap();
        assert_eq!(merge_result.warnings.len(), 0);
        assert_eq!(merge_result.events.len(), 3);

        let entry_count_after = destination_db.entries.len();
        let group_count_after = destination_db.groups.len();
        assert_eq!(entry_count_after, entry_count_before);
        assert_eq!(group_count_after, group_count_before + 1);

        assert!(destination_db.entry(new_entry_id).is_some());
        let entry = destination_db.entry(new_entry_id).unwrap();
        assert_eq!(entry.parent().id(), new_group_id);
        assert_eq!(entry.get(fields::TITLE), Some("new_entry_modified_in_source"));
    }

    /// Test that a group relocation in source is reflected in destination when merging.
    #[test]
    fn test_group_relocation() {
        let mut destination_db = create_test_database();
        let mut source_db = destination_db.clone();

        let entry_count_before = destination_db.entries.len();
        let group_count_before = destination_db.groups.len();

        sleep();

        // before
        // root (ROOT_GROUP_ID)
        // ├── entry1 (ENTRY1_ID)
        // ├── group1 (GROUP1_ID)
        // │   └── subgroup1 (SUBGROUP1_ID) <-- this group
        // │       └── entry2 (ENTRY2_ID)
        // └── group2 (GROUP2_ID)
        //    └── subgroup2 (SUBGROUP2_ID)
        //
        // after
        // root (ROOT_GROUP_ID)
        // ├── entry1 (ENTRY1_ID)
        // ├── group1 (GROUP1_ID)
        // └── group2 (GROUP2_ID)
        //    └── subgroup2 (SUBGROUP2_ID)
        //        └── subgroup1 (SUBGROUP1_ID) <-- moved here
        //            └── entry2 (ENTRY2_ID)

        source_db
            .group_mut(SUBGROUP1_ID)
            .unwrap()
            .track_changes()
            .move_to(GROUP2_ID)
            .expect("move successful");

        let location_changed_timestamp = source_db
            .group(SUBGROUP1_ID)
            .unwrap()
            .times
            .location_changed
            .unwrap();

        // perform the merge - this should relocate the group in destination_db
        let merge_result = destination_db.merge(&source_db).unwrap();
        assert_eq!(merge_result.warnings.len(), 0);
        assert_eq!(merge_result.events.len(), 1);

        let entry_count_after = destination_db.entries.len();
        let group_count_after = destination_db.groups.len();
        assert_eq!(entry_count_after, entry_count_before);
        assert_eq!(group_count_after, group_count_before);

        assert!(destination_db.group(SUBGROUP1_ID).is_some());
        assert!(destination_db.entry(ENTRY2_ID).is_some());

        let group = destination_db.group(SUBGROUP1_ID).unwrap();
        assert_eq!(group.parent().unwrap().id(), GROUP2_ID);
        assert_eq!(group.times.location_changed, Some(location_changed_timestamp));
    }

    /// Test that an entry updated in destination is not touched when merging.
    #[test]
    fn test_update_in_destination_no_conflict() {
        let mut destination_db = create_test_database();
        let source_db = destination_db.clone();

        let entry_count_before = destination_db.entries.len();
        let group_count_before = destination_db.groups.len();

        sleep();

        // update entry in destination
        destination_db.entry_mut(ENTRY1_ID).unwrap().edit_tracking(|e| {
            e.set_unprotected("Title", "entry1_updated");
        });

        // perform the merge - this should not change anything since source is older
        let merge_result = destination_db.merge(&source_db).unwrap();
        assert_eq!(merge_result.warnings.len(), 0);
        assert_eq!(merge_result.events.len(), 0);

        // check that history is preserved
        let merged_history = destination_db.entry(ENTRY1_ID).unwrap().history.clone().unwrap();
        assert_history_ordered(&merged_history);
        assert_eq!(merged_history.entries.len(), 1);

        // check that we can find the old version of the entry
        let merged_entry = &merged_history.entries[0];
        assert_eq!(merged_entry.get(fields::TITLE), Some("entry1"));

        let entry_count_after = destination_db.entries.len();
        let group_count_after = destination_db.groups.len();
        assert_eq!(entry_count_after, entry_count_before);
        assert_eq!(group_count_after, group_count_before);

        assert_eq!(
            destination_db.entry(ENTRY1_ID).unwrap().get(fields::TITLE),
            Some("entry1_updated")
        );
    }

    /// Test that an entry updated in source is merged into destination when merging.
    #[test]
    fn test_update_in_source_no_conflict() {
        let mut destination_db = create_test_database();
        let mut source_db = destination_db.clone();

        let entry_count_before = destination_db.entries.len();
        let group_count_before = destination_db.groups.len();

        sleep();

        // update entry in source
        source_db.entry_mut(ENTRY1_ID).unwrap().edit_tracking(|e| {
            e.set_unprotected("Title", "entry1_updated");
        });

        // perform the merge - this should update the entry in destination_db
        let merge_result = destination_db.merge(&source_db).unwrap();
        assert_eq!(merge_result.warnings.len(), 0);
        assert_eq!(merge_result.events.len(), 1);

        // check that history is preserved
        let merged_history = destination_db.entry(ENTRY1_ID).unwrap().history.clone().unwrap();
        assert_history_ordered(&merged_history);
        assert_eq!(merged_history.entries.len(), 1);

        // check that we can find the old version of the entry
        let merged_entry = &merged_history.entries[0];
        assert_eq!(merged_entry.get(fields::TITLE), Some("entry1"));

        let entry_count_after = destination_db.entries.len();
        let group_count_after = destination_db.groups.len();
        assert_eq!(entry_count_after, entry_count_before);
        assert_eq!(group_count_after, group_count_before);

        // check that the entry was updated
        assert_eq!(
            destination_db.entry(ENTRY1_ID).unwrap().get(fields::TITLE),
            Some("entry1_updated")
        );
    }

    /// Test that an entry updated in both source and destination is merged correctly.
    #[test]
    fn test_update_with_conflicts() {
        let mut destination_db = create_test_database();
        let mut source_db = destination_db.clone();

        let entry_count_before = destination_db.entries.len();
        let group_count_before = destination_db.groups.len();

        sleep();

        // update entry in destination
        destination_db.entry_mut(ENTRY1_ID).unwrap().edit_tracking(|e| {
            e.set_unprotected("Title", "entry1_updated_from_destination");
        });

        sleep();

        // update entry in source
        source_db.entry_mut(ENTRY1_ID).unwrap().edit_tracking(|e| {
            e.set_unprotected("Title", "entry1_updated_from_source");
        });

        // perform the merge - this should merge the changes from both databases, keeping the newer
        let merge_result = destination_db.merge(&source_db).unwrap();
        assert_eq!(merge_result.warnings.len(), 0);
        assert_eq!(merge_result.events.len(), 1);

        let entry_count_after = destination_db.entries.len();
        let group_count_after = destination_db.groups.len();
        assert_eq!(entry_count_after, entry_count_before);
        assert_eq!(group_count_after, group_count_before);

        // check that the entry was updated with the source change (newer)
        let entry = destination_db.entry(ENTRY1_ID).unwrap();
        assert_eq!(entry.get(fields::TITLE), Some("entry1_updated_from_source"));

        // check that history is preserved and contains both older versions
        let merged_history = entry.history.clone().unwrap();
        assert_history_ordered(&merged_history);
        assert_eq!(merged_history.entries.len(), 2);
        assert_eq!(
            merged_history.entries[0].get(fields::TITLE),
            Some("entry1_updated_from_destination")
        );
        assert_eq!(merged_history.entries[1].get(fields::TITLE), Some("entry1"));

        // Merging again should not result in any additional change.
        let merge_result = destination_db.merge(&destination_db.clone()).unwrap();
        assert_eq!(merge_result.warnings.len(), 0);
        assert_eq!(merge_result.events.len(), 0);
    }

    /// Test that a group updated in source is merged into destination when merging.
    #[test]
    fn test_group_update_in_source() {
        let mut destination_db = create_test_database();
        let mut source_db = destination_db.clone();

        let entry_count_before = destination_db.entries.len();
        let group_count_before = destination_db.groups.len();

        sleep();

        source_db.group_mut(SUBGROUP1_ID).unwrap().edit_tracking(|g| {
            g.name = "subgroup1_updated_name".to_string();
        });

        let modification_timestamp = source_db
            .group(SUBGROUP1_ID)
            .unwrap()
            .times
            .last_modification
            .unwrap();

        // perform the merge - this should update the group in destination
        let merge_result = destination_db.merge(&source_db).unwrap();
        assert_eq!(merge_result.warnings.len(), 0);
        assert_eq!(merge_result.events.len(), 1);

        let entry_count_after = destination_db.entries.len();
        let group_count_after = destination_db.groups.len();
        assert_eq!(entry_count_after, entry_count_before);
        assert_eq!(group_count_after, group_count_before);

        assert!(destination_db.group(SUBGROUP1_ID).is_some());

        assert_eq!(
            destination_db.group(SUBGROUP1_ID).unwrap().name,
            "subgroup1_updated_name"
        );
        assert_eq!(
            destination_db
                .group(SUBGROUP1_ID)
                .unwrap()
                .times
                .last_modification,
            Some(modification_timestamp)
        );
    }

    /// Test that a group updated in destination is not changed when merging.
    #[test]
    fn test_group_update_in_destination() {
        let mut destination_db = create_test_database();
        let source_db = destination_db.clone();

        let entry_count_before = destination_db.entries.len();
        let group_count_before = destination_db.groups.len();

        sleep();

        destination_db
            .group_mut(SUBGROUP1_ID)
            .unwrap()
            .edit_tracking(|g| {
                g.name = "subgroup1_updated_name".to_string();
            });

        let last_modification = destination_db
            .group(SUBGROUP1_ID)
            .unwrap()
            .times
            .last_modification
            .unwrap();

        // perform the merge - this should not change anything since source is older
        let merge_result = destination_db.merge(&source_db).unwrap();
        assert_eq!(merge_result.warnings.len(), 0);
        assert_eq!(merge_result.events.len(), 0);

        let entry_count_after = destination_db.entries.len();
        let group_count_after = destination_db.groups.len();
        assert_eq!(entry_count_after, entry_count_before);
        assert_eq!(group_count_after, group_count_before);

        assert!(destination_db.group(SUBGROUP1_ID).is_some());
        assert_eq!(
            destination_db.group(SUBGROUP1_ID).unwrap().name,
            "subgroup1_updated_name"
        );

        assert_eq!(
            destination_db
                .group(SUBGROUP1_ID)
                .unwrap()
                .times
                .last_modification,
            Some(last_modification)
        );
    }

    /// Test that a group updated in source and relocated is merged correctly.
    #[test]
    fn test_group_update_and_relocation() {
        let mut destination_db = create_test_database();
        let mut source_db = destination_db.clone();

        let entry_count_before = destination_db.entries.len();
        let group_count_before = destination_db.groups.len();

        sleep();

        source_db
            .group_mut(SUBGROUP1_ID)
            .unwrap()
            .track_changes()
            .edit(|g| {
                g.name = "subgroup1_updated_name".to_string();
            })
            .move_to(GROUP2_ID)
            .expect("move successful");

        let modification_timestamp = source_db
            .group(SUBGROUP1_ID)
            .unwrap()
            .times
            .last_modification
            .unwrap();

        let location_changed_timestamp = source_db
            .group(SUBGROUP1_ID)
            .unwrap()
            .times
            .location_changed
            .unwrap();

        // perform the merge - this should update and relocate the group in destination
        let merge_result = destination_db.merge(&source_db).unwrap();
        assert_eq!(merge_result.warnings.len(), 0);
        assert_eq!(merge_result.events.len(), 2);

        let entry_count_after = destination_db.entries.len();
        let group_count_after = destination_db.groups.len();
        assert_eq!(entry_count_after, entry_count_before);
        assert_eq!(group_count_after, group_count_before);

        assert!(destination_db.group(SUBGROUP1_ID).is_some());
        let group = destination_db.group(SUBGROUP1_ID).unwrap();
        assert_eq!(group.name, "subgroup1_updated_name");
        assert_eq!(group.parent().unwrap().id(), GROUP2_ID);
        assert_eq!(group.times.last_modification, Some(modification_timestamp));
        assert_eq!(group.times.location_changed, Some(location_changed_timestamp));
    }

    /// Test that a group updated in source and relocated in destionation is merged correctly.
    #[test]
    fn test_group_update_in_destination_and_relocation_in_source() {
        let mut destination_db = create_test_database();
        let mut source_db = destination_db.clone();

        let entry_count_before = destination_db.entries.len();
        let group_count_before = destination_db.groups.len();

        sleep();

        // rename group in source
        source_db.group_mut(SUBGROUP1_ID).unwrap().edit_tracking(|g| {
            g.name = "subgroup1_updated_name".to_string();
        });

        let modification_timestamp = source_db
            .group(SUBGROUP1_ID)
            .unwrap()
            .times
            .last_modification
            .unwrap();

        // relocate group in destination
        destination_db
            .group_mut(SUBGROUP1_ID)
            .unwrap()
            .track_changes()
            .move_to(GROUP2_ID)
            .expect("move successful");

        let location_changed_timestamp = destination_db
            .group(SUBGROUP1_ID)
            .unwrap()
            .times
            .location_changed
            .unwrap();

        // perform the merge - this should update the group name from source and keep the new
        // location from destination
        let merge_result = destination_db.merge(&source_db).unwrap();
        assert_eq!(merge_result.warnings.len(), 0);
        assert_eq!(merge_result.events.len(), 1);

        let entry_count_after = destination_db.entries.len();
        let group_count_after = destination_db.groups.len();
        assert_eq!(entry_count_after, entry_count_before);
        assert_eq!(group_count_after, group_count_before);

        assert!(destination_db.group(SUBGROUP1_ID).is_some());
        let group = destination_db.group(SUBGROUP1_ID).unwrap();
        assert_eq!(group.name, "subgroup1_updated_name");
        assert_eq!(group.parent().unwrap().id(), GROUP2_ID);
        assert_eq!(group.times.last_modification, Some(modification_timestamp));
        assert_eq!(group.times.location_changed, Some(location_changed_timestamp));
    }

    #[test]
    fn test_merge_untracked_group_history() {
        let mut destination_db = create_test_database();
        let mut source_db = destination_db.clone();

        // this is an invalid edit as the last modified timestamp of the group is not updated
        source_db
            .group_mut(GROUP1_ID)
            .unwrap()
            .edit(|g| {
                g.name = "group1_updated_name".to_string();
            })
            .move_to(GROUP2_ID)
            .expect("move successful");

        assert_eq!(
            destination_db.group(GROUP1_ID).unwrap().times,
            source_db.group(GROUP1_ID).unwrap().times
        );

        // there will be an error during merge since the edit in source_db is not tracked and has
        // the same timestamp as the group in destination_db
        assert!(destination_db.merge(&source_db).is_err());

        // remove the timestamps to test warnings
        destination_db
            .group_mut(GROUP1_ID)
            .unwrap()
            .times
            .last_modification = None;
        destination_db
            .group_mut(GROUP1_ID)
            .unwrap()
            .times
            .location_changed = None;
        source_db.group_mut(GROUP1_ID).unwrap().times.last_modification = None;
        source_db.group_mut(GROUP1_ID).unwrap().times.location_changed = None;

        let merge_result = destination_db.merge(&source_db).unwrap();
        assert_eq!(merge_result.warnings.len(), 3);
        assert_eq!(merge_result.events.len(), 0);
    }

    #[test]
    fn test_merge_untracked_entry_history() {
        let mut destination_db = create_test_database();
        let mut source_db = destination_db.clone();

        // this is an invalid edit as the last modified timestamp of the entry is not updated
        source_db
            .entry_mut(ENTRY1_ID)
            .unwrap()
            .edit(|e| {
                e.set_unprotected("Title", "entry1_updated_title");
            })
            .move_to(GROUP2_ID)
            .expect("move successful");

        assert_eq!(
            destination_db.entry(ENTRY1_ID).unwrap().times,
            source_db.entry(ENTRY1_ID).unwrap().times
        );

        // there will be an error during merge since the edit in source_db is not tracked and has
        // the same timestamp as the entry in destination_db
        assert!(destination_db.merge(&source_db).is_err());

        // remove the timestamps to test warnings
        destination_db
            .entry_mut(ENTRY1_ID)
            .unwrap()
            .times
            .last_modification = None;
        destination_db
            .entry_mut(ENTRY1_ID)
            .unwrap()
            .times
            .location_changed = None;
        source_db.entry_mut(ENTRY1_ID).unwrap().times.last_modification = None;
        source_db.entry_mut(ENTRY1_ID).unwrap().times.location_changed = None;

        let merge_result = destination_db.merge(&source_db).unwrap();
        assert_eq!(merge_result.warnings.len(), 3);
        assert_eq!(merge_result.events.len(), 0);
    }

    #[test]
    fn test_icon_added_in_source() {
        let mut destination_db = create_test_database();
        let mut source_db = destination_db.clone();

        sleep();

        // add a new icon in source
        let new_icon_id = {
            let mut source_entry = source_db.entry_mut(ENTRY1_ID).unwrap();
            let mut source_track = source_entry.track_changes();
            let new_icon_id = source_track.set_icon_custom_new(vec![1, 2, 3, 4]).id();

            new_icon_id
        };

        // perform the merge - this should add the new icon to destination and update the entry's icon reference
        let merge_result = destination_db.merge(&source_db).unwrap();
        assert_eq!(merge_result.warnings.len(), 0);
        assert_eq!(merge_result.events.len(), 2);

        assert!(destination_db.custom_icon(new_icon_id).is_some());
    }

    #[test]
    fn test_icon_updated_in_source() {
        let mut destination_db = create_test_database();

        // add a new icon in destination
        let icon_id = destination_db
            .entry_mut(ENTRY1_ID)
            .unwrap()
            .track_changes()
            .as_mut()
            .set_icon_custom_new(vec![1, 2, 3, 4])
            .id();

        let mut source_db = destination_db.clone();

        sleep();

        // update the icon in source
        let mut source_entry = source_db.entry_mut(ENTRY1_ID).unwrap();
        let mut source_icon = source_entry.custom_icon_mut().unwrap();
        source_icon.data = vec![5, 6, 7, 8];
        source_icon.last_modification_time = Some(Times::now());

        // perform the merge - this should update the icon in destination
        let merge_result = destination_db.merge(&source_db).unwrap();
        assert_eq!(merge_result.warnings.len(), 0);
        assert_eq!(merge_result.events.len(), 1);

        let icon = destination_db.custom_icon(icon_id).unwrap();
        assert_eq!(icon.data, vec![5, 6, 7, 8]);
    }

    #[test]
    fn test_icon_updated_in_destination() {
        let mut destination_db = create_test_database();

        // add a new icon in destination
        let icon_id = destination_db
            .entry_mut(ENTRY1_ID)
            .unwrap()
            .track_changes()
            .as_mut()
            .set_icon_custom_new(vec![1, 2, 3, 4])
            .id();

        let source_db = destination_db.clone();

        sleep();

        // update the icon in destination
        let mut destination_icon = destination_db.custom_icon_mut(icon_id).unwrap();
        destination_icon.data = vec![5, 6, 7, 8];
        destination_icon.last_modification_time = Some(Times::now());

        // perform the merge - this should keep the icon update in destination since it's newer
        let merge_result = destination_db.merge(&source_db).unwrap();
        assert_eq!(merge_result.warnings.len(), 0);
        assert_eq!(merge_result.events.len(), 0);

        let icon = destination_db.custom_icon(icon_id).unwrap();
        assert_eq!(icon.data, vec![5, 6, 7, 8]);
    }

    /// Test that merge_with_ancestor auto-resolves a one-sided change in other without conflict.
    ///
    /// Scenario: ancestor and self are identical; other has a newer version of an entry.
    /// Expected: self silently takes other's version with no warning.
    #[test]
    fn test_ancestor_one_sided_change_in_other() {
        let ancestor_db = create_test_database();
        let mut self_db = ancestor_db.clone();
        let mut other_db = ancestor_db.clone();

        sleep();

        other_db.entry_mut(ENTRY1_ID).unwrap().edit_tracking(|e| {
            e.set_unprotected(fields::TITLE, "entry1_updated_in_other");
        });

        let result = self_db.merge_with_ancestor(&other_db, &ancestor_db).unwrap();

        assert_eq!(
            result.warnings.len(),
            0,
            "one-sided change must not produce a warning"
        );
        assert_eq!(result.events.len(), 1);
        assert_eq!(
            self_db.entry(ENTRY1_ID).unwrap().get(fields::TITLE),
            Some("entry1_updated_in_other"),
        );
    }

    /// Test that merge_with_ancestor keeps self's value when only self changed.
    ///
    /// Scenario: ancestor and other are identical; self has a newer version of an entry.
    /// Expected: self is unchanged and no conflict is raised.
    #[test]
    fn test_ancestor_one_sided_change_in_self() {
        let ancestor_db = create_test_database();
        let mut self_db = ancestor_db.clone();
        let other_db = ancestor_db.clone();

        sleep();

        self_db.entry_mut(ENTRY1_ID).unwrap().edit_tracking(|e| {
            e.set_unprotected(fields::TITLE, "entry1_updated_in_self");
        });

        let result = self_db.merge_with_ancestor(&other_db, &ancestor_db).unwrap();

        assert_eq!(
            result.warnings.len(),
            0,
            "one-sided change must not produce a warning"
        );
        assert_eq!(result.events.len(), 0);
        assert_eq!(
            self_db.entry(ENTRY1_ID).unwrap().get(fields::TITLE),
            Some("entry1_updated_in_self"),
        );
    }

    /// Test that merge_with_ancestor surfaces a warning when both sides changed differently.
    ///
    /// Scenario: both self and other changed the same entry since ancestor.
    /// Expected: warning emitted, newest version wins, history preserved.
    #[test]
    fn test_ancestor_true_conflict_warns_and_newest_wins() {
        let ancestor_db = create_test_database();
        let mut self_db = ancestor_db.clone();
        let mut other_db = ancestor_db.clone();

        sleep();

        self_db.entry_mut(ENTRY1_ID).unwrap().edit_tracking(|e| {
            e.set_unprotected(fields::TITLE, "entry1_updated_in_self");
        });

        sleep();

        other_db.entry_mut(ENTRY1_ID).unwrap().edit_tracking(|e| {
            e.set_unprotected(fields::TITLE, "entry1_updated_in_other");
        });

        let result = self_db.merge_with_ancestor(&other_db, &ancestor_db).unwrap();

        assert_eq!(
            result.warnings.len(),
            1,
            "true conflict must produce exactly one warning"
        );
        assert_eq!(result.events.len(), 1);

        // other is newer, so its value wins
        assert_eq!(
            self_db.entry(ENTRY1_ID).unwrap().get(fields::TITLE),
            Some("entry1_updated_in_other"),
        );

        // self's intermediate version must be preserved in history
        let history = self_db.entry(ENTRY1_ID).unwrap().history.clone().unwrap();
        assert_history_ordered(&history);
        assert!(
            history
                .entries
                .iter()
                .any(|e| e.get(fields::TITLE) == Some("entry1_updated_in_self")),
            "self's version must appear in history",
        );
    }

    /// Test that merge_with_ancestor is idempotent.
    #[test]
    fn test_ancestor_idempotence() {
        let ancestor_db = create_test_database();
        let mut self_db = ancestor_db.clone();
        let other_db = ancestor_db.clone();

        let result = self_db.merge_with_ancestor(&other_db, &ancestor_db).unwrap();
        assert_eq!(result.warnings.len(), 0);
        assert_eq!(result.events.len(), 0);
    }

    /// Test that merge (two-way shim) behaviour is unchanged: both-changed is newest-wins, no warning.
    #[test]
    fn test_two_way_shim_no_warning_on_conflict() {
        let mut self_db = create_test_database();
        let mut other_db = self_db.clone();

        sleep();

        self_db.entry_mut(ENTRY1_ID).unwrap().edit_tracking(|e| {
            e.set_unprotected(fields::TITLE, "entry1_updated_in_self");
        });

        sleep();

        other_db.entry_mut(ENTRY1_ID).unwrap().edit_tracking(|e| {
            e.set_unprotected(fields::TITLE, "entry1_updated_in_other");
        });

        let result = self_db.merge(&other_db).unwrap();

        // two-way merge must not emit warnings (backward-compatible behaviour)
        assert_eq!(result.warnings.len(), 0);
        assert_eq!(result.events.len(), 1);
        assert_eq!(
            self_db.entry(ENTRY1_ID).unwrap().get(fields::TITLE),
            Some("entry1_updated_in_other"),
        );
    }

    /// Test that when both sides move an entry to different groups, the side with the more
    /// recent modification wins both the location and the content.
    ///
    /// Scenario:
    ///   ancestor: entry1 in root
    ///   self:     moves entry1 → group1, updates content  (earlier)
    ///   other:    moves entry1 → group2, updates content  (later)
    /// Expected: entry1 ends up in group2 with other's content; one conflict warning.
    #[test]
    fn test_ancestor_entry_moved_to_different_groups_other_wins() {
        let ancestor_db = create_test_database();
        let mut self_db = ancestor_db.clone();
        let mut other_db = ancestor_db.clone();

        sleep();

        // self moves entry1 to group1 and updates content
        self_db
            .entry_mut(ENTRY1_ID)
            .unwrap()
            .track_changes()
            .move_to(GROUP1_ID)
            .expect("move to group1");
        self_db.entry_mut(ENTRY1_ID).unwrap().edit_tracking(|e| {
            e.set_unprotected(fields::TITLE, "entry1_moved_to_group1_by_self");
        });

        sleep();

        // other moves entry1 to group2 and updates content (newer)
        other_db
            .entry_mut(ENTRY1_ID)
            .unwrap()
            .track_changes()
            .move_to(GROUP2_ID)
            .expect("move to group2");
        other_db.entry_mut(ENTRY1_ID).unwrap().edit_tracking(|e| {
            e.set_unprotected(fields::TITLE, "entry1_moved_to_group2_by_other");
        });

        let result = self_db.merge_with_ancestor(&other_db, &ancestor_db).unwrap();

        // true conflict: both sides changed since ancestor — our warning must be present
        assert!(
            result
                .warnings
                .iter()
                .any(|w| w.contains("modified in both databases since the common ancestor")),
            "expected a conflict warning, got: {:?}",
            result.warnings,
        );

        let entry = self_db.entry(ENTRY1_ID).unwrap();

        // other is newer, so its location wins
        assert_eq!(entry.parent().id(), GROUP2_ID);

        // other is newer, so its content wins
        assert_eq!(entry.get(fields::TITLE), Some("entry1_moved_to_group2_by_other"));
    }

    /// Test that when only other moves an entry (self unchanged since ancestor), the move is
    /// taken silently with no conflict warning.
    ///
    /// Scenario:
    ///   ancestor: entry1 in root
    ///   self:     unchanged
    ///   other:    moves entry1 → group1, updates content
    /// Expected: entry1 ends up in group1 with other's content; no warning.
    #[test]
    fn test_ancestor_entry_moved_in_other_only_no_conflict() {
        let ancestor_db = create_test_database();
        let mut self_db = ancestor_db.clone();
        let mut other_db = ancestor_db.clone();

        sleep();

        // only other moves entry1 to group1 and updates content
        other_db
            .entry_mut(ENTRY1_ID)
            .unwrap()
            .track_changes()
            .move_to(GROUP1_ID)
            .expect("move to group1");
        other_db.entry_mut(ENTRY1_ID).unwrap().edit_tracking(|e| {
            e.set_unprotected(fields::TITLE, "entry1_moved_to_group1_by_other");
        });

        let result = self_db.merge_with_ancestor(&other_db, &ancestor_db).unwrap();

        // one-sided change: no conflict warning
        assert_eq!(result.warnings.len(), 0);

        let entry = self_db.entry(ENTRY1_ID).unwrap();

        // other's location is taken
        assert_eq!(entry.parent().id(), GROUP1_ID);

        // other's content is taken
        assert_eq!(entry.get(fields::TITLE), Some("entry1_moved_to_group1_by_other"));
    }

    /// Both sides edited an entry to the same content at different times — no conflict warning.
    #[test]
    fn test_ancestor_both_changed_identically() {
        let ancestor_db = create_test_database();
        let mut self_db = ancestor_db.clone();
        let mut other_db = ancestor_db.clone();

        sleep();

        self_db.entry_mut(ENTRY1_ID).unwrap().edit_tracking(|e| {
            e.set_unprotected(fields::TITLE, "entry1_same_update");
        });

        sleep();

        other_db.entry_mut(ENTRY1_ID).unwrap().edit_tracking(|e| {
            e.set_unprotected(fields::TITLE, "entry1_same_update");
        });

        let result = self_db.merge_with_ancestor(&other_db, &ancestor_db).unwrap();

        assert_eq!(
            result.warnings.len(),
            0,
            "identical concurrent changes must not warn"
        );
        assert_eq!(
            self_db.entry(ENTRY1_ID).unwrap().get(fields::TITLE),
            Some("entry1_same_update"),
        );
    }

    /// Only other changed a group since ancestor — taken silently, no warning.
    #[test]
    fn test_ancestor_group_one_sided_change_in_other() {
        let ancestor_db = create_test_database();
        let mut self_db = ancestor_db.clone();
        let mut other_db = ancestor_db.clone();

        sleep();

        other_db.group_mut(GROUP1_ID).unwrap().edit_tracking(|g| {
            g.name = "group1_updated_by_other".to_string();
        });

        let result = self_db.merge_with_ancestor(&other_db, &ancestor_db).unwrap();

        assert_eq!(result.warnings.len(), 0, "one-sided group change must not warn");
        assert_eq!(result.events.len(), 1);
        assert_eq!(self_db.group(GROUP1_ID).unwrap().name, "group1_updated_by_other");
    }

    /// Only self changed a group since ancestor — kept silently, no warning.
    #[test]
    fn test_ancestor_group_one_sided_change_in_self() {
        let ancestor_db = create_test_database();
        let mut self_db = ancestor_db.clone();
        let other_db = ancestor_db.clone();

        sleep();

        self_db.group_mut(GROUP1_ID).unwrap().edit_tracking(|g| {
            g.name = "group1_updated_by_self".to_string();
        });

        let result = self_db.merge_with_ancestor(&other_db, &ancestor_db).unwrap();

        assert_eq!(result.warnings.len(), 0, "one-sided group change must not warn");
        assert_eq!(result.events.len(), 0);
        assert_eq!(self_db.group(GROUP1_ID).unwrap().name, "group1_updated_by_self");
    }

    /// Both sides changed a group differently — warning emitted, newest wins.
    #[test]
    fn test_ancestor_group_both_changed_conflict() {
        let ancestor_db = create_test_database();
        let mut self_db = ancestor_db.clone();
        let mut other_db = ancestor_db.clone();

        sleep();

        self_db.group_mut(GROUP1_ID).unwrap().edit_tracking(|g| {
            g.name = "group1_updated_by_self".to_string();
        });

        sleep();

        other_db.group_mut(GROUP1_ID).unwrap().edit_tracking(|g| {
            g.name = "group1_updated_by_other".to_string();
        });

        let result = self_db.merge_with_ancestor(&other_db, &ancestor_db).unwrap();

        assert!(
            result
                .warnings
                .iter()
                .any(|w| w.contains("modified in both databases since the common ancestor")),
            "true group conflict must produce a warning, got: {:?}",
            result.warnings,
        );
        // other is newer, so its name wins
        assert_eq!(self_db.group(GROUP1_ID).unwrap().name, "group1_updated_by_other");
    }

    /// Only other moved a group since ancestor — taken silently, no warning.
    #[test]
    fn test_ancestor_group_moved_in_other_only() {
        let ancestor_db = create_test_database();
        let mut self_db = ancestor_db.clone();
        let mut other_db = ancestor_db.clone();

        sleep();

        other_db
            .group_mut(SUBGROUP1_ID)
            .unwrap()
            .track_changes()
            .move_to(GROUP2_ID)
            .expect("move successful");

        let result = self_db.merge_with_ancestor(&other_db, &ancestor_db).unwrap();

        assert_eq!(result.warnings.len(), 0, "one-sided group move must not warn");
        assert_eq!(result.events.len(), 1);
        assert_eq!(
            self_db.group(SUBGROUP1_ID).unwrap().parent().unwrap().id(),
            GROUP2_ID,
        );
    }

    /// Both sides moved the same group to different parents — newer move wins.
    #[test]
    fn test_ancestor_group_moved_in_both_other_wins() {
        let ancestor_db = create_test_database();
        let mut self_db = ancestor_db.clone();
        let mut other_db = ancestor_db.clone();

        sleep();

        // self moves subgroup1 to root
        self_db
            .group_mut(SUBGROUP1_ID)
            .unwrap()
            .track_changes()
            .move_to(ROOT_GROUP_ID)
            .expect("self move successful");

        sleep();

        // other moves subgroup1 to group2 (later, so wins)
        other_db
            .group_mut(SUBGROUP1_ID)
            .unwrap()
            .track_changes()
            .move_to(GROUP2_ID)
            .expect("other move successful");

        let result = self_db.merge_with_ancestor(&other_db, &ancestor_db).unwrap();

        // group relocation conflicts surface as a location event, not a warning
        assert_eq!(result.events.len(), 1);
        assert_eq!(
            self_db.group(SUBGROUP1_ID).unwrap().parent().unwrap().id(),
            GROUP2_ID,
            "other's (newer) location must win",
        );
    }

    /// Only other updated a custom icon since ancestor — taken silently, no warning.
    #[test]
    fn test_ancestor_icon_one_sided_change_in_other() {
        let mut ancestor_db = create_test_database();

        let icon_id = ancestor_db
            .entry_mut(ENTRY1_ID)
            .unwrap()
            .track_changes()
            .as_mut()
            .set_icon_custom_new(vec![1, 2, 3, 4])
            .id();

        let mut self_db = ancestor_db.clone();
        let mut other_db = ancestor_db.clone();

        sleep();

        {
            let mut icon = other_db.custom_icon_mut(icon_id).unwrap();
            icon.data = vec![5, 6, 7, 8];
            icon.last_modification_time = Some(Times::now());
        }

        let result = self_db.merge_with_ancestor(&other_db, &ancestor_db).unwrap();

        assert_eq!(result.warnings.len(), 0, "one-sided icon change must not warn");
        assert_eq!(result.events.len(), 1);
        assert_eq!(self_db.custom_icon(icon_id).unwrap().data, vec![5, 6, 7, 8]);
    }

    /// Only self updated a custom icon since ancestor — kept silently, no warning.
    #[test]
    fn test_ancestor_icon_one_sided_change_in_self() {
        let mut ancestor_db = create_test_database();

        let icon_id = ancestor_db
            .entry_mut(ENTRY1_ID)
            .unwrap()
            .track_changes()
            .as_mut()
            .set_icon_custom_new(vec![1, 2, 3, 4])
            .id();

        let mut self_db = ancestor_db.clone();
        let other_db = ancestor_db.clone();

        sleep();

        {
            let mut icon = self_db.custom_icon_mut(icon_id).unwrap();
            icon.data = vec![5, 6, 7, 8];
            icon.last_modification_time = Some(Times::now());
        }

        let result = self_db.merge_with_ancestor(&other_db, &ancestor_db).unwrap();

        assert_eq!(result.warnings.len(), 0, "one-sided icon change must not warn");
        assert_eq!(result.events.len(), 0);
        assert_eq!(self_db.custom_icon(icon_id).unwrap().data, vec![5, 6, 7, 8]);
    }

    /// Both sides updated the same icon differently — warning emitted, newest wins.
    #[test]
    fn test_ancestor_icon_both_changed_conflict() {
        let mut ancestor_db = create_test_database();

        let icon_id = ancestor_db
            .entry_mut(ENTRY1_ID)
            .unwrap()
            .track_changes()
            .as_mut()
            .set_icon_custom_new(vec![1, 2, 3, 4])
            .id();

        let mut self_db = ancestor_db.clone();
        let mut other_db = ancestor_db.clone();

        sleep();

        {
            let mut icon = self_db.custom_icon_mut(icon_id).unwrap();
            icon.data = vec![10, 20, 30, 40];
            icon.last_modification_time = Some(Times::now());
        }

        sleep();

        {
            let mut icon = other_db.custom_icon_mut(icon_id).unwrap();
            icon.data = vec![50, 60, 70, 80];
            icon.last_modification_time = Some(Times::now());
        }

        let result = self_db.merge_with_ancestor(&other_db, &ancestor_db).unwrap();

        assert!(
            result
                .warnings
                .iter()
                .any(|w| w.contains("modified in both databases since the common ancestor")),
            "true icon conflict must produce a warning, got: {:?}",
            result.warnings,
        );
        // other is newer, so its data wins
        assert_eq!(self_db.custom_icon(icon_id).unwrap().data, vec![50, 60, 70, 80]);
    }

    // ------------------------------------------------------------------
    // Three-way state-space coverage beyond the original PR tests:
    // deletions, no-ops, creations, and the edge arms of the decision
    // gates — enumerating the (self x other relative to ancestor) space.
    // ------------------------------------------------------------------

    #[test]
    fn test_ancestor_unchanged_everywhere_is_a_noop() {
        let ancestor_db = create_test_database();
        let mut self_db = ancestor_db.clone();
        let other_db = ancestor_db.clone();

        let result = self_db.merge_with_ancestor(&other_db, &ancestor_db).unwrap();
        assert_eq!(result.events.len(), 0, "{:?}", result.events);
        assert_eq!(result.warnings.len(), 0, "{:?}", result.warnings);
    }

    #[test]
    fn test_ancestor_deletion_in_other_applies() {
        let ancestor_db = create_test_database();
        let mut self_db = ancestor_db.clone();
        let mut other_db = ancestor_db.clone();

        sleep();
        other_db.entry_mut(ENTRY1_ID).unwrap().track_changes().remove();

        let result = self_db.merge_with_ancestor(&other_db, &ancestor_db).unwrap();
        assert!(self_db.entry(ENTRY1_ID).is_none(), "deletion in other must apply");
        assert_eq!(result.events.len(), 1);
        assert!(self_db.deleted_objects.contains_key(&ENTRY1_ID.uuid()));
    }

    #[test]
    fn test_ancestor_deletion_in_self_is_not_resurrected() {
        let ancestor_db = create_test_database();
        let mut self_db = ancestor_db.clone();
        let other_db = ancestor_db.clone();

        sleep();
        self_db.entry_mut(ENTRY1_ID).unwrap().track_changes().remove();

        let result = self_db.merge_with_ancestor(&other_db, &ancestor_db).unwrap();
        assert!(
            self_db.entry(ENTRY1_ID).is_none(),
            "an entry deleted here and untouched there must stay deleted"
        );
        assert_eq!(result.events.len(), 0, "{:?}", result.events);
    }

    #[test]
    fn test_ancestor_deletion_loses_to_later_edit_in_self() {
        let ancestor_db = create_test_database();
        let mut self_db = ancestor_db.clone();
        let mut other_db = ancestor_db.clone();

        sleep();
        other_db.entry_mut(ENTRY1_ID).unwrap().track_changes().remove();

        sleep();
        self_db.entry_mut(ENTRY1_ID).unwrap().edit_tracking(|e| {
            e.set_unprotected(fields::TITLE, "edited_after_the_deletion");
        });

        let result = self_db.merge_with_ancestor(&other_db, &ancestor_db).unwrap();
        assert_eq!(
            self_db.entry(ENTRY1_ID).unwrap().get(fields::TITLE),
            Some("edited_after_the_deletion"),
            "an edit newer than the deletion must win"
        );
        assert_eq!(result.events.len(), 0, "{:?}", result.events);
    }

    #[test]
    fn test_ancestor_deletion_in_self_loses_to_later_edit_in_other() {
        let ancestor_db = create_test_database();
        let mut self_db = ancestor_db.clone();
        let mut other_db = ancestor_db.clone();

        sleep();
        self_db.entry_mut(ENTRY1_ID).unwrap().track_changes().remove();

        sleep();
        other_db.entry_mut(ENTRY1_ID).unwrap().edit_tracking(|e| {
            e.set_unprotected(fields::TITLE, "edited_after_the_deletion");
        });

        let result = self_db.merge_with_ancestor(&other_db, &ancestor_db).unwrap();
        let entry = self_db.entry(ENTRY1_ID).expect("entry must be re-added");
        assert_eq!(entry.get(fields::TITLE), Some("edited_after_the_deletion"));
        assert_eq!(result.events.len(), 1);
    }

    #[test]
    fn test_ancestor_deleted_in_both_stays_deleted() {
        let ancestor_db = create_test_database();
        let mut self_db = ancestor_db.clone();
        let mut other_db = ancestor_db.clone();

        sleep();
        self_db.entry_mut(ENTRY1_ID).unwrap().track_changes().remove();
        other_db.entry_mut(ENTRY1_ID).unwrap().track_changes().remove();

        let result = self_db.merge_with_ancestor(&other_db, &ancestor_db).unwrap();
        assert!(self_db.entry(ENTRY1_ID).is_none());
        assert_eq!(result.events.len(), 0, "{:?}", result.events);
        assert_eq!(result.warnings.len(), 0, "{:?}", result.warnings);
    }

    #[test]
    fn test_ancestor_entry_created_in_self_survives() {
        let ancestor_db = create_test_database();
        let mut self_db = ancestor_db.clone();
        let other_db = ancestor_db.clone();

        sleep();
        let new_id = {
            let mut root = self_db.root_mut();
            let mut e = root.add_entry();
            e.set_unprotected(fields::TITLE, "created_after_ancestor");
            e.times.last_modification = Some(Times::now());
            e.id()
        };

        let result = self_db.merge_with_ancestor(&other_db, &ancestor_db).unwrap();
        assert!(
            self_db.entry(new_id).is_some(),
            "a new entry must survive the merge"
        );
        assert_eq!(result.events.len(), 0, "{:?}", result.events);
    }

    /// The equal-timestamp refusal survives even with a true ancestor: an
    /// entry whose content changed without its clock is an invariant
    /// violation regardless of what the ancestor says.
    #[test]
    fn test_ancestor_equal_timestamp_divergence_still_errors() {
        let ancestor_db = create_test_database();
        let mut self_db = ancestor_db.clone();
        let mut other_db = ancestor_db.clone();

        other_db.entries.get_mut(&ENTRY1_ID).unwrap().fields.insert(
            fields::TITLE.to_string(),
            Value::unprotected("changed_without_stamp"),
        );

        assert!(matches!(
            self_db.merge_with_ancestor(&other_db, &ancestor_db),
            Err(MergeError::EntryModificationTimeNotUpdated(_))
        ));
    }

    #[test]
    fn test_ancestor_group_equal_timestamp_divergence_still_errors() {
        let ancestor_db = create_test_database();
        let mut self_db = ancestor_db.clone();
        let mut other_db = ancestor_db.clone();

        other_db.groups.get_mut(&GROUP1_ID).unwrap().name = "renamed_without_stamp".to_string();

        assert!(matches!(
            self_db.merge_with_ancestor(&other_db, &ancestor_db),
            Err(MergeError::GroupModificationTimeNotUpdated(_))
        ));
    }

    /// The conflict warning is gated on the ancestor entry carrying a
    /// modification timestamp; without one the merge cannot age the sides
    /// against the ancestor and resolves silently by newest-wins.
    #[test]
    fn test_ancestor_without_timestamp_resolves_silently() {
        let base = create_test_database();
        let mut ancestor_db = base.clone();
        ancestor_db
            .entries
            .get_mut(&ENTRY1_ID)
            .unwrap()
            .times
            .last_modification = None;
        let mut self_db = base.clone();
        let mut other_db = base.clone();

        sleep();
        self_db.entry_mut(ENTRY1_ID).unwrap().edit_tracking(|e| {
            e.set_unprotected(fields::TITLE, "updated_in_self");
        });
        sleep();
        other_db.entry_mut(ENTRY1_ID).unwrap().edit_tracking(|e| {
            e.set_unprotected(fields::TITLE, "updated_in_other");
        });

        let result = self_db.merge_with_ancestor(&other_db, &ancestor_db).unwrap();
        assert_eq!(
            result.warnings.len(),
            0,
            "no ancestor clock, no conflict warning: {:?}",
            result.warnings
        );
        assert_eq!(
            self_db.entry(ENTRY1_ID).unwrap().get(fields::TITLE),
            Some("updated_in_other"),
            "newest still wins"
        );
    }

    /// Both conflict directions preserve the losing value in history. The
    /// source-newer direction always did (see
    /// test_ancestor_true_conflict_warns_and_newest_wins); the dest-newer
    /// direction used to drop the other side's value entirely — not live,
    /// not in history.
    #[test]
    fn test_ancestor_conflict_where_self_is_newer_preserves_other_in_history() {
        let ancestor_db = create_test_database();
        let mut self_db = ancestor_db.clone();
        let mut other_db = ancestor_db.clone();

        sleep();
        other_db.entry_mut(ENTRY1_ID).unwrap().edit_tracking(|e| {
            e.set_unprotected(fields::TITLE, "entry1_updated_in_other");
        });
        sleep();
        self_db.entry_mut(ENTRY1_ID).unwrap().edit_tracking(|e| {
            e.set_unprotected(fields::TITLE, "entry1_updated_in_self");
        });

        let result = self_db.merge_with_ancestor(&other_db, &ancestor_db).unwrap();
        assert_eq!(result.warnings.len(), 1, "{:?}", result.warnings);
        assert_eq!(
            self_db.entry(ENTRY1_ID).unwrap().get(fields::TITLE),
            Some("entry1_updated_in_self"),
        );

        let history = self_db.entry(ENTRY1_ID).unwrap().history.clone().unwrap();
        assert_history_ordered(&history);
        assert!(
            history
                .entries
                .iter()
                .any(|e| e.get(fields::TITLE) == Some("entry1_updated_in_other")),
            "the losing OTHER value must survive in history",
        );
    }

    /// The same guarantee through the plain two-way entry point.
    #[test]
    fn test_two_way_conflict_where_self_is_newer_preserves_other_in_history() {
        let base = create_test_database();
        let mut self_db = base.clone();
        let mut other_db = base.clone();

        sleep();
        other_db.entry_mut(ENTRY1_ID).unwrap().edit_tracking(|e| {
            e.set_unprotected(fields::TITLE, "entry1_updated_in_other");
        });
        sleep();
        self_db.entry_mut(ENTRY1_ID).unwrap().edit_tracking(|e| {
            e.set_unprotected(fields::TITLE, "entry1_updated_in_self");
        });

        self_db.merge(&other_db).unwrap();
        assert_eq!(
            self_db.entry(ENTRY1_ID).unwrap().get(fields::TITLE),
            Some("entry1_updated_in_self"),
        );
        let history = self_db.entry(ENTRY1_ID).unwrap().history.clone().unwrap();
        assert!(
            history
                .entries
                .iter()
                .any(|e| e.get(fields::TITLE) == Some("entry1_updated_in_other")),
            "the losing OTHER value must survive in history",
        );
    }

    /// Re-merging the same source must not duplicate the preserved loser.
    #[test]
    fn test_conflict_loser_preservation_is_idempotent() {
        let ancestor_db = create_test_database();
        let mut self_db = ancestor_db.clone();
        let mut other_db = ancestor_db.clone();

        sleep();
        other_db.entry_mut(ENTRY1_ID).unwrap().edit_tracking(|e| {
            e.set_unprotected(fields::TITLE, "entry1_updated_in_other");
        });
        sleep();
        self_db.entry_mut(ENTRY1_ID).unwrap().edit_tracking(|e| {
            e.set_unprotected(fields::TITLE, "entry1_updated_in_self");
        });

        self_db.merge_with_ancestor(&other_db, &ancestor_db).unwrap();
        let len_after_first = self_db
            .entry(ENTRY1_ID)
            .unwrap()
            .history
            .clone()
            .unwrap()
            .entries
            .len();
        self_db.merge_with_ancestor(&other_db, &ancestor_db).unwrap();
        let len_after_second = self_db
            .entry(ENTRY1_ID)
            .unwrap()
            .history
            .clone()
            .unwrap()
            .entries
            .len();
        assert_eq!(
            len_after_first, len_after_second,
            "no duplicate history rows on re-merge"
        );
    }

    /// Identical values reached at different times are not a conflict and
    /// must not pollute history with a phantom loser.
    #[test]
    fn test_dest_newer_with_identical_content_records_nothing() {
        let ancestor_db = create_test_database();
        let mut self_db = ancestor_db.clone();
        let mut other_db = ancestor_db.clone();

        sleep();
        other_db.entry_mut(ENTRY1_ID).unwrap().edit_tracking(|e| {
            e.set_unprotected(fields::TITLE, "same_value");
        });
        sleep();
        self_db.entry_mut(ENTRY1_ID).unwrap().edit_tracking(|e| {
            e.set_unprotected(fields::TITLE, "same_value");
        });

        self_db.merge_with_ancestor(&other_db, &ancestor_db).unwrap();
        let history = self_db.entry(ENTRY1_ID).unwrap().history.clone().unwrap();
        assert!(
            !history
                .entries
                .iter()
                .any(|e| e.get(fields::TITLE) == Some("same_value")),
            "identical content is not a loser to record",
        );
    }

    #[test]
    fn test_ancestor_icon_deletion_applies() {
        let mut ancestor_db = create_test_database();
        let icon_id = ancestor_db
            .entry_mut(ENTRY1_ID)
            .unwrap()
            .track_changes()
            .set_icon_custom_new(vec![1, 2, 3, 4])
            .id();
        let mut self_db = ancestor_db.clone();
        let mut other_db = ancestor_db.clone();

        sleep();
        other_db.custom_icons.remove(&icon_id);
        other_db
            .deleted_objects
            .insert(icon_id.uuid(), Some(Times::now()));

        let result = self_db.merge_with_ancestor(&other_db, &ancestor_db).unwrap();
        assert!(self_db.custom_icon(icon_id).is_none(), "icon deletion must apply");
        assert!(result
            .events
            .iter()
            .any(|e| matches!(e.event_type, MergeEventType::Deleted)));
    }

    #[test]
    fn test_ancestor_icon_deletion_loses_to_later_modification() {
        let mut ancestor_db = create_test_database();
        let icon_id = ancestor_db
            .entry_mut(ENTRY1_ID)
            .unwrap()
            .track_changes()
            .set_icon_custom_new(vec![1, 2, 3, 4])
            .id();
        let mut self_db = ancestor_db.clone();
        let mut other_db = ancestor_db.clone();

        sleep();
        self_db.custom_icons.remove(&icon_id);
        self_db.deleted_objects.insert(icon_id.uuid(), Some(Times::now()));

        sleep();
        {
            let mut icon = other_db.custom_icon_mut(icon_id).unwrap();
            icon.data = vec![9, 9, 9];
            icon.last_modification_time = Some(Times::now());
        }

        let _result = self_db.merge_with_ancestor(&other_db, &ancestor_db).unwrap();
        let icon = self_db
            .custom_icon(icon_id)
            .expect("an icon modified after its deletion must be re-added");
        assert_eq!(icon.data, vec![9, 9, 9]);
    }

    /// Equal icon timestamps with different data warn rather than error —
    /// pins the icon counterpart of the entry/group refusal.
    #[test]
    fn test_ancestor_icon_equal_timestamp_divergence_warns() {
        let mut ancestor_db = create_test_database();
        let icon_id = ancestor_db
            .entry_mut(ENTRY1_ID)
            .unwrap()
            .track_changes()
            .set_icon_custom_new(vec![1, 2, 3, 4])
            .id();
        let mut self_db = ancestor_db.clone();
        let mut other_db = ancestor_db.clone();

        other_db.custom_icons.get_mut(&icon_id).unwrap().data = vec![5, 6, 7, 8];

        let result = self_db.merge_with_ancestor(&other_db, &ancestor_db).unwrap();
        assert!(
            result.warnings.iter().any(|w| w.contains("Custom icons")),
            "{:?}",
            result.warnings
        );
        assert_eq!(
            self_db.custom_icon(icon_id).unwrap().data,
            vec![1, 2, 3, 4],
            "destination side is kept"
        );
    }

    /// What a KeePassXC 2.7.12 save materializes on untouched objects must
    /// merge as a clean no-op, not a refusal.
    #[test]
    fn test_another_clients_serialization_dialect_is_not_divergence() {
        let mut destination_db = create_test_database();
        let mut source_db = destination_db.clone();

        for entry in source_db.entries.values_mut() {
            entry.fields.insert("Notes".to_string(), Value::unprotected(""));
            entry.autotype = Some(AutoType {
                enabled: true,
                default_sequence: None,
                data_transfer_obfuscation: DataTransferObfuscation::None,
                associations: vec![],
            });
            entry.icon = Some(Icon::BuiltIn(0));
        }
        for group in source_db.groups.values_mut() {
            group.icon = Some(Icon::BuiltIn(48));
            group.is_expanded = false;
            group.last_top_visible_entry =
                Some(EntryId::from_uuid(uuid!("00000000-0000-0000-0000-000000000000")));
        }

        let result = destination_db.merge(&source_db).unwrap();
        assert_eq!(result.warnings.len(), 0, "{:?}", result.warnings);
        assert_eq!(result.events.len(), 0, "{:?}", result.events);
    }

    /// A real value difference at an equal modification time still refuses.
    #[test]
    fn test_real_divergence_at_equal_timestamps_still_errors() {
        let mut destination_db = create_test_database();
        let mut source_db = destination_db.clone();
        source_db
            .entries
            .get_mut(&ENTRY1_ID)
            .unwrap()
            .fields
            .insert("Notes".to_string(), Value::unprotected("actual content"));

        assert!(matches!(
            destination_db.merge(&source_db),
            Err(MergeError::EntryModificationTimeNotUpdated(_))
        ));
    }

    /// Only content — field values and tags — counts as divergence, and a
    /// real difference in it always does.
    #[test]
    fn test_divergence_compares_content_and_nothing_else() {
        let db = create_test_database();
        let a = db.entries.get(&ENTRY1_ID).unwrap().clone();

        let mut b = a.clone();
        b.autotype = Some(AutoType {
            enabled: false,
            default_sequence: Some("{USERNAME}{TAB}{PASSWORD}{ENTER}".to_string()),
            data_transfer_obfuscation: DataTransferObfuscation::None,
            associations: vec![],
        });
        b.icon = Some(Icon::BuiltIn(5));
        b.parent = GROUP2_ID;
        b.previous_parent_group = Some(ROOT_GROUP_ID);
        b.fields.insert("Notes".to_string(), Value::unprotected(""));
        assert!(
            !super::have_entries_diverged(&a, &b),
            "auto-type, icons, location, and empty fields are not content"
        );

        let mut b = a.clone();
        b.fields.insert("Notes".to_string(), Value::unprotected("text"));
        assert!(super::have_entries_diverged(&a, &b), "a real note is content");

        let mut a2 = a.clone();
        a2.fields.insert("PIN".to_string(), Value::protected("1234"));
        let mut b = a2.clone();
        b.fields.insert("PIN".to_string(), Value::unprotected("1234"));
        assert!(
            !super::have_entries_diverged(&a2, &b),
            "the protection flag is a memory attribute, not content"
        );
        let mut b = a2.clone();
        b.fields.insert("PIN".to_string(), Value::protected("9999"));
        assert!(
            super::have_entries_diverged(&a2, &b),
            "a changed value is content"
        );

        let mut a2 = a.clone();
        a2.tags = vec!["work".to_string(), "bank".to_string()];
        let mut b = a2.clone();
        b.tags = vec!["bank".to_string(), "work".to_string()];
        assert!(!super::have_entries_diverged(&a2, &b), "tag order is dialect");
        let mut b = a2.clone();
        b.tags.push("shared".to_string());
        assert!(super::have_entries_diverged(&a2, &b), "a new tag is content");

        let ga = db.groups.get(&GROUP1_ID).unwrap().clone();

        let mut gb = ga.clone();
        gb.icon = Some(Icon::BuiltIn(48));
        gb.is_expanded = !gb.is_expanded;
        gb.last_top_visible_entry = Some(ENTRY1_ID);
        gb.notes = Some(String::new());
        assert!(
            !super::have_groups_diverged(&ga, &gb),
            "view state, icons, and empty notes are not content"
        );

        let mut gb = ga.clone();
        gb.name = "renamed".to_string();
        assert!(super::have_groups_diverged(&ga, &gb), "a rename is content");

        // Icon reconciliation compares name and data, never the derived
        // back-reference bookkeeping.
        let db2 = {
            let mut db2 = Database::new();
            let root = db2.root().id();
            db2.group_mut(root)
                .unwrap()
                .add_entry()
                .set_icon_custom_new(vec![1, 2, 3]);
            db2
        };
        let ia = db2.iter_all_custom_icons().next().unwrap().clone();
        let mut ib = ia.clone();
        ib.entries.clear();
        assert!(
            !super::have_icons_diverged(&ia, &ib),
            "back-references are not content"
        );
        let mut ib = ia.clone();
        ib.data = vec![9, 9, 9];
        assert!(super::have_icons_diverged(&ia, &ib), "image data is content");
    }
}