cdk 0.16.0

Core Cashu Development Kit library implementing the Cashu protocol
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
//! Unit tests for the swap saga implementation
//!
//! These tests verify the swap saga pattern using in-memory mints and databases,
//! without requiring external dependencies like Lightning nodes.

use std::sync::Arc;

use cdk_common::nuts::{Proofs, ProofsMethods};
use cdk_common::{Amount, State};

use super::SwapSaga;
use crate::mint::swap::Mint;
use crate::mint::Verification;
use crate::test_helpers::mint::{
    clear_fail_for, create_test_blinded_messages, create_test_mint, set_fail_for,
};

/// Helper to create a verification result for testing
fn create_verification(amount: Amount) -> Verification {
    Verification {
        amount: amount.with_unit(cdk_common::nuts::CurrencyUnit::Sat),
    }
}

/// Helper to create test proofs for swapping using the mint's process
async fn create_swap_inputs(mint: &Mint, amount: Amount) -> (Proofs, Verification) {
    let proofs = crate::test_helpers::mint::mint_test_proofs(mint, amount)
        .await
        .expect("Failed to create test proofs");

    let verification = create_verification(amount);

    (proofs, verification)
}

/// Tests that a SwapSaga can be created in the Initial state.
///
/// # What This Tests
/// - SwapSaga::new() creates a saga in the Initial state
/// - The typestate pattern ensures only Initial state is accessible after creation
/// - No database operations occur during construction
///
/// # Success Criteria
/// - Saga can be instantiated without errors
/// - Saga is in Initial state (enforced by type system)
#[tokio::test]
async fn test_swap_saga_initial_state_creation() {
    let mint = create_test_mint().await.unwrap();
    let db = mint.localstore();
    let pubsub = mint.pubsub_manager();

    let _saga = SwapSaga::new(&mint, db, pubsub);

    // If we can create the saga, we're in the Initial state
    // This is verified by the type system - only SwapSaga<Initial> can be created with new()
}

/// Tests the complete happy path flow through all sagas.
///
/// # What This Tests
/// - Initial -> SetupComplete -> Signed -> Response state transitions
/// - Database transactions commit successfully at each stage
/// - Input proofs are marked as Pending during setup, then Spent after finalization
/// - Output signatures are generated and returned correctly
/// - Compensations are cleared on successful completion
///
/// # Flow
/// 1. Create saga in Initial state
/// 2. setup_swap: Transition to SetupComplete (TX1: add proofs + blinded messages)
/// 3. sign_outputs: Transition to Signed (blind signing, no DB operations)
/// 4. finalize: Complete saga (TX2: add signatures, mark proofs spent)
///
/// # Success Criteria
/// - All state transitions succeed
/// - Response contains correct number of signatures
/// - All input proofs are marked as Spent
/// - No errors occur during the entire flow
#[tokio::test]
async fn test_swap_saga_full_flow_success() {
    let mint = create_test_mint().await.unwrap();

    let amount = Amount::from(100);
    let (input_proofs, input_verification) = create_swap_inputs(&mint, amount).await;

    let (output_blinded_messages, _pre_mint) =
        create_test_blinded_messages(&mint, amount).await.unwrap();

    let db = mint.localstore();
    let pubsub = mint.pubsub_manager();

    let saga = SwapSaga::new(&mint, db, pubsub);

    let saga = saga
        .setup_swap(
            &input_proofs,
            &output_blinded_messages,
            None,
            input_verification,
        )
        .await
        .expect("Setup should succeed");

    let saga = saga.sign_outputs().await.expect("Signing should succeed");

    let response = saga.finalize().await.expect("Finalize should succeed");

    assert_eq!(
        response.signatures.len(),
        output_blinded_messages.len(),
        "Should have signatures for all outputs"
    );

    let ys = input_proofs.ys().unwrap();
    let states = mint
        .localstore()
        .get_proofs_states(&ys)
        .await
        .expect("Failed to get proof states");

    for state in states {
        assert_eq!(
            state.unwrap(),
            State::Spent,
            "Input proofs should be marked as spent"
        );
    }
}

/// Tests the Initial -> SetupComplete state transition.
///
/// # What This Tests
/// - setup_swap() successfully transitions saga from Initial to SetupComplete state
/// - State data contains blinded messages and input proof Y values
/// - Database transaction (TX1) commits successfully
/// - Input proofs are marked as Pending (not Spent)
/// - Compensation action is registered for potential rollback
///
/// # Database Operations (TX1)
/// 1. Verify transaction is balanced
/// 2. Add input proofs to database
/// 3. Update proof states to Pending
/// 4. Add output blinded messages to database
/// 5. Commit transaction
///
/// # Success Criteria
/// - Saga transitions to SetupComplete state
/// - State data correctly stores blinded messages and input Ys
/// - All input proofs have state = Pending in database
#[tokio::test]
async fn test_swap_saga_setup_transition() {
    let mint = create_test_mint().await.unwrap();

    let amount = Amount::from(64);
    let (input_proofs, input_verification) = create_swap_inputs(&mint, amount).await;

    let (output_blinded_messages, _) = create_test_blinded_messages(&mint, amount).await.unwrap();

    let db = mint.localstore();
    let pubsub = mint.pubsub_manager();

    let saga = SwapSaga::new(&mint, db, pubsub);

    let saga = saga
        .setup_swap(
            &input_proofs,
            &output_blinded_messages,
            None,
            input_verification,
        )
        .await
        .expect("Setup should succeed");

    assert_eq!(
        saga.state_data.blinded_messages.len(),
        output_blinded_messages.len(),
        "SetupComplete state should contain blinded messages"
    );

    assert_eq!(
        saga.state_data.ys.len(),
        input_proofs.len(),
        "SetupComplete state should contain input ys"
    );

    let ys = input_proofs.ys().unwrap();
    let states = mint
        .localstore()
        .get_proofs_states(&ys)
        .await
        .expect("Failed to get proof states");

    for state in states {
        assert_eq!(
            state.unwrap(),
            State::Pending,
            "Input proofs should be marked as pending after setup"
        );
    }
}

/// Tests the SetupComplete -> Signed state transition.
///
/// # What This Tests
/// - sign_outputs() successfully transitions saga from SetupComplete to Signed state
/// - Blind signatures are generated for all output blinded messages
/// - No database operations occur during signing (cryptographic operation only)
/// - State data contains signatures matching the number of blinded messages
///
/// # Operations
/// 1. Performs blind signing on blinded messages (non-transactional)
/// 2. Stores signatures in Signed state
/// 3. Preserves blinded messages and input Ys from previous state
///
/// # Success Criteria
/// - Saga transitions to Signed state
/// - Number of signatures equals number of blinded messages
/// - Compensations are still registered (cleared only on finalize)
#[tokio::test]
async fn test_swap_saga_sign_outputs_transition() {
    let mint = create_test_mint().await.unwrap();

    let amount = Amount::from(128);
    let (input_proofs, input_verification) = create_swap_inputs(&mint, amount).await;

    let (output_blinded_messages, _) = create_test_blinded_messages(&mint, amount).await.unwrap();

    let db = mint.localstore();
    let pubsub = mint.pubsub_manager();

    let saga = SwapSaga::new(&mint, db, pubsub);

    let saga = saga
        .setup_swap(
            &input_proofs,
            &output_blinded_messages,
            None,
            input_verification,
        )
        .await
        .expect("Setup should succeed");

    let saga = saga.sign_outputs().await.expect("Signing should succeed");

    assert_eq!(
        saga.state_data.signatures.len(),
        output_blinded_messages.len(),
        "Signed state should contain signatures for all outputs"
    );
}

/// Tests that duplicate input proofs are rejected during setup.
///
/// # What This Tests
/// - Database detects and rejects duplicate proof additions
/// - setup_swap() fails with appropriate error (TokenPending or duplicate error)
/// - Transaction is rolled back, leaving no partial state
///
/// # Attack Vector
/// This prevents an attacker from trying to spend the same proof twice
/// within a single swap request.
///
/// # Success Criteria
/// - setup_swap() returns an error
/// - Database remains unchanged (transaction rollback)
#[tokio::test]
async fn test_swap_saga_duplicate_inputs() {
    let mint = create_test_mint().await.unwrap();

    let amount = Amount::from(100);
    let (mut input_proofs, input_verification) = create_swap_inputs(&mint, amount).await;

    input_proofs.push(input_proofs[0].clone());

    let (output_blinded_messages, _) = create_test_blinded_messages(&mint, amount).await.unwrap();

    let db = mint.localstore();
    let pubsub = mint.pubsub_manager();

    let saga = SwapSaga::new(&mint, db, pubsub);

    let result = saga
        .setup_swap(
            &input_proofs,
            &output_blinded_messages,
            None,
            input_verification,
        )
        .await;

    assert!(result.is_err(), "Setup should fail with duplicate inputs");
}

/// Tests that duplicate output blinded messages are rejected during setup.
///
/// # What This Tests
/// - Database detects and rejects duplicate blinded message additions
/// - setup_swap() fails with DuplicateOutputs error
/// - Transaction is rolled back, leaving no partial state
///
/// # Attack Vector
/// This prevents reuse of blinded messages, which would allow an attacker
/// to receive the same blind signature multiple times.
///
/// # Success Criteria
/// - setup_swap() returns an error
/// - Database remains unchanged (transaction rollback)
#[tokio::test]
async fn test_swap_saga_duplicate_outputs() {
    let mint = create_test_mint().await.unwrap();

    let amount = Amount::from(100);
    let (input_proofs, input_verification) = create_swap_inputs(&mint, amount).await;

    let (mut output_blinded_messages, _) =
        create_test_blinded_messages(&mint, amount).await.unwrap();

    output_blinded_messages.push(output_blinded_messages[0].clone());

    let db = mint.localstore();
    let pubsub = mint.pubsub_manager();

    let saga = SwapSaga::new(&mint, db, pubsub);

    let result = saga
        .setup_swap(
            &input_proofs,
            &output_blinded_messages,
            None,
            input_verification,
        )
        .await;

    assert!(result.is_err(), "Setup should fail with duplicate outputs");
}

/// Tests that unbalanced swap requests are rejected (outputs > inputs).
///
/// # What This Tests
/// - Balance verification detects when output amount exceeds input amount
/// - setup_swap() fails with TransactionUnbalanced error
/// - Transaction is rolled back before any database changes
///
/// # Attack Vector
/// This prevents an attacker from creating value out of thin air by
/// requesting more outputs than they provided in inputs.
///
/// # Success Criteria
/// - setup_swap() returns an error
/// - Database remains unchanged (no proofs or blinded messages added)
#[tokio::test]
async fn test_swap_saga_unbalanced_transaction_more_outputs() {
    let mint = create_test_mint().await.unwrap();

    let input_amount = Amount::from(100);
    let (input_proofs, input_verification) = create_swap_inputs(&mint, input_amount).await;

    let output_amount = Amount::from(150);
    let (output_blinded_messages, _) = create_test_blinded_messages(&mint, output_amount)
        .await
        .unwrap();

    let db = mint.localstore();
    let pubsub = mint.pubsub_manager();

    let saga = SwapSaga::new(&mint, db, pubsub);

    let result = saga
        .setup_swap(
            &input_proofs,
            &output_blinded_messages,
            None,
            input_verification,
        )
        .await;

    assert!(
        result.is_err(),
        "Setup should fail when outputs exceed inputs"
    );
}

/// Tests that compensation actions are registered and cleared correctly.
///
/// # What This Tests
/// - Compensations start empty
/// - setup_swap() registers one compensation action (RemoveSwapSetup)
/// - sign_outputs() preserves compensations (no change)
/// - finalize() clears all compensations on success
///
/// # Saga Pattern
/// Compensations allow rollback if any step fails. They are cleared only
/// when the entire saga completes successfully. This test verifies the
/// lifecycle of compensation tracking.
///
/// # Success Criteria
/// - 0 compensations initially
/// - 1 compensation after setup
/// - 1 compensation after signing
/// - Compensations cleared after successful finalize
#[tokio::test]
async fn test_swap_saga_compensation_clears_on_success() {
    let mint = create_test_mint().await.unwrap();

    let amount = Amount::from(100);
    let (input_proofs, input_verification) = create_swap_inputs(&mint, amount).await;

    let (output_blinded_messages, _) = create_test_blinded_messages(&mint, amount).await.unwrap();

    let db = mint.localstore();
    let pubsub = mint.pubsub_manager();

    let saga = SwapSaga::new(&mint, db, pubsub);

    let compensations_before = saga.compensations.len();

    let saga = saga
        .setup_swap(
            &input_proofs,
            &output_blinded_messages,
            None,
            input_verification,
        )
        .await
        .expect("Setup should succeed");

    let compensations_after_setup = saga.compensations.len();
    assert_eq!(
        compensations_after_setup, 1,
        "Should have one compensation after setup"
    );

    let saga = saga.sign_outputs().await.expect("Signing should succeed");

    let compensations_after_sign = saga.compensations.len();
    assert_eq!(
        compensations_after_sign, 1,
        "Should still have one compensation after signing"
    );

    let _response = saga.finalize().await.expect("Finalize should succeed");

    assert_eq!(
        compensations_before, 0,
        "Should start with no compensations"
    );
}

/// Tests that empty input proofs are rejected during setup.
///
/// # What This Tests
/// - Swap with empty input proofs should fail gracefully
/// - No database changes should occur
///
/// # Success Criteria
/// - setup_swap() returns an error (not panic)
/// - Database remains unchanged
///
/// # Note
/// Empty inputs with non-empty outputs creates an unbalanced transaction
/// (trying to create value from nothing), which should be rejected by
/// the balance verification step.
#[tokio::test]
async fn test_swap_saga_empty_inputs() {
    let mint = create_test_mint().await.unwrap();
    let amount = Amount::from(100);

    let empty_proofs = Proofs::new();
    let (output_blinded_messages, _) = create_test_blinded_messages(&mint, amount).await.unwrap();
    // Verification must match the actual input amount (zero for empty proofs)
    let verification = create_verification(Amount::from(0));

    let db = mint.localstore();
    let pubsub = mint.pubsub_manager();
    let saga = SwapSaga::new(&mint, db, pubsub);

    let result = saga
        .setup_swap(&empty_proofs, &output_blinded_messages, None, verification)
        .await;

    // This should fail because outputs (100) > inputs (0)
    assert!(
        result.is_err(),
        "Empty inputs with non-empty outputs should be rejected (unbalanced)"
    );
}

/// Tests that empty output blinded messages are rejected during setup.
///
/// # What This Tests
/// - Swap with empty output blinded messages should fail gracefully
/// - No database changes should occur
///
/// # Success Criteria
/// - setup_swap() returns an error (not panic)
/// - Database remains unchanged
#[tokio::test]
async fn test_swap_saga_empty_outputs() {
    let mint = create_test_mint().await.unwrap();
    let amount = Amount::from(100);
    let (input_proofs, input_verification) = create_swap_inputs(&mint, amount).await;

    let empty_blinded_messages = vec![];

    let db = mint.localstore();
    let pubsub = mint.pubsub_manager();
    let saga = SwapSaga::new(&mint, db, pubsub);

    let result = saga
        .setup_swap(
            &input_proofs,
            &empty_blinded_messages,
            None,
            input_verification,
        )
        .await;

    assert!(result.is_err(), "Empty outputs should be rejected");
}

/// Tests that both empty inputs and outputs are rejected during setup.
///
/// # What This Tests
/// - Swap with both empty inputs and outputs should fail gracefully
/// - No database changes should occur
///
/// # Success Criteria
/// - setup_swap() returns an error (not panic)
/// - Database remains unchanged
#[tokio::test]
async fn test_swap_saga_both_empty() {
    let mint = create_test_mint().await.unwrap();

    let empty_proofs = Proofs::new();
    let empty_blinded_messages = vec![];
    let verification = create_verification(Amount::from(0));

    let db = mint.localstore();
    let pubsub = mint.pubsub_manager();
    let saga = SwapSaga::new(&mint, db, pubsub);

    let result = saga
        .setup_swap(&empty_proofs, &empty_blinded_messages, None, verification)
        .await;

    assert!(result.is_err(), "Empty swap should be rejected");
}

/// Tests that a saga dropped without finalize does not auto-cleanup.
///
/// # What This Tests
/// - When a saga is dropped after setup but before finalize:
///   - Proofs remain in Pending state (no automatic cleanup)
///   - Blinded messages remain in database
///   - No compensations run automatically on drop
///
/// # Design Choice
/// This tests for resource leaks and documents expected behavior.
/// Cleanup requires explicit compensation or timeout mechanism.
///
/// # Success Criteria
/// - After saga drop, proofs still Pending
/// - Blinded messages still exist in database
#[tokio::test]
async fn test_swap_saga_drop_without_finalize() {
    let mint = create_test_mint().await.unwrap();
    let amount = Amount::from(100);
    let (input_proofs, input_verification) = create_swap_inputs(&mint, amount).await;
    let (output_blinded_messages, _) = create_test_blinded_messages(&mint, amount).await.unwrap();

    let db = mint.localstore();
    let ys = input_proofs.ys().unwrap();

    {
        let pubsub = mint.pubsub_manager();
        let saga = SwapSaga::new(&mint, db.clone(), pubsub);

        let _saga = saga
            .setup_swap(
                &input_proofs,
                &output_blinded_messages,
                None,
                input_verification,
            )
            .await
            .expect("Setup should succeed");

        // Verify setup state
        let states = db.get_proofs_states(&ys).await.unwrap();
        assert!(states.iter().all(|s| s == &Some(State::Pending)));

        // _saga is dropped here without calling finalize
    }

    // Verify state is NOT automatically cleaned up
    let states_after = db.get_proofs_states(&ys).await.unwrap();
    assert!(
        states_after.iter().all(|s| s == &Some(State::Pending)),
        "Proofs should remain Pending after saga drop (no auto-cleanup)"
    );

    // NOTE: This is expected behavior - compensations don't run on drop
    // Cleanup requires either:
    // 1. Explicit compensation call
    // 2. Timeout mechanism to clean up stale Pending proofs
    // 3. Manual intervention
}

/// Tests that a saga dropped after signing loses signatures.
///
/// # What This Tests
/// - When a saga is dropped after signing but before finalize:
///   - Proofs remain Pending
///   - Signatures are lost (not persisted)
///   - Demonstrates the importance of calling finalize
///
/// # Success Criteria
/// - Proofs still Pending after drop
/// - No signatures in database (they were only in memory)
#[tokio::test]
async fn test_swap_saga_drop_after_signing() {
    let mint = create_test_mint().await.unwrap();
    let amount = Amount::from(100);
    let (input_proofs, input_verification) = create_swap_inputs(&mint, amount).await;
    let (output_blinded_messages, _) = create_test_blinded_messages(&mint, amount).await.unwrap();

    let db = mint.localstore();
    let ys = input_proofs.ys().unwrap();
    let _blinded_secrets: Vec<_> = output_blinded_messages
        .iter()
        .map(|bm| bm.blinded_secret)
        .collect();

    {
        let pubsub = mint.pubsub_manager();
        let saga = SwapSaga::new(&mint, db.clone(), pubsub);

        let saga = saga
            .setup_swap(
                &input_proofs,
                &output_blinded_messages,
                None,
                input_verification,
            )
            .await
            .expect("Setup should succeed");

        let saga = saga.sign_outputs().await.expect("Signing should succeed");

        // Verify we're in Signed state (has signatures)
        assert_eq!(
            saga.state_data.signatures.len(),
            output_blinded_messages.len()
        );

        // saga is dropped here - signatures are lost!
    }

    // Verify proofs still Pending
    let states_after = db.get_proofs_states(&ys).await.unwrap();
    assert!(states_after.iter().all(|s| s == &Some(State::Pending)));

    // Verify signatures were NOT persisted (they were only in memory in the saga)
    let signatures = db.get_blind_signatures(&_blinded_secrets).await.unwrap();
    assert!(
        signatures.iter().all(|s| s.is_none()),
        "Signatures should be lost when saga is dropped (never persisted)"
    );

    // This demonstrates why finalize() is critical - without it, the signatures
    // generated during signing are lost and the swap cannot complete
}

/// Tests that compensations execute when sign_outputs() fails.
///
/// # What This Tests
/// - Verify that compensations execute when sign_outputs() fails
/// - Verify that proofs are removed from database (rollback of setup)
/// - Verify that blinded messages are removed from database
/// - Verify that proof states are cleared (no longer Pending)
///
/// # Implementation
/// Uses thread-local failure flag to make blind_sign() fail
///
/// # Success Criteria
/// - Signing fails with error
/// - Proofs are removed from database after failure
/// - Blinded messages are removed after failure
#[tokio::test]
async fn test_swap_saga_compensation_on_signing_failure() {
    let mint = create_test_mint().await.unwrap();
    let amount = Amount::from(100);
    let (input_proofs, input_verification) = create_swap_inputs(&mint, amount).await;
    let (output_blinded_messages, _) = create_test_blinded_messages(&mint, amount).await.unwrap();

    let db = mint.localstore();
    let pubsub = mint.pubsub_manager();
    let saga = SwapSaga::new(&mint, db.clone(), pubsub);

    // Setup should succeed
    let saga = saga
        .setup_swap(
            &input_proofs,
            &output_blinded_messages,
            None,
            input_verification,
        )
        .await
        .expect("Setup should succeed");

    // Verify setup state
    let ys = input_proofs.ys().unwrap();
    let states = db.get_proofs_states(&ys).await.unwrap();
    assert!(states.iter().all(|s| s == &Some(State::Pending)));

    // Enable test failure mode (thread-local, won't affect parallel tests)
    set_fail_for("GENERAL");

    // Attempt signing (should fail due to failure flag)
    let result = saga.sign_outputs().await;

    // Clean up failure flag immediately
    clear_fail_for("GENERAL");

    assert!(result.is_err(), "Signing should fail");

    // Verify compensation executed - proofs removed
    let states_after = db.get_proofs_states(&ys).await.unwrap();
    assert!(
        states_after.iter().all(|s| s.is_none()),
        "Proofs should be removed"
    );

    // Verify blinded messages removed (compensation removes blinded messages, not signatures)
    // Since signatures are never created (only during finalize), we verify that
    // if we query for them, we get None for all (they were never added)
    let _blinded_secrets: Vec<_> = output_blinded_messages
        .iter()
        .map(|bm| bm.blinded_secret)
        .collect();
    let signatures = db.get_blind_signatures(&_blinded_secrets).await.unwrap();
    assert!(
        signatures.iter().all(|s| s.is_none()),
        "No signatures should exist (never created)"
    );
}

/// Tests that double-spend attempts are detected and rejected.
///
/// # What This Tests
/// - First complete swap marks proofs as Spent
/// - Second swap attempt with same proofs fails immediately
/// - Database proof state prevents double-spending
///
/// # Security
/// This is a critical security test. Double-spending would allow an
/// attacker to reuse the same ecash tokens multiple times. The database
/// must detect that proofs are already spent and reject the second swap.
///
/// # Flow
/// 1. Complete first swap successfully (proofs marked Spent)
/// 2. Attempt second swap with same proofs
/// 3. Second setup_swap() fails with TokenAlreadySpent error
///
/// # Success Criteria
/// - First swap completes successfully
/// - Second swap fails with error
/// - Proofs remain in Spent state
#[tokio::test]
async fn test_swap_saga_double_spend_detection() {
    let mint = create_test_mint().await.unwrap();

    let amount = Amount::from(100);
    let (input_proofs, input_verification) = create_swap_inputs(&mint, amount).await;

    let (output_blinded_messages_1, _) = create_test_blinded_messages(&mint, amount).await.unwrap();
    let (output_blinded_messages_2, _) = create_test_blinded_messages(&mint, amount).await.unwrap();

    let db = mint.localstore();
    let pubsub = mint.pubsub_manager();

    let saga1 = SwapSaga::new(&mint, db.clone(), pubsub.clone());

    let saga1 = saga1
        .setup_swap(
            &input_proofs,
            &output_blinded_messages_1,
            None,
            input_verification.clone(),
        )
        .await
        .expect("First setup should succeed");

    let saga1 = saga1
        .sign_outputs()
        .await
        .expect("First signing should succeed");

    let _response1 = saga1
        .finalize()
        .await
        .expect("First finalize should succeed");

    let saga2 = SwapSaga::new(&mint, db, pubsub);

    let result = saga2
        .setup_swap(
            &input_proofs,
            &output_blinded_messages_2,
            None,
            input_verification,
        )
        .await;

    assert!(
        result.is_err(),
        "Second setup should fail due to double-spend"
    );
}

/// Tests that pending proofs are detected and rejected.
///
/// # What This Tests
/// - First swap marks proofs as Pending during setup
/// - Second swap attempt with same proofs fails immediately
/// - Database proof state prevents concurrent use of same proofs
///
/// # Concurrency Protection
/// When proofs are marked Pending, they are reserved for an in-progress
/// swap. No other swap should be able to use them until the first swap
/// completes or rolls back.
///
/// # Flow
/// 1. Start first swap (proofs marked Pending)
/// 2. DO NOT finalize first swap
/// 3. Attempt second swap with same proofs
/// 4. Second setup_swap() fails with TokenPending error
///
/// # Success Criteria
/// - First setup succeeds (proofs marked Pending)
/// - Second setup fails with error
/// - Proofs remain in Pending state
#[tokio::test]
async fn test_swap_saga_pending_proof_detection() {
    let mint = create_test_mint().await.unwrap();

    let amount = Amount::from(100);
    let (input_proofs, input_verification) = create_swap_inputs(&mint, amount).await;

    let (output_blinded_messages_1, _) = create_test_blinded_messages(&mint, amount).await.unwrap();
    let (output_blinded_messages_2, _) = create_test_blinded_messages(&mint, amount).await.unwrap();

    let db = mint.localstore();
    let pubsub = mint.pubsub_manager();

    let saga1 = SwapSaga::new(&mint, db.clone(), pubsub.clone());

    let saga1 = saga1
        .setup_swap(
            &input_proofs,
            &output_blinded_messages_1,
            None,
            input_verification.clone(),
        )
        .await
        .expect("First setup should succeed");

    // Keep saga1 in scope to maintain pending proofs
    drop(saga1);

    let saga2 = SwapSaga::new(&mint, db, pubsub);

    let result = saga2
        .setup_swap(
            &input_proofs,
            &output_blinded_messages_2,
            None,
            input_verification,
        )
        .await;

    assert!(
        result.is_err(),
        "Second setup should fail because proofs are pending"
    );
}

/// Tests concurrent swap attempts with the same proofs.
///
/// # What This Tests
/// - Database serialization ensures only one concurrent swap succeeds
/// - Exactly one of N concurrent swaps with same proofs completes
/// - Other swaps fail with TokenPending or TokenAlreadySpent errors
/// - Final proof state is Spent (from the successful swap)
///
/// # Race Condition Protection
/// This test verifies that the saga pattern combined with database
/// transactions provides proper serialization. Even with 3 tasks racing
/// to setup/sign/finalize, only one can succeed.
///
/// # Flow
/// 1. Spawn 3 concurrent tasks, each trying to swap the same proofs
/// 2. Each task creates its own saga and attempts full flow
/// 3. Database ensures only one can mark proofs as Pending/Spent
/// 4. Count successes and failures
///
/// # Success Criteria
/// - Exactly 1 swap succeeds
/// - Exactly 2 swaps fail
/// - All proofs end up in Spent state
#[tokio::test(flavor = "multi_thread", worker_threads = 3)]
async fn test_swap_saga_concurrent_swaps() {
    let mint = Arc::new(create_test_mint().await.unwrap());

    let amount = Amount::from(100);
    let (input_proofs, input_verification) = create_swap_inputs(&mint, amount).await;

    let (output_blinded_messages_1, _) = create_test_blinded_messages(&mint, amount).await.unwrap();
    let (output_blinded_messages_2, _) = create_test_blinded_messages(&mint, amount).await.unwrap();
    let (output_blinded_messages_3, _) = create_test_blinded_messages(&mint, amount).await.unwrap();

    let mint1 = Arc::clone(&mint);
    let mint2 = Arc::clone(&mint);
    let mint3 = Arc::clone(&mint);

    let proofs1 = input_proofs.clone();
    let proofs2 = input_proofs.clone();
    let proofs3 = input_proofs.clone();

    let verification1 = input_verification.clone();
    let verification2 = input_verification.clone();
    let verification3 = input_verification.clone();

    let task1 = tokio::spawn(async move {
        let db = mint1.localstore();
        let pubsub = mint1.pubsub_manager();
        let saga = SwapSaga::new(&mint1, db, pubsub);

        let saga = saga
            .setup_swap(&proofs1, &output_blinded_messages_1, None, verification1)
            .await?;
        let saga = saga.sign_outputs().await?;
        saga.finalize().await
    });

    let task2 = tokio::spawn(async move {
        let db = mint2.localstore();
        let pubsub = mint2.pubsub_manager();
        let saga = SwapSaga::new(&mint2, db, pubsub);

        let saga = saga
            .setup_swap(&proofs2, &output_blinded_messages_2, None, verification2)
            .await?;
        let saga = saga.sign_outputs().await?;
        saga.finalize().await
    });

    let task3 = tokio::spawn(async move {
        let db = mint3.localstore();
        let pubsub = mint3.pubsub_manager();
        let saga = SwapSaga::new(&mint3, db, pubsub);

        let saga = saga
            .setup_swap(&proofs3, &output_blinded_messages_3, None, verification3)
            .await?;
        let saga = saga.sign_outputs().await?;
        saga.finalize().await
    });

    let results = tokio::try_join!(task1, task2, task3).expect("Tasks should complete");

    let mut success_count = 0;
    let mut error_count = 0;

    for result in [results.0, results.1, results.2] {
        match result {
            Ok(_) => success_count += 1,
            Err(_) => error_count += 1,
        }
    }

    assert_eq!(success_count, 1, "Only one concurrent swap should succeed");
    assert_eq!(error_count, 2, "Two concurrent swaps should fail");

    let ys = input_proofs.ys().unwrap();
    let states = mint
        .localstore()
        .get_proofs_states(&ys)
        .await
        .expect("Failed to get proof states");

    for state in states {
        assert_eq!(
            state.unwrap(),
            State::Spent,
            "Proofs should be marked as spent after successful swap"
        );
    }
}

/// Tests that compensations execute when finalize() fails during add_blind_signatures.
///
/// # What This Tests
/// - Verify that compensations execute when finalize() fails at signature addition
/// - Verify that proofs are removed from database (compensation rollback)
/// - Verify that blinded messages are removed from database
/// - Verify that signatures are NOT persisted to database
/// - Transaction rollback + compensation cleanup both occur
///
/// # Implementation
/// Uses thread-local failure flag to inject failure
/// at the signature addition step within the finalize transaction.
///
/// # Success Criteria
/// - Finalize fails with error
/// - Proofs are removed from database after failure
/// - Blinded messages are removed after failure
/// - No signatures persisted to database
#[tokio::test]
async fn test_swap_saga_compensation_on_finalize_add_signatures_failure() {
    let mint = create_test_mint().await.unwrap();
    let amount = Amount::from(100);
    let (input_proofs, input_verification) = create_swap_inputs(&mint, amount).await;
    let (output_blinded_messages, _) = create_test_blinded_messages(&mint, amount).await.unwrap();

    let db = mint.localstore();
    let pubsub = mint.pubsub_manager();
    let saga = SwapSaga::new(&mint, db.clone(), pubsub);

    // Setup and sign should succeed
    let saga = saga
        .setup_swap(
            &input_proofs,
            &output_blinded_messages,
            None,
            input_verification,
        )
        .await
        .expect("Setup should succeed");

    let saga = saga.sign_outputs().await.expect("Signing should succeed");

    // Verify we're in Signed state
    assert_eq!(
        saga.state_data.signatures.len(),
        output_blinded_messages.len()
    );

    // Enable test failure mode for ADD_SIGNATURES (thread-local, won't affect parallel tests)
    set_fail_for("ADD_SIGNATURES");

    // Attempt finalize (should fail due to failure flag)
    let result = saga.finalize().await;

    // Clean up failure flag immediately
    clear_fail_for("ADD_SIGNATURES");

    assert!(result.is_err(), "Finalize should fail");

    // Verify compensation executed - proofs removed
    let ys = input_proofs.ys().unwrap();
    let states_after = db.get_proofs_states(&ys).await.unwrap();
    assert!(
        states_after.iter().all(|s| s.is_none()),
        "Proofs should be removed by compensation"
    );

    // Verify signatures were NOT persisted (transaction rolled back)
    let blinded_secrets: Vec<_> = output_blinded_messages
        .iter()
        .map(|bm| bm.blinded_secret)
        .collect();
    let signatures = db.get_blind_signatures(&blinded_secrets).await.unwrap();
    assert!(
        signatures.iter().all(|s| s.is_none()),
        "Signatures should not be persisted after rollback"
    );
}

/// Tests that compensations execute when finalize() fails during update_proofs_states.
///
/// # What This Tests
/// - Verify that compensations execute when finalize() fails at proof state update
/// - Verify that proofs are removed from database (compensation rollback)
/// - Verify that blinded messages are removed from database
/// - Verify that signatures are NOT persisted to database
/// - Transaction rollback + compensation cleanup both occur
///
/// # Implementation
/// Uses thread-local failure flag to inject failure
/// at the proof state update step within the finalize transaction.
///
/// # Success Criteria
/// - Finalize fails with error
/// - Proofs are removed from database after failure
/// - Blinded messages are removed after failure
/// - No signatures persisted to database
#[tokio::test]
async fn test_swap_saga_compensation_on_finalize_update_proofs_failure() {
    let mint = create_test_mint().await.unwrap();
    let amount = Amount::from(100);
    let (input_proofs, input_verification) = create_swap_inputs(&mint, amount).await;
    let (output_blinded_messages, _) = create_test_blinded_messages(&mint, amount).await.unwrap();

    let db = mint.localstore();
    let pubsub = mint.pubsub_manager();
    let saga = SwapSaga::new(&mint, db.clone(), pubsub);

    // Setup and sign should succeed
    let saga = saga
        .setup_swap(
            &input_proofs,
            &output_blinded_messages,
            None,
            input_verification,
        )
        .await
        .expect("Setup should succeed");

    let saga = saga.sign_outputs().await.expect("Signing should succeed");

    // Verify we're in Signed state
    assert_eq!(
        saga.state_data.signatures.len(),
        output_blinded_messages.len()
    );

    // Enable test failure mode for UPDATE_PROOFS (thread-local, won't affect parallel tests)
    set_fail_for("UPDATE_PROOFS");

    // Attempt finalize (should fail due to failure flag)
    let result = saga.finalize().await;

    // Clean up failure flag immediately
    clear_fail_for("UPDATE_PROOFS");

    assert!(result.is_err(), "Finalize should fail");

    // Verify compensation executed - proofs removed
    let ys = input_proofs.ys().unwrap();
    let states_after = db.get_proofs_states(&ys).await.unwrap();
    assert!(
        states_after.iter().all(|s| s.is_none()),
        "Proofs should be removed by compensation"
    );

    // Verify signatures were NOT persisted (transaction rolled back)
    let blinded_secrets: Vec<_> = output_blinded_messages
        .iter()
        .map(|bm| bm.blinded_secret)
        .collect();
    let signatures = db.get_blind_signatures(&blinded_secrets).await.unwrap();
    assert!(
        signatures.iter().all(|s| s.is_none()),
        "Signatures should not be persisted after rollback"
    );
}

// ==================== PHASE 1: FOUNDATION TESTS ====================
// These tests verify the basic saga persistence mechanism.

/// Tests that saga is persisted to the database after setup.
///
/// # What This Tests
/// - Saga is written to database during setup_swap()
/// - get_saga() can retrieve the persisted state
/// - State content is correct (operation_id, state, blinded_secrets, input_ys)
///
/// # Success Criteria
/// - Saga exists in database after setup
/// - State matches SwapSagaState::SetupComplete
/// - All expected data is present and correct
#[tokio::test]
async fn test_saga_state_persistence_after_setup() {
    let mint = create_test_mint().await.unwrap();
    let db = mint.localstore();

    let amount = Amount::from(100);
    let (input_proofs, verification) = create_swap_inputs(&mint, amount).await;
    let (output_blinded_messages, _) = create_test_blinded_messages(&mint, amount).await.unwrap();

    let pubsub = mint.pubsub_manager();
    let saga = SwapSaga::new(&mint, db.clone(), pubsub);

    let saga = saga
        .setup_swap(&input_proofs, &output_blinded_messages, None, verification)
        .await
        .expect("Setup should succeed");

    let operation_id = saga.state_data.operation.id();

    // Verify saga exists in database
    let saga = {
        let mut tx = db.begin_transaction().await.unwrap();
        let result = tx.get_saga(operation_id).await.expect("Failed to get saga");
        tx.commit().await.unwrap();
        result.expect("Saga should exist after setup")
    };

    // Verify state is SetupComplete
    use cdk_common::mint::{SagaStateEnum, SwapSagaState};
    assert_eq!(
        saga.state,
        SagaStateEnum::Swap(SwapSagaState::SetupComplete),
        "Saga should be SetupComplete"
    );

    // Verify operation_id matches
    assert_eq!(saga.operation_id, *operation_id);

    // Verify blinded_secrets can be looked up by operation_id
    let expected_blinded_secrets: Vec<_> = output_blinded_messages
        .iter()
        .map(|bm| bm.blinded_secret)
        .collect();
    let stored_blinded_secrets = mint
        .localstore()
        .get_blinded_secrets_by_operation_id(&saga.operation_id)
        .await
        .unwrap();
    assert_eq!(stored_blinded_secrets.len(), expected_blinded_secrets.len());
    for bs in &expected_blinded_secrets {
        assert!(
            stored_blinded_secrets.contains(bs),
            "Blinded secret should be stored"
        );
    }

    // Verify input_ys can be looked up by operation_id
    let expected_ys = input_proofs.ys().unwrap();
    let stored_input_ys = mint
        .localstore()
        .get_proof_ys_by_operation_id(&saga.operation_id)
        .await
        .unwrap();
    assert_eq!(stored_input_ys.len(), expected_ys.len());
    for y in &expected_ys {
        assert!(stored_input_ys.contains(y), "Input Y should be stored");
    }
}

/// Tests that saga is deleted after successful finalization.
///
/// # What This Tests
/// - Saga exists after setup
/// - Saga still exists after signing
/// - Saga is DELETED after successful finalize
/// - get_incomplete_sagas() returns empty after success
///
/// # Success Criteria
/// - Saga deleted from database
/// - No incomplete sagas remain
#[tokio::test]
async fn test_saga_deletion_on_success() {
    let mint = create_test_mint().await.unwrap();
    let db = mint.localstore();

    let amount = Amount::from(100);
    let (input_proofs, verification) = create_swap_inputs(&mint, amount).await;
    let (output_blinded_messages, _) = create_test_blinded_messages(&mint, amount).await.unwrap();

    let pubsub = mint.pubsub_manager();
    let saga = SwapSaga::new(&mint, db.clone(), pubsub);

    let saga = saga
        .setup_swap(&input_proofs, &output_blinded_messages, None, verification)
        .await
        .expect("Setup should succeed");

    let operation_id = *saga.state_data.operation.id();

    // Verify saga exists after setup
    let saga_after_setup = {
        let mut tx = db.begin_transaction().await.unwrap();
        let result = tx
            .get_saga(&operation_id)
            .await
            .expect("Failed to get saga");
        tx.commit().await.unwrap();
        result
    };
    assert!(saga_after_setup.is_some(), "Saga should exist after setup");

    let saga = saga.sign_outputs().await.expect("Signing should succeed");

    // Verify saga still exists after signing
    let saga_after_sign = {
        let mut tx = db.begin_transaction().await.unwrap();
        let result = tx
            .get_saga(&operation_id)
            .await
            .expect("Failed to get saga");
        tx.commit().await.unwrap();
        result
    };
    assert!(
        saga_after_sign.is_some(),
        "Saga should still exist after signing"
    );

    let _response = saga.finalize().await.expect("Finalize should succeed");

    // CRITICAL: Verify saga is DELETED after success
    let saga_after_finalize = {
        let mut tx = db.begin_transaction().await.unwrap();
        let result = tx
            .get_saga(&operation_id)
            .await
            .expect("Failed to get saga");
        tx.commit().await.unwrap();
        result
    };
    assert!(
        saga_after_finalize.is_none(),
        "Saga should be deleted after successful finalization"
    );

    // Verify no incomplete sagas exist
    use cdk_common::mint::OperationKind;
    let incomplete = db
        .get_incomplete_sagas(OperationKind::Swap)
        .await
        .expect("Failed to get incomplete sagas");
    assert_eq!(incomplete.len(), 0, "No incomplete sagas should exist");
}

/// Tests querying incomplete sagas.
///
/// # What This Tests
/// - get_incomplete_sagas() returns saga after setup
/// - get_incomplete_sagas() still returns saga after signing
/// - get_incomplete_sagas() returns empty after finalize
/// - Multiple incomplete sagas can be queried
///
/// # Success Criteria
/// - Incomplete saga appears in query results
/// - Completed saga does not appear in query results
#[tokio::test]
async fn test_get_incomplete_sagas_basic() {
    let mint = create_test_mint().await.unwrap();
    let db = mint.localstore();

    let amount = Amount::from(100);
    let (input_proofs_1, verification_1) = create_swap_inputs(&mint, amount).await;
    let (output_blinded_messages_1, _) = create_test_blinded_messages(&mint, amount).await.unwrap();

    let (input_proofs_2, verification_2) = create_swap_inputs(&mint, amount).await;
    let (output_blinded_messages_2, _) = create_test_blinded_messages(&mint, amount).await.unwrap();

    use cdk_common::mint::OperationKind;

    // Initially no incomplete sagas
    let incomplete_initial = db
        .get_incomplete_sagas(OperationKind::Swap)
        .await
        .expect("Failed to get incomplete sagas");
    assert_eq!(incomplete_initial.len(), 0);

    let pubsub = mint.pubsub_manager();

    // Setup first saga
    let saga_1 = SwapSaga::new(&mint, db.clone(), pubsub.clone());
    let saga_1 = saga_1
        .setup_swap(
            &input_proofs_1,
            &output_blinded_messages_1,
            None,
            verification_1,
        )
        .await
        .expect("Setup should succeed");
    let op_id_1 = *saga_1.state_data.operation.id();

    // Should have 1 incomplete saga
    let incomplete_after_1 = db
        .get_incomplete_sagas(OperationKind::Swap)
        .await
        .expect("Failed to get incomplete sagas");
    assert_eq!(incomplete_after_1.len(), 1);
    assert_eq!(incomplete_after_1[0].operation_id, op_id_1);

    // Setup second saga
    let saga_2 = SwapSaga::new(&mint, db.clone(), pubsub.clone());
    let saga_2 = saga_2
        .setup_swap(
            &input_proofs_2,
            &output_blinded_messages_2,
            None,
            verification_2,
        )
        .await
        .expect("Setup should succeed");
    let op_id_2 = *saga_2.state_data.operation.id();

    // Should have 2 incomplete sagas
    let incomplete_after_2 = db
        .get_incomplete_sagas(OperationKind::Swap)
        .await
        .expect("Failed to get incomplete sagas");
    assert_eq!(incomplete_after_2.len(), 2);

    // Finalize first saga
    let saga_1 = saga_1.sign_outputs().await.expect("Signing should succeed");
    let _response_1 = saga_1.finalize().await.expect("Finalize should succeed");

    // Should have 1 incomplete saga (second one still incomplete)
    let incomplete_after_finalize = db
        .get_incomplete_sagas(OperationKind::Swap)
        .await
        .expect("Failed to get incomplete sagas");
    assert_eq!(incomplete_after_finalize.len(), 1);
    assert_eq!(incomplete_after_finalize[0].operation_id, op_id_2);

    // Finalize second saga
    let saga_2 = saga_2.sign_outputs().await.expect("Signing should succeed");
    let _response_2 = saga_2.finalize().await.expect("Finalize should succeed");

    // Should have 0 incomplete sagas
    let incomplete_final = db
        .get_incomplete_sagas(OperationKind::Swap)
        .await
        .expect("Failed to get incomplete sagas");
    assert_eq!(incomplete_final.len(), 0);
}

/// Tests detailed validation of saga content.
///
/// # What This Tests
/// - Operation ID is correct
/// - Operation kind is correct
/// - State enum is correct
/// - Blinded secrets are all present
/// - Input Ys are all present
/// - Timestamps are reasonable (created_at, updated_at)
///
/// # Success Criteria
/// - All fields match expected values
/// - Timestamps are within reasonable range
#[tokio::test]
async fn test_saga_content_validation() {
    let mint = create_test_mint().await.unwrap();
    let db = mint.localstore();

    let amount = Amount::from(100);
    let (input_proofs, verification) = create_swap_inputs(&mint, amount).await;
    let (output_blinded_messages, _) = create_test_blinded_messages(&mint, amount).await.unwrap();

    let expected_ys: Vec<_> = input_proofs.ys().unwrap();
    let expected_blinded_secrets: Vec<_> = output_blinded_messages
        .iter()
        .map(|bm| bm.blinded_secret)
        .collect();

    let pubsub = mint.pubsub_manager();
    let saga = SwapSaga::new(&mint, db.clone(), pubsub);

    let saga = saga
        .setup_swap(&input_proofs, &output_blinded_messages, None, verification)
        .await
        .expect("Setup should succeed");

    let operation_id = *saga.state_data.operation.id();

    // Query saga
    let saga = {
        let mut tx = db.begin_transaction().await.unwrap();
        let result = tx
            .get_saga(&operation_id)
            .await
            .expect("Failed to get saga");
        tx.commit().await.unwrap();
        result.expect("Saga should exist after setup")
    };

    // Validate content
    use cdk_common::mint::{OperationKind, SagaStateEnum, SwapSagaState};
    assert_eq!(saga.operation_id, operation_id);
    assert_eq!(saga.operation_kind, OperationKind::Swap);
    assert_eq!(
        saga.state,
        SagaStateEnum::Swap(SwapSagaState::SetupComplete)
    );

    // Validate blinded secrets can be looked up by operation_id
    let stored_blinded_secrets = mint
        .localstore()
        .get_blinded_secrets_by_operation_id(&saga.operation_id)
        .await
        .unwrap();
    assert_eq!(stored_blinded_secrets.len(), expected_blinded_secrets.len());
    for bs in &expected_blinded_secrets {
        assert!(stored_blinded_secrets.contains(bs));
    }

    // Validate input Ys can be looked up by operation_id
    let stored_input_ys = mint
        .localstore()
        .get_proof_ys_by_operation_id(&saga.operation_id)
        .await
        .unwrap();
    assert_eq!(stored_input_ys.len(), expected_ys.len());
    for y in &expected_ys {
        assert!(stored_input_ys.contains(y));
    }

    // Validate timestamps
    use cdk_common::util::unix_time;
    let now = unix_time();
    assert!(
        saga.created_at <= now,
        "created_at should be <= current time"
    );
    assert!(
        saga.updated_at <= now,
        "updated_at should be <= current time"
    );
    assert!(
        saga.created_at <= saga.updated_at,
        "created_at should be <= updated_at"
    );
}

/// Tests that saga updates are persisted correctly.
///
/// # What This Tests
/// - Saga persisted after setup
/// - updated_at timestamp changes after state updates
/// - Other fields remain unchanged during updates
///
/// # Note
/// Currently sign_outputs() does NOT update saga in the database
/// (the "signed" state is not persisted). This test documents that behavior.
///
/// # Success Criteria
/// - State exists after setup
/// - If state is updated, updated_at increases
/// - Other fields remain consistent
#[tokio::test]
async fn test_saga_state_updates_persisted() {
    let mint = create_test_mint().await.unwrap();
    let db = mint.localstore();

    let amount = Amount::from(100);
    let (input_proofs, verification) = create_swap_inputs(&mint, amount).await;
    let (output_blinded_messages, _) = create_test_blinded_messages(&mint, amount).await.unwrap();

    let pubsub = mint.pubsub_manager();
    let saga = SwapSaga::new(&mint, db.clone(), pubsub);

    let saga = saga
        .setup_swap(&input_proofs, &output_blinded_messages, None, verification)
        .await
        .expect("Setup should succeed");

    let operation_id = *saga.state_data.operation.id();

    // Query saga
    let state_after_setup = {
        let mut tx = db.begin_transaction().await.unwrap();
        let result = tx
            .get_saga(&operation_id)
            .await
            .expect("Failed to get saga");
        tx.commit().await.unwrap();
        result.expect("Saga should exist after setup")
    };

    use cdk_common::mint::{SagaStateEnum, SwapSagaState};
    assert_eq!(
        state_after_setup.state,
        SagaStateEnum::Swap(SwapSagaState::SetupComplete)
    );
    let initial_created_at = state_after_setup.created_at;
    let initial_updated_at = state_after_setup.updated_at;

    // Small delay to ensure timestamp would change if updated
    tokio::time::sleep(std::time::Duration::from_millis(10)).await;

    let saga = saga.sign_outputs().await.expect("Signing should succeed");

    // Query saga
    let state_after_sign = {
        let mut tx = db.begin_transaction().await.unwrap();
        let result = tx
            .get_saga(&operation_id)
            .await
            .expect("Failed to get saga");
        tx.commit().await.unwrap();
        result.expect("Saga should exist after setup")
    };

    // State should still be SetupComplete (not updated to Signed)
    assert_eq!(
        state_after_sign.state,
        SagaStateEnum::Swap(SwapSagaState::SetupComplete),
        "Saga remains SetupComplete (signing doesn't update DB)"
    );

    // Verify other fields unchanged
    assert_eq!(state_after_sign.operation_id, operation_id);
    assert_eq!(state_after_sign.created_at, initial_created_at);

    // updated_at might not change since state wasn't updated
    assert_eq!(state_after_sign.updated_at, initial_updated_at);

    // Finalize and verify state is deleted (not updated)
    let _response = saga.finalize().await.expect("Finalize should succeed");

    // Query saga
    let state_after_finalize = {
        let mut tx = db.begin_transaction().await.unwrap();
        let result = tx
            .get_saga(&operation_id)
            .await
            .expect("Failed to get saga");
        tx.commit().await.unwrap();

        result
    };

    assert!(
        state_after_finalize.is_none(),
        "Saga should be deleted after finalize"
    );
}

// ==================== STARTUP RECOVERY TESTS ====================
// These tests verify the `recover_from_bad_swaps()` startup check that
// cleans up orphaned swap state when the mint restarts.

/// Tests startup recovery when saga is dropped before signing.
///
/// # What This Tests
/// - Saga dropped after setup (proofs PENDING, no signatures)
/// - recover_from_bad_swaps() removes the proofs
/// - Blinded messages are removed
/// - Same proofs can be used in a new swap after recovery
///
/// # Recovery Behavior
/// When no blind signatures exist for an operation_id:
/// - Proofs are removed from database
/// - Blinded messages are removed
/// - User can retry the swap with same proofs
///
/// # Flow
/// 1. Setup swap (proofs marked PENDING)
/// 2. Drop saga without signing
/// 3. Call recover_from_bad_swaps() (simulates mint restart)
/// 4. Verify proofs removed
/// 5. Verify can use same proofs in new swap
///
/// # Success Criteria
/// - Recovery removes proofs completely
/// - Blinded messages removed
/// - Second swap with same proofs succeeds
#[tokio::test]
async fn test_startup_recovery_saga_dropped_before_signing() {
    let mint = create_test_mint().await.unwrap();
    let amount = Amount::from(100);
    let (input_proofs, input_verification) = create_swap_inputs(&mint, amount).await;
    let (output_blinded_messages, _) = create_test_blinded_messages(&mint, amount).await.unwrap();

    let db = mint.localstore();
    let ys = input_proofs.ys().unwrap();

    // Setup swap and drop without signing
    {
        let pubsub = mint.pubsub_manager();
        let saga = SwapSaga::new(&mint, db.clone(), pubsub);

        let _saga = saga
            .setup_swap(
                &input_proofs,
                &output_blinded_messages,
                None,
                input_verification.clone(),
            )
            .await
            .expect("Setup should succeed");

        // Verify proofs are PENDING
        let states = db.get_proofs_states(&ys).await.unwrap();
        assert!(states.iter().all(|s| s == &Some(State::Pending)));

        // Saga dropped here without signing
    }

    // Proofs still PENDING after drop (no auto-cleanup)
    let states_before_recovery = db.get_proofs_states(&ys).await.unwrap();
    assert!(states_before_recovery
        .iter()
        .all(|s| s == &Some(State::Pending)));

    // Simulate mint restart - run recovery
    mint.stop().await.expect("Recovery should succeed");
    mint.start().await.expect("Recovery should succeed");

    // Verify proofs are REMOVED (not just state cleared)
    let states_after_recovery = db.get_proofs_states(&ys).await.unwrap();
    assert!(
        states_after_recovery.iter().all(|s| s.is_none()),
        "Proofs should be removed after recovery (no signatures exist)"
    );

    // Verify we can now use the same proofs in a new swap
    let (new_output_blinded_messages, _) =
        create_test_blinded_messages(&mint, amount).await.unwrap();

    let pubsub = mint.pubsub_manager();
    let new_saga = SwapSaga::new(&mint, db, pubsub);

    let new_saga = new_saga
        .setup_swap(
            &input_proofs,
            &new_output_blinded_messages,
            None,
            input_verification,
        )
        .await
        .expect("Second swap should succeed after recovery");

    let new_saga = new_saga
        .sign_outputs()
        .await
        .expect("Signing should succeed");

    let _response = new_saga.finalize().await.expect("Finalize should succeed");

    // Verify proofs are now SPENT
    let final_states = mint.localstore().get_proofs_states(&ys).await.unwrap();
    assert!(final_states.iter().all(|s| s == &Some(State::Spent)));
}

/// Tests startup recovery when saga is dropped after signing.
///
/// # What This Tests
/// - Saga dropped after signing but before finalize
/// - Signatures exist in memory but were never persisted to database
/// - recover_from_bad_swaps() removes the proofs (no signatures in DB)
/// - Same proofs can be used in a new swap after recovery
///
/// # Recovery Behavior
/// When no blind signatures exist in database for an operation_id:
/// - Proofs are removed from database
/// - User can retry the swap
///
/// Note: Signatures from sign_outputs() are in memory only. They're only
/// persisted during finalize(). So a dropped saga after signing has no
/// signatures in the database.
///
/// # Flow
/// 1. Setup swap and sign outputs
/// 2. Drop saga without finalize (signatures lost)
/// 3. Call recover_from_bad_swaps()
/// 4. Verify proofs removed
/// 5. Verify can use same proofs in new swap
///
/// # Success Criteria
/// - Recovery removes proofs completely
/// - No signatures in database (never persisted)
/// - Second swap with same proofs succeeds
#[tokio::test]
async fn test_startup_recovery_saga_dropped_after_signing() {
    let mint = create_test_mint().await.unwrap();
    let amount = Amount::from(100);
    let (input_proofs, input_verification) = create_swap_inputs(&mint, amount).await;
    let (output_blinded_messages, _) = create_test_blinded_messages(&mint, amount).await.unwrap();

    let db = mint.localstore();
    let ys = input_proofs.ys().unwrap();
    let blinded_secrets: Vec<_> = output_blinded_messages
        .iter()
        .map(|bm| bm.blinded_secret)
        .collect();

    // Setup swap, sign, and drop without finalize
    {
        let pubsub = mint.pubsub_manager();
        let saga = SwapSaga::new(&mint, db.clone(), pubsub);

        let saga = saga
            .setup_swap(
                &input_proofs,
                &output_blinded_messages,
                None,
                input_verification.clone(),
            )
            .await
            .expect("Setup should succeed");

        let _saga = saga.sign_outputs().await.expect("Signing should succeed");

        // Saga dropped here - signatures were in memory only, never persisted
    }

    // Verify proofs still PENDING
    let states_before = db.get_proofs_states(&ys).await.unwrap();
    assert!(states_before.iter().all(|s| s == &Some(State::Pending)));

    // Verify no signatures in database (they were only in memory)
    let sigs_before = db.get_blind_signatures(&blinded_secrets).await.unwrap();
    assert!(sigs_before.iter().all(|s| s.is_none()));

    // Simulate mint restart - run recovery
    mint.stop().await.expect("Recovery should succeed");
    mint.start().await.expect("Recovery should succeed");

    // Verify proofs are REMOVED
    let states_after = db.get_proofs_states(&ys).await.unwrap();
    assert!(
        states_after.iter().all(|s| s.is_none()),
        "Proofs should be removed (no signatures in DB)"
    );

    // Verify we can use the same proofs in a new swap
    let (new_output_blinded_messages, _) =
        create_test_blinded_messages(&mint, amount).await.unwrap();

    let pubsub = mint.pubsub_manager();
    let new_saga = SwapSaga::new(&mint, db, pubsub);

    let new_saga = new_saga
        .setup_swap(
            &input_proofs,
            &new_output_blinded_messages,
            None,
            input_verification,
        )
        .await
        .expect("Second swap should succeed after recovery");

    let new_saga = new_saga
        .sign_outputs()
        .await
        .expect("Signing should succeed");

    let _response = new_saga.finalize().await.expect("Finalize should succeed");
}

/// Tests startup recovery with multiple abandoned operations.
///
/// # What This Tests
/// - Multiple swap operations in different states
/// - recover_from_bad_swaps() processes all operations correctly
/// - Each operation is handled according to its state
///
/// # Test Scenario
/// - Operation A: Dropped after setup (no signatures) → proofs removed
/// - Operation B: Dropped after signing (signatures not persisted) → proofs removed
/// - Operation C: Completed successfully (has signatures, SPENT) → untouched
///
/// # Success Criteria
/// - Operation A proofs removed
/// - Operation B proofs removed
/// - Operation C proofs remain SPENT
/// - All operations processed in single recovery call
#[tokio::test]
async fn test_startup_recovery_multiple_operations() {
    let mint = create_test_mint().await.unwrap();
    let amount = Amount::from(100);

    // Create three separate sets of proofs for three operations
    let (proofs_a, verification_a) = create_swap_inputs(&mint, amount).await;
    let (proofs_b, verification_b) = create_swap_inputs(&mint, amount).await;
    let (proofs_c, verification_c) = create_swap_inputs(&mint, amount).await;

    let (outputs_a, _) = create_test_blinded_messages(&mint, amount).await.unwrap();
    let (outputs_b, _) = create_test_blinded_messages(&mint, amount).await.unwrap();
    let (outputs_c, _) = create_test_blinded_messages(&mint, amount).await.unwrap();

    let db = mint.localstore();
    let pubsub = mint.pubsub_manager();

    let ys_a = proofs_a.ys().unwrap();
    let ys_b = proofs_b.ys().unwrap();
    let ys_c = proofs_c.ys().unwrap();

    // Operation A: Setup only (dropped before signing)
    {
        let saga_a = SwapSaga::new(&mint, db.clone(), pubsub.clone());
        let _saga_a = saga_a
            .setup_swap(&proofs_a, &outputs_a, None, verification_a)
            .await
            .expect("Operation A setup should succeed");
        // Dropped without signing
    }

    // Operation B: Setup + Sign (dropped before finalize)
    {
        let saga_b = SwapSaga::new(&mint, db.clone(), pubsub.clone());
        let saga_b = saga_b
            .setup_swap(&proofs_b, &outputs_b, None, verification_b)
            .await
            .expect("Operation B setup should succeed");
        let _saga_b = saga_b
            .sign_outputs()
            .await
            .expect("Operation B signing should succeed");
        // Dropped without finalize
    }

    // Operation C: Complete successfully
    {
        let saga_c = SwapSaga::new(&mint, db.clone(), pubsub.clone());
        let saga_c = saga_c
            .setup_swap(&proofs_c, &outputs_c, None, verification_c)
            .await
            .expect("Operation C setup should succeed");
        let saga_c = saga_c
            .sign_outputs()
            .await
            .expect("Operation C signing should succeed");
        let _response = saga_c
            .finalize()
            .await
            .expect("Operation C finalize should succeed");
    }

    // Verify states before recovery
    let states_a_before = db.get_proofs_states(&ys_a).await.unwrap();
    let states_b_before = db.get_proofs_states(&ys_b).await.unwrap();
    let states_c_before = db.get_proofs_states(&ys_c).await.unwrap();

    assert!(states_a_before.iter().all(|s| s == &Some(State::Pending)));
    assert!(states_b_before.iter().all(|s| s == &Some(State::Pending)));
    assert!(states_c_before.iter().all(|s| s == &Some(State::Spent)));

    // Simulate mint restart - run recovery
    mint.stop().await.expect("Recovery should succeed");
    mint.start().await.expect("Recovery should succeed");

    // Verify states after recovery
    let states_a_after = db.get_proofs_states(&ys_a).await.unwrap();
    let states_b_after = db.get_proofs_states(&ys_b).await.unwrap();
    let states_c_after = db.get_proofs_states(&ys_c).await.unwrap();

    assert!(
        states_a_after.iter().all(|s| s.is_none()),
        "Operation A proofs should be removed (no signatures)"
    );
    assert!(
        states_b_after.iter().all(|s| s.is_none()),
        "Operation B proofs should be removed (no signatures in DB)"
    );
    assert!(
        states_c_after.iter().all(|s| s == &Some(State::Spent)),
        "Operation C proofs should remain SPENT (completed successfully)"
    );
}

/// Tests startup recovery with operation ID uniqueness and tracking.
///
/// # What This Tests
/// - Multiple concurrent swaps get unique operation_ids
/// - Proofs are correctly associated with their operation_ids
/// - Recovery can distinguish between different operations
/// - Each operation is tracked independently
///
/// # Flow
/// 1. Create multiple swaps concurrently
/// 2. Drop all sagas without finalize
/// 3. Verify proofs are associated with different operations
/// 4. Run recovery
/// 5. Verify all operations cleaned up correctly
///
/// # Success Criteria
/// - Each swap has unique operation_id
/// - Proofs correctly tracked per operation
/// - Recovery processes each operation independently
/// - All proofs removed after recovery
#[tokio::test]
async fn test_operation_id_uniqueness_and_tracking() {
    let mint = Arc::new(create_test_mint().await.unwrap());
    let amount = Amount::from(100);

    // Create three separate sets of proofs
    let (proofs_1, verification_1) = create_swap_inputs(&mint, amount).await;
    let (proofs_2, verification_2) = create_swap_inputs(&mint, amount).await;
    let (proofs_3, verification_3) = create_swap_inputs(&mint, amount).await;

    let (outputs_1, _) = create_test_blinded_messages(&mint, amount).await.unwrap();
    let (outputs_2, _) = create_test_blinded_messages(&mint, amount).await.unwrap();
    let (outputs_3, _) = create_test_blinded_messages(&mint, amount).await.unwrap();

    let db = mint.localstore();

    let ys_1 = proofs_1.ys().unwrap();
    let ys_2 = proofs_2.ys().unwrap();
    let ys_3 = proofs_3.ys().unwrap();

    // Create all three swaps and drop without finalize
    {
        let pubsub = mint.pubsub_manager();

        let saga_1 = SwapSaga::new(&mint, db.clone(), pubsub.clone());
        let _saga_1 = saga_1
            .setup_swap(&proofs_1, &outputs_1, None, verification_1)
            .await
            .expect("Swap 1 setup should succeed");

        let saga_2 = SwapSaga::new(&mint, db.clone(), pubsub.clone());
        let _saga_2 = saga_2
            .setup_swap(&proofs_2, &outputs_2, None, verification_2)
            .await
            .expect("Swap 2 setup should succeed");

        let saga_3 = SwapSaga::new(&mint, db.clone(), pubsub.clone());
        let _saga_3 = saga_3
            .setup_swap(&proofs_3, &outputs_3, None, verification_3)
            .await
            .expect("Swap 3 setup should succeed");

        // All sagas dropped without finalize
    }

    // Verify all proofs are PENDING
    let states_1 = db.get_proofs_states(&ys_1).await.unwrap();
    let states_2 = db.get_proofs_states(&ys_2).await.unwrap();
    let states_3 = db.get_proofs_states(&ys_3).await.unwrap();

    assert!(states_1.iter().all(|s| s == &Some(State::Pending)));
    assert!(states_2.iter().all(|s| s == &Some(State::Pending)));
    assert!(states_3.iter().all(|s| s == &Some(State::Pending)));

    // Simulate mint restart - run recovery
    mint.stop().await.expect("Recovery should succeed");
    mint.start().await.expect("Recovery should succeed");

    // Verify all proofs removed
    let states_1_after = db.get_proofs_states(&ys_1).await.unwrap();
    let states_2_after = db.get_proofs_states(&ys_2).await.unwrap();
    let states_3_after = db.get_proofs_states(&ys_3).await.unwrap();

    assert!(
        states_1_after.iter().all(|s| s.is_none()),
        "Swap 1 proofs should be removed"
    );
    assert!(
        states_2_after.iter().all(|s| s.is_none()),
        "Swap 2 proofs should be removed"
    );
    assert!(
        states_3_after.iter().all(|s| s.is_none()),
        "Swap 3 proofs should be removed"
    );

    // Verify each set of proofs can now be used in new swaps
    let (new_outputs_1, _) = create_test_blinded_messages(&mint, amount).await.unwrap();
    let verification = create_verification(amount);

    let pubsub = mint.pubsub_manager();
    let new_saga = SwapSaga::new(&mint, db, pubsub);

    let result = new_saga
        .setup_swap(&proofs_1, &new_outputs_1, None, verification)
        .await;

    assert!(
        result.is_ok(),
        "Should be able to reuse proofs after recovery"
    );
}

// ==================== PHASE 2: CRASH RECOVERY TESTS ====================
// These tests verify crash recovery using saga persistence.

/// Tests crash recovery without calling compensate_all().
///
/// # What This Tests
/// - Saga dropped WITHOUT calling compensate_all() (simulates process crash)
/// - Saga persists in database after crash
/// - Proofs remain PENDING after crash (not cleaned up)
/// - Recovery mechanism finds incomplete saga via get_incomplete_sagas()
/// - Recovery cleans up orphaned state (proofs, blinded messages, saga)
///
/// # This Is The PRIMARY USE CASE for Saga Persistence
/// The in-memory compensation mechanism only works if the process stays alive.
/// When the process crashes, we lose in-memory compensations and must rely
/// on persisted saga to recover.
///
/// # Success Criteria
/// - Saga exists after crash
/// - Proofs are PENDING after crash (compensation didn't run)
/// - Recovery removes proofs
/// - Recovery removes blinded messages
/// - Recovery deletes saga
#[tokio::test]
async fn test_crash_recovery_without_compensation() {
    let mint = create_test_mint().await.unwrap();
    let db = mint.localstore();

    let amount = Amount::from(100);
    let (input_proofs, verification) = create_swap_inputs(&mint, amount).await;
    let (output_blinded_messages, _) = create_test_blinded_messages(&mint, amount).await.unwrap();

    let operation_id;
    let ys = input_proofs.ys().unwrap();
    let _blinded_secrets: Vec<_> = output_blinded_messages
        .iter()
        .map(|bm| bm.blinded_secret)
        .collect();

    // Simulate crash: setup swap, then drop WITHOUT calling compensate_all()
    {
        let pubsub = mint.pubsub_manager();
        let saga = SwapSaga::new(&mint, db.clone(), pubsub);

        let saga = saga
            .setup_swap(&input_proofs, &output_blinded_messages, None, verification)
            .await
            .expect("Setup should succeed");

        operation_id = *saga.state_data.operation.id();

        // CRITICAL: Drop saga WITHOUT calling compensate_all()
        // This simulates a crash where in-memory compensations are lost
        drop(saga);
    }

    // Verify saga still exists in database (persisted during setup)
    let saga = {
        let mut tx = db.begin_transaction().await.unwrap();
        let result = tx
            .get_saga(&operation_id)
            .await
            .expect("Failed to get saga");
        tx.commit().await.unwrap();
        result
    };
    assert!(saga.is_some(), "Saga should persist after crash");

    // Verify proofs are still Pending (compensation didn't run)
    let states = db.get_proofs_states(&ys).await.unwrap();
    assert!(
        states.iter().all(|s| s == &Some(State::Pending)),
        "Proofs should still be Pending after crash (compensation didn't run)"
    );

    // Note: We cannot directly verify blinded messages exist (no query method)
    // but the recovery process will delete them along with proofs

    // Simulate mint restart - run recovery
    mint.stop().await.expect("Stop should succeed");
    mint.start().await.expect("Start should succeed");

    // Verify recovery cleaned up:
    // 1. Proofs removed from database
    let states_after = db.get_proofs_states(&ys).await.unwrap();
    assert!(
        states_after.iter().all(|s| s.is_none()),
        "Recovery should remove proofs"
    );

    // 2. Blinded messages removed (implicitly - no query method available)

    // 3. Saga deleted
    let saga_after = {
        let mut tx = db.begin_transaction().await.unwrap();
        let result = tx
            .get_saga(&operation_id)
            .await
            .expect("Failed to get saga");
        tx.commit().await.unwrap();
        result
    };
    assert!(saga_after.is_none(), "Recovery should delete saga");
}

/// Tests crash recovery after setup only (before signing).
///
/// # What This Tests
/// - Saga in SetupComplete state when crashed
/// - No signatures exist in database
/// - Recovery removes all swap state
///
/// # Success Criteria
/// - Saga exists before recovery
/// - Proofs are Pending before recovery
/// - Everything cleaned up after recovery
#[tokio::test]
async fn test_crash_recovery_after_setup_only() {
    let mint = create_test_mint().await.unwrap();
    let db = mint.localstore();

    let amount = Amount::from(100);
    let (input_proofs, verification) = create_swap_inputs(&mint, amount).await;
    let (output_blinded_messages, _) = create_test_blinded_messages(&mint, amount).await.unwrap();

    let operation_id;
    let ys = input_proofs.ys().unwrap();
    let _blinded_secrets: Vec<_> = output_blinded_messages
        .iter()
        .map(|bm| bm.blinded_secret)
        .collect();

    // Setup and crash
    {
        let pubsub = mint.pubsub_manager();
        let saga = SwapSaga::new(&mint, db.clone(), pubsub);

        let saga = saga
            .setup_swap(&input_proofs, &output_blinded_messages, None, verification)
            .await
            .expect("Setup should succeed");

        operation_id = *saga.state_data.operation.id();

        // Verify saga was persisted
        let saga = {
            let mut tx = db.begin_transaction().await.unwrap();
            let result = tx.get_saga(&operation_id).await.unwrap();
            tx.commit().await.unwrap();
            result
        };
        assert!(saga.is_some());

        // Drop without compensation (crash)
        drop(saga);
    }

    // Verify state before recovery
    let saga_before = {
        let mut tx = db.begin_transaction().await.unwrap();
        let result = tx.get_saga(&operation_id).await.unwrap();
        tx.commit().await.unwrap();
        result
    };
    assert!(saga_before.is_some());

    let states_before = db.get_proofs_states(&ys).await.unwrap();
    assert!(states_before.iter().all(|s| s == &Some(State::Pending)));

    // Run recovery
    mint.stop().await.expect("Stop should succeed");
    mint.start().await.expect("Start should succeed");

    // Verify cleanup
    let saga_after = {
        let mut tx = db.begin_transaction().await.unwrap();
        let result = tx.get_saga(&operation_id).await.unwrap();
        tx.commit().await.unwrap();
        result
    };
    assert!(saga_after.is_none(), "Saga should be deleted");

    let states_after = db.get_proofs_states(&ys).await.unwrap();
    assert!(
        states_after.iter().all(|s| s.is_none()),
        "Proofs should be removed"
    );

    // Blinded messages also removed by recovery (no query method to verify)
}

/// Tests crash recovery after signing (before finalize).
///
/// # What This Tests
/// - Saga crashed after sign_outputs() but before finalize()
/// - Signatures were in memory only (never persisted)
/// - Recovery treats this the same as crashed after setup
/// - All state is cleaned up
///
/// # Success Criteria
/// - Saga exists before recovery
/// - No signatures in database (never persisted)
/// - Everything cleaned up after recovery
#[tokio::test]
async fn test_crash_recovery_after_signing() {
    let mint = create_test_mint().await.unwrap();
    let db = mint.localstore();

    let amount = Amount::from(100);
    let (input_proofs, verification) = create_swap_inputs(&mint, amount).await;
    let (output_blinded_messages, _) = create_test_blinded_messages(&mint, amount).await.unwrap();

    let operation_id;
    let ys = input_proofs.ys().unwrap();
    let blinded_secrets: Vec<_> = output_blinded_messages
        .iter()
        .map(|bm| bm.blinded_secret)
        .collect();

    // Setup, sign, and crash
    {
        let pubsub = mint.pubsub_manager();
        let saga = SwapSaga::new(&mint, db.clone(), pubsub);

        let saga = saga
            .setup_swap(&input_proofs, &output_blinded_messages, None, verification)
            .await
            .expect("Setup should succeed");

        operation_id = *saga.state_data.operation.id();

        let saga = saga.sign_outputs().await.expect("Signing should succeed");

        // Verify we have signatures in memory
        assert_eq!(
            saga.state_data.signatures.len(),
            output_blinded_messages.len()
        );

        // Drop without finalize (crash) - signatures lost
        drop(saga);
    }

    // Verify state before recovery
    let saga_before = {
        let mut tx = db.begin_transaction().await.unwrap();
        let result = tx.get_saga(&operation_id).await.unwrap();
        tx.commit().await.unwrap();
        result
    };
    assert!(saga_before.is_some());

    // Verify no signatures in database (they were in memory only)
    let sigs_before = db.get_blind_signatures(&blinded_secrets).await.unwrap();
    assert!(
        sigs_before.iter().all(|s| s.is_none()),
        "Signatures should not be in DB (never persisted)"
    );

    // Run recovery
    mint.stop().await.expect("Stop should succeed");
    mint.start().await.expect("Start should succeed");

    // Verify cleanup
    let saga_after = {
        let mut tx = db.begin_transaction().await.unwrap();
        let result = tx.get_saga(&operation_id).await.unwrap();
        tx.commit().await.unwrap();
        result
    };
    assert!(saga_after.is_none(), "Saga should be deleted");

    let states_after = db.get_proofs_states(&ys).await.unwrap();
    assert!(
        states_after.iter().all(|s| s.is_none()),
        "Proofs should be removed"
    );

    // Blinded messages also removed by recovery (no query method to verify)
}

/// Tests recovery with multiple incomplete sagas in different states.
///
/// # What This Tests
/// - Multiple sagas can be incomplete simultaneously
/// - Recovery processes all incomplete sagas
/// - Each saga is handled correctly based on its state
///
/// # Test Scenario
/// - Saga A: Setup only (incomplete)
/// - Saga B: Setup + Sign (incomplete, signatures lost)
/// - Saga C: Completed (should NOT be affected by recovery)
///
/// # Success Criteria
/// - Saga A cleaned up
/// - Saga B cleaned up
/// - Saga C unaffected
#[tokio::test]
async fn test_recovery_multiple_incomplete_sagas() {
    let mint = create_test_mint().await.unwrap();
    let db = mint.localstore();

    let amount = Amount::from(100);

    // Create three sets of inputs/outputs
    let (proofs_a, verification_a) = create_swap_inputs(&mint, amount).await;
    let (proofs_b, verification_b) = create_swap_inputs(&mint, amount).await;
    let (proofs_c, verification_c) = create_swap_inputs(&mint, amount).await;

    let (outputs_a, _) = create_test_blinded_messages(&mint, amount).await.unwrap();
    let (outputs_b, _) = create_test_blinded_messages(&mint, amount).await.unwrap();
    let (outputs_c, _) = create_test_blinded_messages(&mint, amount).await.unwrap();

    let ys_a = proofs_a.ys().unwrap();
    let ys_b = proofs_b.ys().unwrap();
    let ys_c = proofs_c.ys().unwrap();

    let op_id_a;
    let op_id_b;
    let op_id_c;

    // Saga A: Setup only, then crash
    {
        let pubsub = mint.pubsub_manager();
        let saga = SwapSaga::new(&mint, db.clone(), pubsub);
        let saga = saga
            .setup_swap(&proofs_a, &outputs_a, None, verification_a)
            .await
            .expect("Setup A should succeed");
        op_id_a = *saga.state_data.operation.id();
        drop(saga);
    }

    // Saga B: Setup + Sign, then crash
    {
        let pubsub = mint.pubsub_manager();
        let saga = SwapSaga::new(&mint, db.clone(), pubsub);
        let saga = saga
            .setup_swap(&proofs_b, &outputs_b, None, verification_b)
            .await
            .expect("Setup B should succeed");
        op_id_b = *saga.state_data.operation.id();
        let saga = saga.sign_outputs().await.expect("Sign B should succeed");
        drop(saga);
    }

    // Saga C: Complete successfully
    {
        let pubsub = mint.pubsub_manager();
        let saga = SwapSaga::new(&mint, db.clone(), pubsub);
        let saga = saga
            .setup_swap(&proofs_c, &outputs_c, None, verification_c)
            .await
            .expect("Setup C should succeed");
        op_id_c = *saga.state_data.operation.id();
        let saga = saga.sign_outputs().await.expect("Sign C should succeed");
        let _response = saga.finalize().await.expect("Finalize C should succeed");
    }

    // Verify state before recovery
    use cdk_common::mint::OperationKind;
    let incomplete_before = db.get_incomplete_sagas(OperationKind::Swap).await.unwrap();
    assert_eq!(
        incomplete_before.len(),
        2,
        "Should have 2 incomplete sagas (A and B)"
    );

    let states_a_before = db.get_proofs_states(&ys_a).await.unwrap();
    let states_b_before = db.get_proofs_states(&ys_b).await.unwrap();
    let states_c_before = db.get_proofs_states(&ys_c).await.unwrap();

    assert!(states_a_before.iter().all(|s| s == &Some(State::Pending)));
    assert!(states_b_before.iter().all(|s| s == &Some(State::Pending)));
    assert!(states_c_before.iter().all(|s| s == &Some(State::Spent)));

    // Run recovery
    mint.stop().await.expect("Stop should succeed");
    mint.start().await.expect("Start should succeed");

    // Verify cleanup
    let incomplete_after = db.get_incomplete_sagas(OperationKind::Swap).await.unwrap();
    assert_eq!(
        incomplete_after.len(),
        0,
        "No incomplete sagas after recovery"
    );

    // Saga A cleaned up
    let saga_a = {
        let mut tx = db.begin_transaction().await.unwrap();
        let result = tx.get_saga(&op_id_a).await.unwrap();
        tx.commit().await.unwrap();
        result
    };
    assert!(saga_a.is_none());
    let states_a_after = db.get_proofs_states(&ys_a).await.unwrap();
    assert!(states_a_after.iter().all(|s| s.is_none()));

    // Saga B cleaned up
    let saga_b = {
        let mut tx = db.begin_transaction().await.unwrap();
        let result = tx.get_saga(&op_id_b).await.unwrap();
        tx.commit().await.unwrap();
        result
    };
    assert!(saga_b.is_none());
    let states_b_after = db.get_proofs_states(&ys_b).await.unwrap();
    assert!(states_b_after.iter().all(|s| s.is_none()));

    // Saga C unaffected (still spent, saga was already deleted)
    let saga_c = {
        let mut tx = db.begin_transaction().await.unwrap();
        let result = tx.get_saga(&op_id_c).await.unwrap();
        tx.commit().await.unwrap();
        result
    };
    assert!(saga_c.is_none(), "Completed saga was deleted");
    let states_c_after = db.get_proofs_states(&ys_c).await.unwrap();
    assert!(
        states_c_after.iter().all(|s| s == &Some(State::Spent)),
        "Completed saga proofs remain spent"
    );
}

/// Tests that recovery is idempotent (can be run multiple times safely).
///
/// # What This Tests
/// - Recovery can be run multiple times without errors
/// - Second recovery run is a no-op
/// - State remains consistent after multiple recoveries
///
/// # Success Criteria
/// - First recovery cleans up incomplete saga
/// - Second recovery succeeds (no incomplete sagas to process)
/// - State is consistent after both runs
#[tokio::test]
async fn test_recovery_idempotence() {
    let mint = create_test_mint().await.unwrap();
    let db = mint.localstore();

    let amount = Amount::from(100);
    let (input_proofs, verification) = create_swap_inputs(&mint, amount).await;
    let (output_blinded_messages, _) = create_test_blinded_messages(&mint, amount).await.unwrap();

    let operation_id;
    let ys = input_proofs.ys().unwrap();

    // Create incomplete saga
    {
        let pubsub = mint.pubsub_manager();
        let saga = SwapSaga::new(&mint, db.clone(), pubsub);
        let saga = saga
            .setup_swap(&input_proofs, &output_blinded_messages, None, verification)
            .await
            .expect("Setup should succeed");
        operation_id = *saga.state_data.operation.id();
        drop(saga);
    }

    // Verify incomplete saga exists
    let saga_before = {
        let mut tx = db.begin_transaction().await.unwrap();
        let result = tx.get_saga(&operation_id).await.unwrap();
        tx.commit().await.unwrap();
        result
    };
    assert!(saga_before.is_some());

    // First recovery
    mint.stop().await.expect("First stop should succeed");
    mint.start().await.expect("First start should succeed");

    // Verify cleanup
    let saga_after_1 = {
        let mut tx = db.begin_transaction().await.unwrap();
        let result = tx.get_saga(&operation_id).await.unwrap();
        tx.commit().await.unwrap();
        result
    };
    assert!(saga_after_1.is_none());
    let states_after_1 = db.get_proofs_states(&ys).await.unwrap();
    assert!(states_after_1.iter().all(|s| s.is_none()));

    // Second recovery (should be idempotent - no work to do)
    mint.stop().await.expect("Second stop should succeed");
    mint.start().await.expect("Second start should succeed");

    // Verify state unchanged
    let saga_after_2 = {
        let mut tx = db.begin_transaction().await.unwrap();
        let result = tx.get_saga(&operation_id).await.unwrap();
        tx.commit().await.unwrap();
        result
    };
    assert!(saga_after_2.is_none());
    let states_after_2 = db.get_proofs_states(&ys).await.unwrap();
    assert!(states_after_2.iter().all(|s| s.is_none()));

    // Third recovery for good measure
    mint.stop().await.expect("Third stop should succeed");
    mint.start().await.expect("Third start should succeed");

    let saga_after_3 = {
        let mut tx = db.begin_transaction().await.unwrap();
        let result = tx.get_saga(&operation_id).await.unwrap();
        tx.commit().await.unwrap();
        result
    };
    assert!(saga_after_3.is_none());
}

// ==================== PHASE 3: EDGE CASE TESTS ====================
// These tests verify edge cases and error handling scenarios.

/// Tests cleanup of orphaned saga (saga deletion fails but swap succeeds).
///
/// # What This Tests
/// - Swap completes successfully (proofs marked SPENT)
/// - Saga deletion fails (simulated by test hook)
/// - Swap still succeeds (best-effort deletion)
/// - Saga remains orphaned in database
/// - Recovery detects orphaned saga (proofs already SPENT)
/// - Recovery deletes orphaned saga
///
/// # Why This Matters
/// According to the implementation, saga deletion is best-effort. If it fails,
/// the swap should still succeed. The orphaned saga will be cleaned up
/// on next recovery.
///
/// # Success Criteria
/// - Swap succeeds despite deletion failure
/// - Proofs are SPENT after swap
/// - Saga remains after swap (orphaned)
/// - Recovery cleans up orphaned saga
#[tokio::test]
async fn test_orphaned_saga_cleanup() {
    let mint = create_test_mint().await.unwrap();
    let db = mint.localstore();

    let amount = Amount::from(100);
    let (input_proofs, verification) = create_swap_inputs(&mint, amount).await;
    let (output_blinded_messages, _) = create_test_blinded_messages(&mint, amount).await.unwrap();

    let pubsub = mint.pubsub_manager();
    let saga = SwapSaga::new(&mint, db.clone(), pubsub);

    let saga = saga
        .setup_swap(&input_proofs, &output_blinded_messages, None, verification)
        .await
        .expect("Setup should succeed");

    let operation_id = *saga.state_data.operation.id();
    let ys = input_proofs.ys().unwrap();

    let saga = saga.sign_outputs().await.expect("Signing should succeed");

    // Note: We cannot easily inject a failure for saga deletion within finalize
    // because the deletion happens inside a database transaction and uses the
    // transaction trait. For now, we'll test the recovery side: create a saga
    // that completes, then manually verify recovery can handle scenarios where
    // saga exists but proofs are already SPENT.

    let _response = saga.finalize().await.expect("Finalize should succeed");

    // Verify swap succeeded (proofs SPENT)
    let states = db.get_proofs_states(&ys).await.unwrap();
    assert!(
        states.iter().all(|s| s == &Some(State::Spent)),
        "Proofs should be SPENT after successful swap"
    );

    // In a real scenario with deletion failure, saga would remain.
    // For this test, we'll verify that saga is properly deleted.
    // TODO: Add failure injection for delete_saga to properly test this.
    let saga = {
        let mut tx = db.begin_transaction().await.unwrap();
        let result = tx.get_saga(&operation_id).await.unwrap();
        tx.commit().await.unwrap();
        result
    };
    assert!(
        saga.is_none(),
        "Saga should be deleted after successful swap"
    );

    // If we had a way to inject deletion failure, we would:
    // 1. Verify saga remains (orphaned)
    // 2. Run recovery
    // 3. Verify recovery detects proofs are SPENT
    // 4. Verify recovery deletes orphaned saga
}

/// Tests recovery with orphaned proofs (proofs without corresponding saga).
///
/// # What This Tests
/// - Proofs exist in database without saga
/// - Recovery handles this gracefully (no crash)
/// - Proofs remain in their current state
///
/// # Scenario
/// This could happen if:
/// - Manual database intervention removed saga but not proofs
/// - A bug caused saga deletion without proof cleanup
/// - Database corruption
///
/// # Success Criteria
/// - Recovery runs without errors
/// - Proofs remain in database (recovery doesn't remove them without saga)
/// - No crashes or panics
#[tokio::test]
async fn test_recovery_with_orphaned_proofs() {
    let mint = create_test_mint().await.unwrap();
    let db = mint.localstore();

    let amount = Amount::from(100);
    let (input_proofs, verification) = create_swap_inputs(&mint, amount).await;
    let (output_blinded_messages, _) = create_test_blinded_messages(&mint, amount).await.unwrap();

    let ys = input_proofs.ys().unwrap();

    // Setup saga to get proofs into PENDING state
    let operation_id = {
        let pubsub = mint.pubsub_manager();
        let saga = SwapSaga::new(&mint, db.clone(), pubsub);

        let saga = saga
            .setup_swap(&input_proofs, &output_blinded_messages, None, verification)
            .await
            .expect("Setup should succeed");

        let op_id = *saga.state_data.operation.id();

        // Drop saga (crash simulation)
        drop(saga);

        op_id
    };

    // Verify proofs are PENDING and saga exists
    let states_before = db.get_proofs_states(&ys).await.unwrap();
    assert!(states_before.iter().all(|s| s == &Some(State::Pending)));

    let saga_before = {
        let mut tx = db.begin_transaction().await.unwrap();
        let result = tx.get_saga(&operation_id).await.unwrap();
        tx.commit().await.unwrap();
        result
    };
    assert!(saga_before.is_some());

    // Manually delete saga (simulating orphaned proofs scenario)
    {
        let mut tx = db.begin_transaction().await.unwrap();
        tx.delete_saga(&operation_id).await.unwrap();
        tx.commit().await.unwrap();
    }

    // Verify saga is gone but proofs remain
    let saga_after_delete = {
        let mut tx = db.begin_transaction().await.unwrap();
        let result = tx.get_saga(&operation_id).await.unwrap();
        tx.commit().await.unwrap();
        result
    };
    assert!(saga_after_delete.is_none(), "Saga should be deleted");

    let states_after_delete = db.get_proofs_states(&ys).await.unwrap();
    assert!(
        states_after_delete
            .iter()
            .all(|s| s == &Some(State::Pending)),
        "Proofs should still be PENDING (orphaned)"
    );

    // Run recovery - should handle gracefully
    mint.stop().await.expect("Stop should succeed");
    mint.start().await.expect("Start should succeed");

    // Verify recovery completed without errors
    // Orphaned PENDING proofs without saga should remain (not cleaned up)
    // This is by design - recovery only acts on incomplete sagas, not orphaned proofs
    let states_after_recovery = db.get_proofs_states(&ys).await.unwrap();
    assert!(
        states_after_recovery
            .iter()
            .all(|s| s == &Some(State::Pending)),
        "Orphaned proofs remain PENDING (recovery doesn't clean up proofs without saga)"
    );

    // Note: In production, a separate cleanup mechanism (e.g., timeout-based)
    // would be needed to handle such orphaned resources. Saga recovery only
    // processes incomplete sagas that have saga.
}

/// Tests recovery with partial state (missing blinded messages).
///
/// # What This Tests
/// - Saga exists
/// - Proofs exist
/// - Blinded messages are missing (deleted manually)
/// - Recovery handles this gracefully
///
/// # Scenario
/// This could occur due to:
/// - Partial transaction commit (unlikely with proper atomicity)
/// - Manual database intervention
/// - Database corruption
///
/// # Success Criteria
/// - Recovery runs without errors
/// - Saga is cleaned up
/// - Proofs are removed
/// - No crashes due to missing blinded messages
#[tokio::test]
async fn test_recovery_with_partial_state() {
    let mint = create_test_mint().await.unwrap();
    let db = mint.localstore();

    let amount = Amount::from(100);
    let (input_proofs, verification) = create_swap_inputs(&mint, amount).await;
    let (output_blinded_messages, _) = create_test_blinded_messages(&mint, amount).await.unwrap();

    let ys = input_proofs.ys().unwrap();
    let blinded_secrets: Vec<_> = output_blinded_messages
        .iter()
        .map(|bm| bm.blinded_secret)
        .collect();

    // Setup saga
    let operation_id = {
        let pubsub = mint.pubsub_manager();
        let saga = SwapSaga::new(&mint, db.clone(), pubsub);

        let saga = saga
            .setup_swap(&input_proofs, &output_blinded_messages, None, verification)
            .await
            .expect("Setup should succeed");

        let op_id = *saga.state_data.operation.id();

        // Drop saga (crash simulation)
        drop(saga);

        op_id
    };

    // Verify setup
    let saga_before = {
        let mut tx = db.begin_transaction().await.unwrap();
        let result = tx.get_saga(&operation_id).await.unwrap();
        tx.commit().await.unwrap();
        result
    };
    assert!(saga_before.is_some());

    let states_before = db.get_proofs_states(&ys).await.unwrap();
    assert!(states_before.iter().all(|s| s == &Some(State::Pending)));

    // Manually delete blinded messages (simulating partial state)
    {
        let mut tx = db.begin_transaction().await.unwrap();
        tx.delete_blinded_messages(&blinded_secrets).await.unwrap();
        tx.commit().await.unwrap();
    }

    // Verify blinded messages are gone but saga and proofs remain
    // (Note: We can't directly query blinded messages to verify they're gone,
    // but the recovery mechanism will attempt to delete them regardless)

    // Run recovery - should handle missing blinded messages gracefully
    mint.stop().await.expect("Stop should succeed");
    mint.start().await.expect("Start should succeed");

    // Verify recovery completed successfully
    let saga_after = {
        let mut tx = db.begin_transaction().await.unwrap();
        let result = tx.get_saga(&operation_id).await.unwrap();
        tx.commit().await.unwrap();
        result
    };
    assert!(saga_after.is_none(), "Saga should be deleted");

    let states_after = db.get_proofs_states(&ys).await.unwrap();
    assert!(
        states_after.iter().all(|s| s.is_none()),
        "Proofs should be removed"
    );

    // Recovery should succeed even if blinded messages were already gone
}

/// Tests recovery when blinded messages are missing (but proofs and saga exist).
///
/// # What This Tests
/// - Saga exists with blinded_secrets
/// - Proofs exist and are PENDING
/// - Blinded messages themselves are missing from database
/// - Recovery completes without errors
/// - Saga is cleaned up
/// - Proofs are removed
///
/// # Success Criteria
/// - No errors when trying to delete missing blinded messages
/// - Recovery completes successfully
/// - All saga cleaned up
#[tokio::test]
async fn test_recovery_with_missing_blinded_messages() {
    let mint = create_test_mint().await.unwrap();
    let db = mint.localstore();

    let amount = Amount::from(100);
    let (input_proofs, verification) = create_swap_inputs(&mint, amount).await;
    let (output_blinded_messages, _) = create_test_blinded_messages(&mint, amount).await.unwrap();

    let ys = input_proofs.ys().unwrap();
    let blinded_secrets: Vec<_> = output_blinded_messages
        .iter()
        .map(|bm| bm.blinded_secret)
        .collect();

    // Setup saga and crash
    let operation_id = {
        let pubsub = mint.pubsub_manager();
        let saga = SwapSaga::new(&mint, db.clone(), pubsub);

        let saga = saga
            .setup_swap(&input_proofs, &output_blinded_messages, None, verification)
            .await
            .expect("Setup should succeed");

        let op_id = *saga.state_data.operation.id();
        drop(saga); // Crash

        op_id
    };

    // Verify initial state
    let saga = {
        let mut tx = db.begin_transaction().await.unwrap();
        let result = tx.get_saga(&operation_id).await.unwrap();
        tx.commit().await.unwrap();
        result
    };
    assert!(saga.is_some(), "Saga should exist");

    // Manually delete blinded messages before recovery
    {
        let mut tx = db.begin_transaction().await.unwrap();
        tx.delete_blinded_messages(&blinded_secrets).await.unwrap();
        tx.commit().await.unwrap();
    }

    // Run recovery - should handle missing blinded messages gracefully
    mint.stop().await.expect("Stop should succeed");
    mint.start()
        .await
        .expect("Start should succeed despite missing blinded messages");

    // Verify cleanup
    let saga_after = {
        let mut tx = db.begin_transaction().await.unwrap();
        let result = tx.get_saga(&operation_id).await.unwrap();
        tx.commit().await.unwrap();
        result
    };
    assert!(saga_after.is_none(), "Saga should be cleaned up");

    let states_after = db.get_proofs_states(&ys).await.unwrap();
    assert!(
        states_after.iter().all(|s| s.is_none()),
        "Proofs should be removed"
    );
}

/// Tests that saga deletion failure is handled gracefully during finalize.
///
/// # What This Tests
/// - Swap completes successfully through finalize
/// - Even if saga deletion fails internally, swap succeeds
/// - Best-effort saga deletion doesn't fail the swap
///
/// # Note
/// This test verifies the design decision that saga deletion is best-effort.
/// Currently we cannot easily inject deletion failures, so this test documents
/// the expected behavior and verifies normal deletion.
///
/// # Success Criteria
/// - Swap completes successfully
/// - Saga is deleted (in normal case)
/// - If deletion fails (not testable yet), swap still succeeds
#[tokio::test]
async fn test_saga_deletion_failure_handling() {
    let mint = create_test_mint().await.unwrap();
    let db = mint.localstore();

    let amount = Amount::from(100);
    let (input_proofs, verification) = create_swap_inputs(&mint, amount).await;
    let (output_blinded_messages, _) = create_test_blinded_messages(&mint, amount).await.unwrap();

    let pubsub = mint.pubsub_manager();
    let saga = SwapSaga::new(&mint, db.clone(), pubsub);

    let saga = saga
        .setup_swap(&input_proofs, &output_blinded_messages, None, verification)
        .await
        .expect("Setup should succeed");

    let operation_id = *saga.state_data.operation.id();
    let ys = input_proofs.ys().unwrap();

    let saga = saga.sign_outputs().await.expect("Signing should succeed");

    // In normal operation, deletion succeeds
    let response = saga.finalize().await.expect("Finalize should succeed");

    // Verify swap succeeded
    assert_eq!(
        response.signatures.len(),
        output_blinded_messages.len(),
        "Should have signatures for all outputs"
    );

    let states = db.get_proofs_states(&ys).await.unwrap();
    assert!(
        states.iter().all(|s| s == &Some(State::Spent)),
        "Proofs should be SPENT"
    );

    // Verify saga is deleted
    let saga = {
        let mut tx = db.begin_transaction().await.unwrap();
        let result = tx.get_saga(&operation_id).await.unwrap();
        tx.commit().await.unwrap();
        result
    };
    assert!(saga.is_none(), "Saga should be deleted");

    // TODO: Add test failure injection for delete_saga to verify that:
    // 1. Swap still succeeds even if deletion fails
    // 2. Orphaned saga remains
    // 3. Recovery can clean it up later
    //
    // This would require adding a TEST_FAIL_DELETE_SAGA env var check in the
    // database implementation's delete_saga method.
}