cdk 0.16.0-rc.2

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
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
//! Tests for melt saga pattern implementation
//!
//! This test module covers:
//! - Basic state transitions
//! - Crash recovery scenarios
//! - Saga persistence and deletion
//! - Compensation execution
//! - Concurrent operations
//! - Failure handling

use std::str::FromStr;

use cdk_common::mint::{MeltSagaState, OperationKind, Saga};
use cdk_common::nut00::KnownMethod;
use cdk_common::nuts::MeltQuoteState;
use cdk_common::{Amount, PaymentMethod, ProofsMethods, State};

use crate::mint::melt::melt_saga::MeltSaga;
use crate::test_helpers::mint::{create_test_mint, mint_test_proofs};

// ============================================================================
// Basic State Transition Tests
// ============================================================================

/// Test: Saga can be created in Initial state
#[tokio::test]
async fn test_melt_saga_initial_state_creation() {
    let mint = create_test_mint().await.unwrap();
    let db = mint.localstore();
    let pubsub = mint.pubsub_manager();

    let _saga = MeltSaga::new(std::sync::Arc::new(mint.clone()), db, pubsub);
    // Type system enforces Initial state - if this compiles, test passes
}

// ============================================================================
// Saga Persistence Tests
// ============================================================================

/// Test: Saga state is persisted atomically with setup transaction
#[tokio::test]
async fn test_saga_state_persistence_after_setup() {
    // STEP 1: Setup test environment
    let mint = create_test_mint().await.unwrap();
    let proofs = mint_test_proofs(&mint, Amount::from(10_000)).await.unwrap();
    let quote = create_test_melt_quote(&mint, Amount::from(9_000)).await;
    let melt_request = create_test_melt_request(&proofs, &quote);

    // STEP 2: Setup melt saga
    let verification = mint.verify_inputs(melt_request.inputs()).await.unwrap();
    let saga = MeltSaga::new(
        std::sync::Arc::new(mint.clone()),
        mint.localstore(),
        mint.pubsub_manager(),
    );
    let setup_saga = saga
        .setup_melt(
            &melt_request,
            verification,
            PaymentMethod::Known(KnownMethod::Bolt11),
        )
        .await
        .unwrap();

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

    // STEP 3: Query database for saga
    let sagas = mint
        .localstore
        .get_incomplete_sagas(OperationKind::Melt)
        .await
        .unwrap();

    // STEP 4: Find our saga
    let persisted_saga = sagas
        .iter()
        .find(|s| s.operation_id == operation_id)
        .expect("Saga should be persisted");

    // STEP 5: Validate saga content
    assert_eq!(
        persisted_saga.operation_id, operation_id,
        "Operation ID should match"
    );
    assert_eq!(
        persisted_saga.operation_kind,
        OperationKind::Melt,
        "Operation kind should be Melt"
    );

    // Verify state is SetupComplete
    match &persisted_saga.state {
        cdk_common::mint::SagaStateEnum::Melt(state) => {
            assert_eq!(
                *state,
                MeltSagaState::SetupComplete,
                "State should be SetupComplete"
            );
        }
        _ => panic!("Expected Melt saga state"),
    }

    // STEP 6: Verify input_ys can be looked up by operation_id
    let input_ys = proofs.ys().unwrap();
    let stored_input_ys = mint
        .localstore
        .get_proof_ys_by_operation_id(&persisted_saga.operation_id)
        .await
        .unwrap();
    assert_eq!(
        stored_input_ys.len(),
        input_ys.len(),
        "Should store all input Ys"
    );
    for y in &input_ys {
        assert!(
            stored_input_ys.contains(y),
            "Input Y should be stored: {:?}",
            y
        );
    }

    // STEP 7: Verify timestamps are set
    assert!(
        persisted_saga.created_at > 0,
        "Created timestamp should be set"
    );
    assert!(
        persisted_saga.updated_at > 0,
        "Updated timestamp should be set"
    );
    assert_eq!(
        persisted_saga.created_at, persisted_saga.updated_at,
        "Timestamps should match for new saga"
    );

    // STEP 8: Verify blinded_secrets lookup returns empty (not used for melt without change)
    let stored_blinded_secrets = mint
        .localstore
        .get_blinded_secrets_by_operation_id(&persisted_saga.operation_id)
        .await
        .unwrap();
    assert!(
        stored_blinded_secrets.is_empty(),
        "Melt saga without change should have no blinded_secrets"
    );

    // SUCCESS: Saga persisted correctly!
}

/// Test: Saga is deleted after successful finalization
#[tokio::test]
async fn test_saga_deletion_on_success() {
    // STEP 1: Setup test environment (FakeWallet handles payments automatically)
    let mint = create_test_mint().await.unwrap();

    // STEP 2: Create proofs and quote
    let proofs = mint_test_proofs(&mint, Amount::from(10_000)).await.unwrap();
    let quote = create_test_melt_quote(&mint, Amount::from(9_000)).await;
    let melt_request = create_test_melt_request(&proofs, &quote);

    // STEP 3: Complete full melt flow
    let verification = mint.verify_inputs(melt_request.inputs()).await.unwrap();
    let saga = MeltSaga::new(
        std::sync::Arc::new(mint.clone()),
        mint.localstore(),
        mint.pubsub_manager(),
    );

    // Setup
    let setup_saga = saga
        .setup_melt(
            &melt_request,
            verification,
            PaymentMethod::Known(KnownMethod::Bolt11),
        )
        .await
        .unwrap();
    let operation_id = *setup_saga.state_data.operation.id();

    // Verify saga exists
    assert_saga_exists(&mint, &operation_id).await;

    // Attempt internal settlement (will fail, go to external payment)
    let (payment_saga, decision) = setup_saga
        .attempt_internal_settlement(&melt_request)
        .await
        .unwrap();

    // Make payment (FakeWallet will return success based on FakeInvoiceDescription)
    let confirmed_saga = payment_saga.make_payment(decision).await.unwrap();

    // Finalize
    let _response = confirmed_saga.finalize().await.unwrap();

    // STEP 4: Verify saga was deleted
    assert_saga_not_exists(&mint, &operation_id).await;

    // STEP 5: Verify no incomplete sagas remain
    let sagas = mint
        .localstore
        .get_incomplete_sagas(OperationKind::Melt)
        .await
        .unwrap();
    assert!(sagas.is_empty(), "Should have no incomplete melt sagas");

    // SUCCESS: Saga cleaned up on success!
}

/// Test: Saga remains in database if finalize fails
#[tokio::test]
async fn test_saga_persists_on_finalize_failure() {
    // TODO: Implement this test
    // 1. Setup melt saga successfully
    // 2. Simulate finalize failure (e.g., database error)
    // 3. Verify saga still exists in database
    // 4. Verify state is still SetupComplete
}

// ============================================================================
// Crash Recovery Tests - SetupComplete State
// ============================================================================

/// Test: Recovery from crash after setup but before payment
///
/// This is the primary crash recovery scenario. If the mint crashes after
/// setup_melt() completes but before payment is sent, the proofs should be
/// restored on restart.
#[tokio::test]
async fn test_crash_recovery_setup_complete() {
    // STEP 1: Setup test environment
    let mint = create_test_mint().await.unwrap();

    // STEP 2: Create test proofs (10,000 millisats = 10 sats)
    let proofs = mint_test_proofs(&mint, Amount::from(10_000)).await.unwrap();
    let input_ys = proofs.ys().unwrap();

    // STEP 3: Create melt quote (9,000 millisats = 9 sats)
    let quote = create_test_melt_quote(&mint, Amount::from(9_000)).await;

    // STEP 4: Create melt request
    let melt_request = create_test_melt_request(&proofs, &quote);

    // STEP 5: Setup melt saga (this persists saga to DB)
    let verification = mint.verify_inputs(melt_request.inputs()).await.unwrap();
    let saga = MeltSaga::new(
        std::sync::Arc::new(mint.clone()),
        mint.localstore(),
        mint.pubsub_manager(),
    );
    let setup_saga = saga
        .setup_melt(
            &melt_request,
            verification,
            PaymentMethod::Known(KnownMethod::Bolt11),
        )
        .await
        .expect("Setup should succeed");

    // STEP 6: Verify proofs are PENDING
    assert_proofs_state(&mint, &input_ys, Some(State::Pending)).await;

    // STEP 7: Verify saga was persisted
    let operation_id = *setup_saga.state_data.operation.id();
    assert_saga_exists(&mint, &operation_id).await;

    // STEP 8: Simulate crash - drop saga without finalizing
    drop(setup_saga);

    // STEP 9: Run recovery (simulating mint restart)
    mint.recover_from_incomplete_melt_sagas()
        .await
        .expect("Recovery should succeed");

    // STEP 10: Verify proofs were REMOVED (restored to client)
    assert_proofs_state(&mint, &input_ys, None).await;

    // STEP 11: Verify saga was deleted
    assert_saga_not_exists(&mint, &operation_id).await;

    // STEP 12: Verify quote state reset to UNPAID
    let recovered_quote = mint
        .localstore
        .get_melt_quote(&quote.id)
        .await
        .unwrap()
        .expect("Quote should still exist");
    assert_eq!(
        recovered_quote.state,
        MeltQuoteState::Unpaid,
        "Quote state should be reset to Unpaid after recovery"
    );

    // SUCCESS: Crash recovery works!
}

/// Test: Multiple incomplete sagas can be recovered
///
/// This test validates that the recovery mechanism can handle multiple
/// incomplete sagas in a single recovery pass, ensuring batch operations work.
#[tokio::test]
async fn test_crash_recovery_multiple_sagas() {
    // STEP 1: Setup test environment
    let mint = create_test_mint().await.unwrap();

    // STEP 2: Create multiple incomplete melt sagas (5 sagas)
    let mut operation_ids = Vec::new();
    let mut proof_ys_list = Vec::new();
    let mut quote_ids = Vec::new();

    for i in 0..5 {
        // Use smaller amounts to fit within FakeWallet limits
        let proofs = mint_test_proofs(&mint, Amount::from(5_000 + i * 100))
            .await
            .unwrap();
        let input_ys = proofs.ys().unwrap();
        let quote = create_test_melt_quote(&mint, Amount::from(4_000 + i * 100)).await;
        let melt_request = create_test_melt_request(&proofs, &quote);

        let verification = mint.verify_inputs(melt_request.inputs()).await.unwrap();
        let saga = MeltSaga::new(
            std::sync::Arc::new(mint.clone()),
            mint.localstore(),
            mint.pubsub_manager(),
        );
        let setup_saga = saga
            .setup_melt(
                &melt_request,
                verification,
                PaymentMethod::Known(KnownMethod::Bolt11),
            )
            .await
            .unwrap();

        operation_ids.push(*setup_saga.state_data.operation.id());
        proof_ys_list.push(input_ys);
        quote_ids.push(quote.id.clone());

        // Drop saga to simulate crash
        drop(setup_saga);
    }

    // STEP 3: Verify all sagas exist before recovery
    let sagas_before = mint
        .localstore
        .get_incomplete_sagas(OperationKind::Melt)
        .await
        .unwrap();

    assert_eq!(
        sagas_before.len(),
        5,
        "Should have 5 incomplete sagas before recovery"
    );

    // Verify all our operation IDs are present
    for operation_id in &operation_ids {
        assert!(
            sagas_before.iter().any(|s| s.operation_id == *operation_id),
            "Saga {} should exist before recovery",
            operation_id
        );
    }

    // Verify all proofs are PENDING
    for input_ys in &proof_ys_list {
        assert_proofs_state(&mint, input_ys, Some(State::Pending)).await;
    }

    // STEP 4: Run recovery (should handle all sagas)
    mint.recover_from_incomplete_melt_sagas()
        .await
        .expect("Recovery should succeed");

    // STEP 5: Verify all sagas were recovered and cleaned up
    let sagas_after = mint
        .localstore
        .get_incomplete_sagas(OperationKind::Melt)
        .await
        .unwrap();

    assert!(
        sagas_after.is_empty(),
        "All sagas should be deleted after recovery"
    );

    // Verify none of our operation IDs exist
    for operation_id in &operation_ids {
        assert_saga_not_exists(&mint, operation_id).await;
    }

    // STEP 6: Verify all proofs were removed (returned to client)
    for input_ys in &proof_ys_list {
        assert_proofs_state(&mint, input_ys, None).await;
    }

    // STEP 7: Verify all quotes were reset to UNPAID
    for quote_id in &quote_ids {
        let recovered_quote = mint
            .localstore
            .get_melt_quote(quote_id)
            .await
            .unwrap()
            .expect("Quote should still exist");

        assert_eq!(
            recovered_quote.state,
            MeltQuoteState::Unpaid,
            "Quote {} should be reset to Unpaid",
            quote_id
        );
    }

    // SUCCESS: Multiple sagas recovered successfully!
}

/// Test: Recovery handles sagas gracefully even when data relationships exist
///
/// This test verifies that recovery works correctly in a standard crash scenario
/// where all data is intact (saga, quote, proofs all exist).
#[tokio::test]
async fn test_crash_recovery_orphaned_saga() {
    // STEP 1: Setup test environment
    let mint = create_test_mint().await.unwrap();
    let proofs = mint_test_proofs(&mint, Amount::from(10_000)).await.unwrap();
    let quote = create_test_melt_quote(&mint, Amount::from(9_000)).await;
    let melt_request = create_test_melt_request(&proofs, &quote);

    // STEP 2: Create incomplete saga
    let verification = mint.verify_inputs(melt_request.inputs()).await.unwrap();
    let saga = MeltSaga::new(
        std::sync::Arc::new(mint.clone()),
        mint.localstore(),
        mint.pubsub_manager(),
    );
    let setup_saga = saga
        .setup_melt(
            &melt_request,
            verification,
            PaymentMethod::Known(KnownMethod::Bolt11),
        )
        .await
        .unwrap();

    let operation_id = *setup_saga.state_data.operation.id();
    let input_ys = proofs.ys().unwrap();

    // Drop saga (simulate crash)
    drop(setup_saga);

    // Verify saga exists
    assert_saga_exists(&mint, &operation_id).await;
    assert_proofs_state(&mint, &input_ys, Some(State::Pending)).await;

    // STEP 3: Run recovery
    // Recovery should handle the saga gracefully, cleaning up all state
    mint.recover_from_incomplete_melt_sagas()
        .await
        .expect("Recovery should succeed");

    // STEP 4: Verify saga was cleaned up
    assert_saga_not_exists(&mint, &operation_id).await;
    assert_proofs_state(&mint, &input_ys, None).await;

    // Verify quote was reset
    let recovered_quote = mint
        .localstore
        .get_melt_quote(&quote.id)
        .await
        .unwrap()
        .unwrap();
    assert_eq!(recovered_quote.state, MeltQuoteState::Unpaid);

    // SUCCESS: Recovery works correctly!
}

/// Test: Recovery continues even if one saga fails
#[tokio::test]
async fn test_crash_recovery_partial_failure() {
    // TODO: Implement this test
    // 1. Create multiple incomplete sagas
    // 2. Make one saga fail (e.g., corrupted data)
    // 3. Run recovery
    // 4. Verify other sagas were still recovered
    // 5. Verify failed saga is logged but doesn't stop recovery
}

/// Test: Crash recovery after internal settlement commits but before finalize
///
/// This test verifies that if the mint crashes after internal settlement
/// (melt-to-mint on same mint) commits but before finalize() completes,
/// recovery will correctly finalize the melt rather than compensating.
///
/// This prevents fund loss where:
/// - The mint quote was credited (mint received funds)
/// - But proofs are returned to user (double-spend)
#[tokio::test]
async fn test_crash_recovery_internal_settlement() {
    use cdk_common::nuts::MintQuoteState;
    use cdk_common::MintQuoteBolt11Request;

    // STEP 1: Setup test environment
    let mint = create_test_mint().await.unwrap();
    let proofs = mint_test_proofs(&mint, Amount::from(10_000)).await.unwrap();
    let input_ys = proofs.ys().unwrap();

    // STEP 2: Create a mint quote that will be paid internally
    // This creates a payment request (invoice) on this mint
    // Note: We use a smaller amount (4000) because the test mint has 100% fee reserve,
    // so required = amount + fee_reserve = 4000 + 4000 = 8000 < 10000 inputs
    let mint_quote_response: cdk_common::MintQuoteBolt11Response<_> = mint
        .get_mint_quote(
            MintQuoteBolt11Request {
                amount: Amount::from(4_000),
                unit: cdk_common::CurrencyUnit::Sat,
                description: None,
                pubkey: None,
            }
            .into(),
        )
        .await
        .unwrap()
        .into();

    // Get the mint quote from database
    let mint_quote_id = cdk_common::QuoteId::from_str(&mint_quote_response.quote).unwrap();
    let mint_quote = mint
        .localstore
        .get_mint_quote(&mint_quote_id)
        .await
        .unwrap()
        .expect("Mint quote should exist");

    // STEP 3: Create a melt quote that uses the mint quote's payment request
    // This will trigger internal settlement since it's the same mint
    use cdk_common::melt::MeltQuoteRequest;
    use cdk_common::nuts::MeltQuoteBolt11Request;

    let melt_bolt11_request = MeltQuoteBolt11Request {
        request: mint_quote.request.to_string().parse().unwrap(),
        unit: cdk_common::CurrencyUnit::Sat,
        options: None,
    };
    let melt_quote_request = MeltQuoteRequest::Bolt11(melt_bolt11_request);

    let melt_quote_response = mint.get_melt_quote(melt_quote_request).await.unwrap();
    let melt_quote = mint
        .localstore
        .get_melt_quote(&melt_quote_response.quote)
        .await
        .unwrap()
        .expect("Melt quote should exist");

    // STEP 4: Create melt request and setup saga
    let melt_request = create_test_melt_request(&proofs, &melt_quote);
    let verification = mint.verify_inputs(melt_request.inputs()).await.unwrap();

    let saga = MeltSaga::new(
        std::sync::Arc::new(mint.clone()),
        mint.localstore(),
        mint.pubsub_manager(),
    );

    let setup_saga = saga
        .setup_melt(
            &melt_request,
            verification,
            PaymentMethod::Known(KnownMethod::Bolt11),
        )
        .await
        .unwrap();
    let operation_id = *setup_saga.state_data.operation.id();

    // STEP 5: Attempt internal settlement - this will commit and update saga state
    let (payment_saga, decision) = setup_saga
        .attempt_internal_settlement(&melt_request)
        .await
        .unwrap();

    // Verify internal settlement was detected
    match decision {
        crate::mint::melt::melt_saga::state::SettlementDecision::Internal { amount } => {
            assert_eq!(
                amount,
                Amount::from(4_000).with_unit(cdk_common::CurrencyUnit::Sat),
                "Internal settlement amount should match"
            );
        }
        _ => panic!("Expected internal settlement decision"),
    }

    // STEP 6: Simulate crash - drop saga WITHOUT calling make_payment/finalize
    drop(payment_saga);

    // STEP 7: Verify pre-recovery state
    // Saga should exist in PaymentAttempted state (updated by internal settlement)
    let persisted_saga = assert_saga_exists(&mint, &operation_id).await;
    match &persisted_saga.state {
        cdk_common::mint::SagaStateEnum::Melt(state) => {
            assert_eq!(
                *state,
                MeltSagaState::PaymentAttempted,
                "Saga should be in PaymentAttempted state after internal settlement"
            );
        }
        _ => panic!("Expected Melt saga state"),
    }

    // Proofs should still be Pending
    assert_proofs_state(&mint, &input_ys, Some(State::Pending)).await;

    // Mint quote should be paid (internal settlement committed)
    let mint_quote_after = mint
        .localstore
        .get_mint_quote(&mint_quote_id)
        .await
        .unwrap()
        .expect("Mint quote should exist");
    assert_eq!(
        mint_quote_after.state(),
        MintQuoteState::Paid,
        "Mint quote should be paid after internal settlement"
    );

    // STEP 8: Run recovery
    mint.recover_from_incomplete_melt_sagas()
        .await
        .expect("Recovery should succeed");

    // STEP 9: Verify post-recovery state
    // Saga should be deleted (successfully finalized)
    assert_saga_not_exists(&mint, &operation_id).await;

    // CRITICAL: Proofs should be SPENT, not returned (None)
    // This is the key assertion - if proofs were compensated, they'd be None
    assert_proofs_state(&mint, &input_ys, Some(State::Spent)).await;

    // Melt quote should be Paid
    let melt_quote_after = mint
        .localstore
        .get_melt_quote(&melt_quote.id)
        .await
        .unwrap()
        .expect("Melt quote should exist");
    assert_eq!(
        melt_quote_after.state,
        MeltQuoteState::Paid,
        "Melt quote should be paid after recovery"
    );

    // Mint quote should still be paid
    let mint_quote_final = mint
        .localstore
        .get_mint_quote(&mint_quote_id)
        .await
        .unwrap()
        .expect("Mint quote should exist");
    assert_eq!(
        mint_quote_final.state(),
        MintQuoteState::Paid,
        "Mint quote should remain paid after recovery"
    );

    // SUCCESS: Recovery correctly finalized internal settlement!
    // No fund loss - proofs spent and mint quote paid
}

// ============================================================================
// Startup Integration Tests
// ============================================================================

/// Test: Startup recovery is called on mint.start()
#[tokio::test]
async fn test_startup_recovery_integration() {
    // STEP 1: Setup test environment
    let mint = create_test_mint().await.unwrap();

    // STEP 2: Create incomplete saga
    let proofs = mint_test_proofs(&mint, Amount::from(10_000)).await.unwrap();
    let quote = create_test_melt_quote(&mint, Amount::from(9_000)).await;
    let melt_request = create_test_melt_request(&proofs, &quote);

    let verification = mint.verify_inputs(melt_request.inputs()).await.unwrap();
    let saga = MeltSaga::new(
        std::sync::Arc::new(mint.clone()),
        mint.localstore(),
        mint.pubsub_manager(),
    );
    let setup_saga = saga
        .setup_melt(
            &melt_request,
            verification,
            PaymentMethod::Known(KnownMethod::Bolt11),
        )
        .await
        .unwrap();

    let operation_id = *setup_saga.state_data.operation.id();
    let input_ys = proofs.ys().unwrap();

    // Drop saga (simulate crash)
    drop(setup_saga);

    // Verify saga exists after setup
    assert_saga_exists(&mint, &operation_id).await;
    assert_proofs_state(&mint, &input_ys, Some(State::Pending)).await;

    // STEP 3: Manually trigger recovery (simulating restart behavior)
    // Note: create_test_mint() already calls mint.start(), so recovery should
    // have run on startup. However, since we created the saga AFTER startup,
    // we need to manually trigger recovery to simulate a restart scenario.
    mint.recover_from_incomplete_melt_sagas()
        .await
        .expect("Recovery should succeed");

    // STEP 4: Verify recovery was executed
    assert_saga_not_exists(&mint, &operation_id).await;
    assert_proofs_state(&mint, &input_ys, None).await;

    // STEP 5: Verify mint is running normally
    // (Can perform new melt operations)
    let new_proofs = mint_test_proofs(&mint, Amount::from(5_000)).await.unwrap();
    let new_quote = create_test_melt_quote(&mint, Amount::from(4_000)).await;
    let new_request = create_test_melt_request(&new_proofs, &new_quote);

    let new_verification = mint.verify_inputs(new_request.inputs()).await.unwrap();
    let new_saga = MeltSaga::new(
        std::sync::Arc::new(mint.clone()),
        mint.localstore(),
        mint.pubsub_manager(),
    );
    let _new_setup = new_saga
        .setup_melt(
            &new_request,
            new_verification,
            PaymentMethod::Known(KnownMethod::Bolt11),
        )
        .await
        .unwrap();

    // SUCCESS: Recovery runs on startup and mint works normally!
}

/// Test: Startup never fails due to recovery errors
#[tokio::test]
async fn test_startup_resilient_to_recovery_errors() {
    // TODO: Implement this test
    // 1. Create corrupted saga data
    // 2. Call mint.start()
    // 3. Verify start() completes successfully
    // 4. Verify error was logged
}

// ============================================================================
// Compensation Tests
// ============================================================================

/// Test: Compensation removes proofs from database
///
/// This test validates that when compensation runs (during crash recovery),
/// the proofs are properly removed from the database and returned to the client.
#[tokio::test]
async fn test_compensation_removes_proofs() {
    // STEP 1: Setup test environment
    let mint = create_test_mint().await.unwrap();
    let proofs = mint_test_proofs(&mint, Amount::from(10_000)).await.unwrap();
    let input_ys = proofs.ys().unwrap();
    let quote = create_test_melt_quote(&mint, Amount::from(9_000)).await;
    let melt_request = create_test_melt_request(&proofs, &quote);

    // STEP 2: Setup melt saga (this marks proofs as PENDING)
    let verification = mint.verify_inputs(melt_request.inputs()).await.unwrap();
    let saga = MeltSaga::new(
        std::sync::Arc::new(mint.clone()),
        mint.localstore(),
        mint.pubsub_manager(),
    );
    let setup_saga = saga
        .setup_melt(
            &melt_request,
            verification,
            PaymentMethod::Known(KnownMethod::Bolt11),
        )
        .await
        .unwrap();

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

    // Verify proofs are PENDING
    assert_proofs_state(&mint, &input_ys, Some(State::Pending)).await;

    // STEP 3: Simulate crash and trigger compensation via recovery
    drop(setup_saga);

    // Run recovery which triggers compensation
    mint.recover_from_incomplete_melt_sagas()
        .await
        .expect("Recovery should succeed");

    // STEP 4: Verify proofs were removed from database (returned to client)
    assert_proofs_state(&mint, &input_ys, None).await;

    // STEP 5: Verify saga was cleaned up
    assert_saga_not_exists(&mint, &operation_id).await;

    // STEP 6: Verify proofs can be used again in a new melt operation
    let new_quote = create_test_melt_quote(&mint, Amount::from(9_000)).await;
    let new_request = create_test_melt_request(&proofs, &new_quote);

    let new_verification = mint.verify_inputs(new_request.inputs()).await.unwrap();
    let new_saga = MeltSaga::new(
        std::sync::Arc::new(mint.clone()),
        mint.localstore(),
        mint.pubsub_manager(),
    );
    let new_setup = new_saga
        .setup_melt(
            &new_request,
            new_verification,
            PaymentMethod::Known(KnownMethod::Bolt11),
        )
        .await
        .expect("Should be able to reuse proofs after compensation");

    // Verify new saga was created successfully
    assert_saga_exists(&mint, new_setup.state_data.operation.id()).await;

    // SUCCESS: Compensation properly removed proofs and they can be reused!
}

/// Test: Compensation removes change outputs
///
/// This test validates that compensation properly removes blinded messages
/// (change outputs) from the database during rollback.
#[tokio::test]
async fn test_compensation_removes_change_outputs() {
    use cdk_common::nuts::MeltRequest;

    use crate::test_helpers::mint::create_test_blinded_messages;

    // STEP 1: Setup test environment
    let mint = create_test_mint().await.unwrap();

    // Create input proofs (more than needed so we have change)
    let proofs = mint_test_proofs(&mint, Amount::from(10_000)).await.unwrap();
    let quote = create_test_melt_quote(&mint, Amount::from(7_000)).await;

    // STEP 2: Create change outputs (blinded messages)
    // Change = 10,000 - 7,000 - fee = ~3,000 sats
    let (blinded_messages, _premint) = create_test_blinded_messages(&mint, Amount::from(3_000))
        .await
        .unwrap();

    let blinded_secrets: Vec<_> = blinded_messages
        .iter()
        .map(|bm| bm.blinded_secret)
        .collect();

    // STEP 3: Create melt request with change outputs
    let melt_request = MeltRequest::new(quote.id.clone(), proofs.clone(), Some(blinded_messages));

    // STEP 4: Setup melt saga (this stores blinded messages)
    let verification = mint.verify_inputs(melt_request.inputs()).await.unwrap();
    let saga = MeltSaga::new(
        std::sync::Arc::new(mint.clone()),
        mint.localstore(),
        mint.pubsub_manager(),
    );
    let setup_saga = saga
        .setup_melt(
            &melt_request,
            verification,
            PaymentMethod::Known(KnownMethod::Bolt11),
        )
        .await
        .unwrap();

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

    // STEP 5: Verify blinded messages are stored in database
    let stored_info = {
        let mut tx = mint.localstore.begin_transaction().await.unwrap();
        let info = tx
            .get_melt_request_and_blinded_messages(&quote.id)
            .await
            .expect("Should be able to query melt request")
            .expect("Melt request should exist");
        tx.rollback().await.unwrap();
        info
    };

    assert_eq!(
        stored_info.change_outputs.len(),
        blinded_secrets.len(),
        "All blinded messages should be stored"
    );

    // STEP 6: Simulate crash and trigger compensation
    drop(setup_saga);

    mint.recover_from_incomplete_melt_sagas()
        .await
        .expect("Recovery should succeed");

    // STEP 7: Verify blinded messages were removed
    let result = {
        let mut tx = mint.localstore.begin_transaction().await.unwrap();
        let res = tx
            .get_melt_request_and_blinded_messages(&quote.id)
            .await
            .expect("Query should succeed");
        tx.rollback().await.unwrap();
        res
    };

    assert!(
        result.is_none(),
        "Melt request and blinded messages should be deleted after compensation"
    );

    // STEP 8: Verify saga was cleaned up
    assert_saga_not_exists(&mint, &operation_id).await;

    // SUCCESS: Compensation properly removed change outputs!
}

/// Test: Compensation resets quote state
///
/// This test validates that compensation properly resets the quote state
/// from PENDING back to UNPAID, allowing the quote to be used again.
#[tokio::test]
async fn test_compensation_resets_quote_state() {
    // STEP 1: Setup test environment
    let mint = create_test_mint().await.unwrap();
    let proofs = mint_test_proofs(&mint, Amount::from(10_000)).await.unwrap();
    let quote = create_test_melt_quote(&mint, Amount::from(9_000)).await;

    // Verify initial quote state is UNPAID
    assert_eq!(
        quote.state,
        MeltQuoteState::Unpaid,
        "Quote should start as Unpaid"
    );

    let melt_request = create_test_melt_request(&proofs, &quote);

    // STEP 2: Setup melt saga (this changes quote state to PENDING)
    let verification = mint.verify_inputs(melt_request.inputs()).await.unwrap();
    let saga = MeltSaga::new(
        std::sync::Arc::new(mint.clone()),
        mint.localstore(),
        mint.pubsub_manager(),
    );
    let setup_saga = saga
        .setup_melt(
            &melt_request,
            verification,
            PaymentMethod::Known(KnownMethod::Bolt11),
        )
        .await
        .unwrap();

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

    // STEP 3: Verify quote state became PENDING
    let pending_quote = mint
        .localstore
        .get_melt_quote(&quote.id)
        .await
        .unwrap()
        .expect("Quote should exist");

    assert_eq!(
        pending_quote.state,
        MeltQuoteState::Pending,
        "Quote state should be Pending after setup"
    );

    // STEP 4: Simulate crash and trigger compensation
    drop(setup_saga);

    mint.recover_from_incomplete_melt_sagas()
        .await
        .expect("Recovery should succeed");

    // STEP 5: Verify quote state was reset to UNPAID
    let recovered_quote = mint
        .localstore
        .get_melt_quote(&quote.id)
        .await
        .unwrap()
        .expect("Quote should still exist after compensation");

    assert_eq!(
        recovered_quote.state,
        MeltQuoteState::Unpaid,
        "Quote state should be reset to Unpaid after compensation"
    );

    // STEP 6: Verify saga was cleaned up
    assert_saga_not_exists(&mint, &operation_id).await;

    // STEP 7: Verify quote can be used again with new melt request
    let new_proofs = mint_test_proofs(&mint, Amount::from(10_000)).await.unwrap();
    let new_request = create_test_melt_request(&new_proofs, &recovered_quote);

    let new_verification = mint.verify_inputs(new_request.inputs()).await.unwrap();
    let new_saga = MeltSaga::new(
        std::sync::Arc::new(mint.clone()),
        mint.localstore(),
        mint.pubsub_manager(),
    );
    let _new_setup = new_saga
        .setup_melt(
            &new_request,
            new_verification,
            PaymentMethod::Known(KnownMethod::Bolt11),
        )
        .await
        .expect("Should be able to reuse quote after compensation");

    // SUCCESS: Quote state properly reset and can be reused!
}

/// Test: Compensation is idempotent
///
/// This test validates that running compensation multiple times is safe
/// and produces consistent results. This is important because recovery
/// might be called multiple times during debugging or startup.
#[tokio::test]
async fn test_compensation_idempotent() {
    // STEP 1: Setup test environment
    let mint = create_test_mint().await.unwrap();
    let proofs = mint_test_proofs(&mint, Amount::from(10_000)).await.unwrap();
    let input_ys = proofs.ys().unwrap();
    let quote = create_test_melt_quote(&mint, Amount::from(9_000)).await;
    let melt_request = create_test_melt_request(&proofs, &quote);

    // STEP 2: Setup melt saga
    let verification = mint.verify_inputs(melt_request.inputs()).await.unwrap();
    let saga = MeltSaga::new(
        std::sync::Arc::new(mint.clone()),
        mint.localstore(),
        mint.pubsub_manager(),
    );
    let setup_saga = saga
        .setup_melt(
            &melt_request,
            verification,
            PaymentMethod::Known(KnownMethod::Bolt11),
        )
        .await
        .unwrap();

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

    // Verify initial state
    assert_proofs_state(&mint, &input_ys, Some(State::Pending)).await;
    assert_saga_exists(&mint, &operation_id).await;

    // STEP 3: Simulate crash
    drop(setup_saga);

    // STEP 4: Run compensation first time
    mint.recover_from_incomplete_melt_sagas()
        .await
        .expect("First recovery should succeed");

    // Verify state after first compensation
    assert_proofs_state(&mint, &input_ys, None).await;
    assert_saga_not_exists(&mint, &operation_id).await;

    let quote_after_first = mint
        .localstore
        .get_melt_quote(&quote.id)
        .await
        .unwrap()
        .expect("Quote should exist");
    assert_eq!(quote_after_first.state, MeltQuoteState::Unpaid);

    // STEP 5: Run compensation second time (should be idempotent)
    mint.recover_from_incomplete_melt_sagas()
        .await
        .expect("Second recovery should succeed without errors");

    // STEP 6: Verify state is unchanged after second compensation
    assert_proofs_state(&mint, &input_ys, None).await;
    assert_saga_not_exists(&mint, &operation_id).await;

    let quote_after_second = mint
        .localstore
        .get_melt_quote(&quote.id)
        .await
        .unwrap()
        .expect("Quote should still exist");
    assert_eq!(quote_after_second.state, MeltQuoteState::Unpaid);

    // STEP 7: Verify both results are identical
    assert_eq!(
        quote_after_first.state, quote_after_second.state,
        "Quote state should be identical after multiple compensations"
    );

    // STEP 8: Run third time to be extra sure
    mint.recover_from_incomplete_melt_sagas()
        .await
        .expect("Third recovery should also succeed");

    // SUCCESS: Compensation is idempotent and safe to run multiple times!
}

/// Test: Saga is deleted after direct payment failure (not via recovery)
///
/// This test validates that when make_payment() fails and compensate_all()
/// is called directly during normal operation (not through crash recovery),
/// the saga is properly deleted from the database.
///
/// This is different from the recovery tests which simulate crashes - this
/// tests the actual payment failure path in normal operation.
#[tokio::test]
async fn test_saga_deleted_after_payment_failure() {
    use cdk_common::CurrencyUnit;
    use cdk_fake_wallet::{create_fake_invoice, FakeInvoiceDescription};

    // STEP 1: Setup test environment
    let mint = create_test_mint().await.unwrap();
    let proofs = mint_test_proofs(&mint, Amount::from(10_000)).await.unwrap();
    let input_ys = proofs.ys().unwrap();

    // STEP 2: Create a quote that will FAIL payment
    let fake_description = FakeInvoiceDescription {
        pay_invoice_state: MeltQuoteState::Failed, // Payment will fail
        check_payment_state: MeltQuoteState::Failed, // Check will also show failed
        pay_err: false,
        check_err: false,
    };

    let amount_msats: u64 = Amount::from(9_000).into();
    let invoice = create_fake_invoice(
        amount_msats,
        serde_json::to_string(&fake_description).unwrap(),
    );

    let bolt11_request = cdk_common::nuts::MeltQuoteBolt11Request {
        request: invoice,
        unit: CurrencyUnit::Sat,
        options: None,
    };

    let request = cdk_common::melt::MeltQuoteRequest::Bolt11(bolt11_request);
    let quote_response = mint.get_melt_quote(request).await.unwrap();
    let quote = mint
        .localstore
        .get_melt_quote(&quote_response.quote)
        .await
        .unwrap()
        .expect("Quote should exist");

    let melt_request = create_test_melt_request(&proofs, &quote);

    // STEP 3: Setup melt saga
    let verification = mint.verify_inputs(melt_request.inputs()).await.unwrap();
    let saga = MeltSaga::new(
        std::sync::Arc::new(mint.clone()),
        mint.localstore(),
        mint.pubsub_manager(),
    );
    let setup_saga = saga
        .setup_melt(
            &melt_request,
            verification,
            PaymentMethod::Known(KnownMethod::Bolt11),
        )
        .await
        .unwrap();
    let operation_id = setup_saga.operation_id;

    // Verify saga exists after setup
    assert_saga_exists(&mint, &operation_id).await;
    assert_proofs_state(&mint, &input_ys, Some(State::Pending)).await;

    // STEP 4: Attempt internal settlement (will return RequiresExternalPayment)
    let (payment_saga, decision) = setup_saga
        .attempt_internal_settlement(&melt_request)
        .await
        .unwrap();

    // STEP 5: Make payment - this should FAIL and trigger compensate_all()
    let result = payment_saga.make_payment(decision).await;

    // Payment should fail
    assert!(
        result.is_err(),
        "Payment should fail with Failed status from FakeWallet"
    );

    // STEP 6: Verify saga was deleted after compensation
    // This is the key assertion - the saga should be cleaned up after compensate_all()
    assert_saga_not_exists(&mint, &operation_id).await;

    // STEP 7: Verify proofs were returned (removed from database)
    assert_proofs_state(&mint, &input_ys, None).await;

    // STEP 8: Verify quote state was reset to Unpaid
    let recovered_quote = mint
        .localstore
        .get_melt_quote(&quote.id)
        .await
        .unwrap()
        .expect("Quote should still exist");
    assert_eq!(
        recovered_quote.state,
        MeltQuoteState::Unpaid,
        "Quote state should be reset to Unpaid after compensation"
    );

    // SUCCESS: Saga properly deleted after direct payment failure!
}

// ============================================================================
// Saga Content Validation Tests
// ============================================================================

/// Test: Persisted saga contains correct data
///
/// This test validates that all saga fields are persisted correctly,
/// providing comprehensive validation beyond the basic persistence test.
#[tokio::test]
async fn test_saga_content_validation() {
    // STEP 1: Setup test environment with known data
    let mint = create_test_mint().await.unwrap();

    // Create proofs with specific amount
    let proof_amount = Amount::from(10_000);
    let proofs = mint_test_proofs(&mint, proof_amount).await.unwrap();
    let input_ys = proofs.ys().unwrap();

    // Create quote with specific amount
    let quote_amount = Amount::from(9_000);
    let quote = create_test_melt_quote(&mint, quote_amount).await;

    // Create melt request
    let melt_request = create_test_melt_request(&proofs, &quote);

    // STEP 2: Setup melt saga
    let verification = mint.verify_inputs(melt_request.inputs()).await.unwrap();
    let saga = MeltSaga::new(
        std::sync::Arc::new(mint.clone()),
        mint.localstore(),
        mint.pubsub_manager(),
    );
    let setup_saga = saga
        .setup_melt(
            &melt_request,
            verification,
            PaymentMethod::Known(KnownMethod::Bolt11),
        )
        .await
        .unwrap();

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

    // STEP 3: Retrieve saga from database
    let persisted_saga = assert_saga_exists(&mint, &operation_id).await;

    // STEP 4: Verify operation_id matches exactly
    assert_eq!(
        persisted_saga.operation_id, operation_id,
        "Operation ID should match exactly"
    );

    // STEP 5: Verify operation_kind is Melt
    assert_eq!(
        persisted_saga.operation_kind,
        OperationKind::Melt,
        "Operation kind must be Melt"
    );

    // STEP 6: Verify state is SetupComplete
    match &persisted_saga.state {
        cdk_common::mint::SagaStateEnum::Melt(state) => {
            assert_eq!(
                *state,
                MeltSagaState::SetupComplete,
                "State should be SetupComplete after setup"
            );
        }
        _ => panic!("Expected Melt saga state, got {:?}", persisted_saga.state),
    }

    // STEP 7: Verify input_ys can be looked up by operation_id
    let stored_input_ys = mint
        .localstore
        .get_proof_ys_by_operation_id(&persisted_saga.operation_id)
        .await
        .unwrap();
    assert_eq!(
        stored_input_ys.len(),
        input_ys.len(),
        "Should store all input Ys"
    );

    // Verify each Y is present
    for (i, expected_y) in input_ys.iter().enumerate() {
        assert!(
            stored_input_ys.contains(expected_y),
            "Input Y at index {} should be stored: {:?}",
            i,
            expected_y
        );
    }

    // STEP 8: Verify timestamps are set and reasonable
    let current_timestamp = web_time::SystemTime::now()
        .duration_since(web_time::UNIX_EPOCH)
        .unwrap()
        .as_secs();

    assert!(
        persisted_saga.created_at > 0,
        "Created timestamp should be set"
    );
    assert!(
        persisted_saga.updated_at > 0,
        "Updated timestamp should be set"
    );

    // Timestamps should be recent (within last hour)
    assert!(
        persisted_saga.created_at <= current_timestamp,
        "Created timestamp should not be in the future"
    );
    assert!(
        persisted_saga.created_at > current_timestamp - 3600,
        "Created timestamp should be recent (within last hour)"
    );

    // For new saga, created_at and updated_at should match
    assert_eq!(
        persisted_saga.created_at, persisted_saga.updated_at,
        "Timestamps should match for newly created saga"
    );

    // STEP 9: Verify blinded_secrets lookup returns empty (not used for melt without change)
    let stored_blinded_secrets = mint
        .localstore
        .get_blinded_secrets_by_operation_id(&persisted_saga.operation_id)
        .await
        .unwrap();
    assert!(
        stored_blinded_secrets.is_empty(),
        "Melt saga without change should have no blinded_secrets"
    );

    // SUCCESS: All saga content validated!
}

/// Test: Saga timestamps remain consistent across retrievals
///
/// Note: The melt saga doesn't have intermediate state updates that persist
/// to the database. It's created in SetupComplete state and then deleted on
/// finalize. This test validates that timestamps remain consistent when
/// retrieving the saga multiple times from the database.
#[tokio::test]
async fn test_saga_state_updates_timestamp() {
    // STEP 1: Setup test environment
    let mint = create_test_mint().await.unwrap();
    let proofs = mint_test_proofs(&mint, Amount::from(10_000)).await.unwrap();
    let quote = create_test_melt_quote(&mint, Amount::from(9_000)).await;
    let melt_request = create_test_melt_request(&proofs, &quote);

    // STEP 2: Setup melt saga and note timestamps
    let verification = mint.verify_inputs(melt_request.inputs()).await.unwrap();
    let saga = MeltSaga::new(
        std::sync::Arc::new(mint.clone()),
        mint.localstore(),
        mint.pubsub_manager(),
    );
    let setup_saga = saga
        .setup_melt(
            &melt_request,
            verification,
            PaymentMethod::Known(KnownMethod::Bolt11),
        )
        .await
        .unwrap();

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

    // STEP 3: Retrieve saga and note timestamps
    let saga1 = assert_saga_exists(&mint, &operation_id).await;
    let created_at_1 = saga1.created_at;
    let updated_at_1 = saga1.updated_at;

    // STEP 4: Wait a brief moment
    tokio::time::sleep(tokio::time::Duration::from_millis(10)).await;

    // STEP 5: Retrieve saga again
    let saga2 = assert_saga_exists(&mint, &operation_id).await;
    let created_at_2 = saga2.created_at;
    let updated_at_2 = saga2.updated_at;

    // STEP 6: Verify timestamps remain unchanged across retrievals
    assert_eq!(
        created_at_1, created_at_2,
        "Created timestamp should not change across retrievals"
    );
    assert_eq!(
        updated_at_1, updated_at_2,
        "Updated timestamp should not change across retrievals"
    );

    // STEP 7: Verify timestamps are identical for new saga
    assert_eq!(
        created_at_1, updated_at_1,
        "New saga should have matching created_at and updated_at"
    );

    // SUCCESS: Timestamps are consistent!
}

// ============================================================================
// Query Tests
// ============================================================================

/// Test: get_incomplete_sagas returns only melt sagas
///
/// This test validates that the database query correctly filters sagas
/// by operation kind, only returning melt sagas when requested.
#[tokio::test]
async fn test_get_incomplete_sagas_filters_by_kind() {
    use crate::mint::swap::swap_saga::SwapSaga;
    use crate::test_helpers::mint::create_test_blinded_messages;

    // STEP 1: Setup test environment
    let mint = create_test_mint().await.unwrap();

    // STEP 2: Create a melt saga
    let melt_proofs = mint_test_proofs(&mint, Amount::from(10_000)).await.unwrap();
    let melt_quote = create_test_melt_quote(&mint, Amount::from(9_000)).await;
    let melt_request = create_test_melt_request(&melt_proofs, &melt_quote);

    let melt_verification = mint.verify_inputs(melt_request.inputs()).await.unwrap();
    let melt_saga = MeltSaga::new(
        std::sync::Arc::new(mint.clone()),
        mint.localstore(),
        mint.pubsub_manager(),
    );
    let melt_setup = melt_saga
        .setup_melt(
            &melt_request,
            melt_verification,
            PaymentMethod::Known(KnownMethod::Bolt11),
        )
        .await
        .unwrap();

    let melt_operation_id = *melt_setup.state_data.operation.id();

    // STEP 3: Create a swap saga
    let swap_proofs = mint_test_proofs(&mint, Amount::from(5_000)).await.unwrap();
    let swap_verification = crate::mint::Verification {
        amount: Amount::from(5_000).with_unit(cdk_common::nuts::CurrencyUnit::Sat),
    };

    let (swap_outputs, _) = create_test_blinded_messages(&mint, Amount::from(5_000))
        .await
        .unwrap();

    let swap_saga = SwapSaga::new(&mint, mint.localstore(), mint.pubsub_manager());
    let _swap_setup = swap_saga
        .setup_swap(&swap_proofs, &swap_outputs, None, swap_verification)
        .await
        .unwrap();

    // STEP 4: Query for incomplete melt sagas
    let melt_sagas = mint
        .localstore
        .get_incomplete_sagas(OperationKind::Melt)
        .await
        .unwrap();

    // STEP 5: Verify only melt saga is returned
    assert_eq!(melt_sagas.len(), 1, "Should return exactly one melt saga");

    assert_eq!(
        melt_sagas[0].operation_id, melt_operation_id,
        "Returned saga should be the melt saga"
    );

    assert_eq!(
        melt_sagas[0].operation_kind,
        OperationKind::Melt,
        "Returned saga should have Melt kind"
    );

    // STEP 6: Query for incomplete swap sagas
    let swap_sagas = mint
        .localstore
        .get_incomplete_sagas(OperationKind::Swap)
        .await
        .unwrap();

    // STEP 7: Verify only swap saga is returned
    assert_eq!(swap_sagas.len(), 1, "Should return exactly one swap saga");

    assert_eq!(
        swap_sagas[0].operation_kind,
        OperationKind::Swap,
        "Returned saga should have Swap kind"
    );

    // SUCCESS: Query correctly filters by operation kind!
}

/// Test: get_incomplete_sagas returns empty when none exist
#[tokio::test]
async fn test_get_incomplete_sagas_empty() {
    let mint = create_test_mint().await.unwrap();

    let sagas = mint
        .localstore
        .get_incomplete_sagas(OperationKind::Melt)
        .await
        .unwrap();

    assert!(sagas.is_empty(), "Should have no incomplete melt sagas");
}

// ============================================================================
// Concurrent Operation Tests
// ============================================================================

/// Test: Multiple concurrent melt operations don't interfere
#[tokio::test]
async fn test_concurrent_melt_operations() {
    // STEP 1: Setup test environment
    let mint = create_test_mint().await.unwrap();

    // STEP 2: Create 5 sets of proofs and quotes concurrently
    // Using same amount for each to avoid FakeWallet limit issues
    let mut tasks = Vec::new();

    for _ in 0..5 {
        let mint_clone = mint.clone();
        let task = tokio::spawn(async move {
            let proofs = mint_test_proofs(&mint_clone, Amount::from(10_000))
                .await
                .unwrap();
            let quote = create_test_melt_quote(&mint_clone, Amount::from(9_000)).await;
            (proofs, quote)
        });
        tasks.push(task);
    }

    let proof_quote_pairs: Vec<_> = futures::future::join_all(tasks)
        .await
        .into_iter()
        .map(|r| r.unwrap())
        .collect();

    // STEP 3: Setup all melt sagas concurrently
    let mut setup_tasks = Vec::new();

    for (proofs, quote) in proof_quote_pairs {
        let mint_clone = mint.clone();
        let task = tokio::spawn(async move {
            let melt_request = create_test_melt_request(&proofs, &quote);
            let verification = mint_clone
                .verify_inputs(melt_request.inputs())
                .await
                .unwrap();
            let saga = MeltSaga::new(
                std::sync::Arc::new(mint_clone.clone()),
                mint_clone.localstore(),
                mint_clone.pubsub_manager(),
            );
            let setup_saga = saga
                .setup_melt(
                    &melt_request,
                    verification,
                    PaymentMethod::Known(KnownMethod::Bolt11),
                )
                .await
                .unwrap();
            let operation_id = *setup_saga.state_data.operation.id();
            // Drop setup_saga before returning to avoid lifetime issues
            drop(setup_saga);
            operation_id
        });
        setup_tasks.push(task);
    }

    let operation_ids: Vec<_> = futures::future::join_all(setup_tasks)
        .await
        .into_iter()
        .map(|r| r.unwrap())
        .collect();

    // STEP 4: Verify all operation_ids are unique
    let unique_ids: std::collections::HashSet<_> = operation_ids.iter().collect();
    assert_eq!(
        unique_ids.len(),
        operation_ids.len(),
        "All operation IDs should be unique"
    );

    // STEP 5: Verify all sagas exist in database
    let sagas = mint
        .localstore
        .get_incomplete_sagas(OperationKind::Melt)
        .await
        .unwrap();
    assert!(sagas.len() >= 5, "Should have at least 5 incomplete sagas");

    for operation_id in &operation_ids {
        assert!(
            sagas.iter().any(|s| s.operation_id == *operation_id),
            "Saga {} should exist in database",
            operation_id
        );
    }

    // SUCCESS: Concurrent operations work without interference!
}

/// Test: Concurrent recovery and new operations work together
#[tokio::test]
async fn test_concurrent_recovery_and_operations() {
    // STEP 1: Setup test environment
    let mint = create_test_mint().await.unwrap();

    // STEP 2: Create incomplete saga
    let proofs1 = mint_test_proofs(&mint, Amount::from(10_000)).await.unwrap();
    let quote1 = create_test_melt_quote(&mint, Amount::from(9_000)).await;
    let melt_request1 = create_test_melt_request(&proofs1, &quote1);

    let verification1 = mint.verify_inputs(melt_request1.inputs()).await.unwrap();
    let saga1 = MeltSaga::new(
        std::sync::Arc::new(mint.clone()),
        mint.localstore(),
        mint.pubsub_manager(),
    );
    let setup_saga1 = saga1
        .setup_melt(
            &melt_request1,
            verification1,
            PaymentMethod::Known(KnownMethod::Bolt11),
        )
        .await
        .unwrap();
    let incomplete_operation_id = *setup_saga1.state_data.operation.id();

    // Drop saga to simulate crash
    drop(setup_saga1);

    // Verify saga exists
    assert_saga_exists(&mint, &incomplete_operation_id).await;

    // STEP 3: Create tasks for concurrent recovery and new operation
    let mint_for_recovery = mint.clone();
    let recovery_task = tokio::spawn(async move {
        mint_for_recovery
            .recover_from_incomplete_melt_sagas()
            .await
            .expect("Recovery should succeed")
    });

    let mint_for_new_op = mint.clone();
    let new_operation_task = tokio::spawn(async move {
        let proofs2 = mint_test_proofs(&mint_for_new_op, Amount::from(10_000))
            .await
            .unwrap();
        let quote2 = create_test_melt_quote(&mint_for_new_op, Amount::from(9_000)).await;
        let melt_request2 = create_test_melt_request(&proofs2, &quote2);

        let verification2 = mint_for_new_op
            .verify_inputs(melt_request2.inputs())
            .await
            .unwrap();
        let saga2 = MeltSaga::new(
            std::sync::Arc::new(mint_for_new_op.clone()),
            mint_for_new_op.localstore(),
            mint_for_new_op.pubsub_manager(),
        );
        let setup_saga2 = saga2
            .setup_melt(
                &melt_request2,
                verification2,
                PaymentMethod::Known(KnownMethod::Bolt11),
            )
            .await
            .unwrap();
        *setup_saga2.state_data.operation.id()
    });

    // STEP 4: Wait for both tasks to complete
    let (recovery_result, new_op_result) = tokio::join!(recovery_task, new_operation_task);

    recovery_result.expect("Recovery task should complete");
    let new_operation_id = new_op_result.expect("New operation task should complete");

    // STEP 5: Verify recovery completed
    assert_saga_not_exists(&mint, &incomplete_operation_id).await;

    // STEP 6: Verify new operation succeeded
    assert_saga_exists(&mint, &new_operation_id).await;

    // SUCCESS: Concurrent recovery and operations work together!
}

// ============================================================================
// Failure Scenario Tests
// ============================================================================

/// Test: Double-spend detection during setup
#[tokio::test]
async fn test_double_spend_detection() {
    // STEP 1: Setup test environment
    let mint = create_test_mint().await.unwrap();
    let proofs = mint_test_proofs(&mint, Amount::from(10_000)).await.unwrap();

    // STEP 2: Setup first melt saga with proofs
    let quote1 = create_test_melt_quote(&mint, Amount::from(9_000)).await;
    let melt_request1 = create_test_melt_request(&proofs, &quote1);

    let verification1 = mint.verify_inputs(melt_request1.inputs()).await.unwrap();
    let saga1 = MeltSaga::new(
        std::sync::Arc::new(mint.clone()),
        mint.localstore(),
        mint.pubsub_manager(),
    );
    let _setup_saga1 = saga1
        .setup_melt(
            &melt_request1,
            verification1,
            PaymentMethod::Known(KnownMethod::Bolt11),
        )
        .await
        .unwrap();

    // Proofs should now be in PENDING state
    let input_ys = proofs.ys().unwrap();
    assert_proofs_state(&mint, &input_ys, Some(State::Pending)).await;

    // STEP 3: Try to setup second saga with same proofs
    let quote2 = create_test_melt_quote(&mint, Amount::from(8_000)).await;
    let melt_request2 = create_test_melt_request(&proofs, &quote2);

    // STEP 4: verify_inputs succeeds (only checks signatures)
    // but setup_melt should fail (checks proof states)
    let verification2 = mint.verify_inputs(melt_request2.inputs()).await.unwrap();
    let saga2 = MeltSaga::new(
        std::sync::Arc::new(mint.clone()),
        mint.localstore(),
        mint.pubsub_manager(),
    );
    let setup_result2 = saga2
        .setup_melt(
            &melt_request2,
            verification2,
            PaymentMethod::Known(KnownMethod::Bolt11),
        )
        .await;

    // STEP 5: Verify second setup fails with appropriate error
    assert!(
        setup_result2.is_err(),
        "Second melt with same proofs should fail during setup"
    );

    if let Err(error) = setup_result2 {
        let error_msg = error.to_string().to_lowercase();
        assert!(
            error_msg.contains("pending")
                || error_msg.contains("spent")
                || error_msg.contains("state"),
            "Error should mention proof state issue, got: {}",
            error
        );
    }

    // STEP 6: Verify first saga is unaffected - proofs still pending
    assert_proofs_state(&mint, &input_ys, Some(State::Pending)).await;

    // SUCCESS: Double-spend prevented!
}

/// Test: Transaction balance validation
///
/// Note: This test verifies that the mint properly validates transaction balance.
/// In the current implementation, balance checking happens during melt request
/// validation before saga setup.
#[tokio::test]
async fn test_insufficient_funds() {
    // STEP 1: Setup test environment
    let mint = create_test_mint().await.unwrap();

    // STEP 2: Create proofs
    let proofs = mint_test_proofs(&mint, Amount::from(10_000)).await.unwrap();
    let input_ys = proofs.ys().unwrap();

    // STEP 3: Create quote
    let quote = create_test_melt_quote(&mint, Amount::from(9_000)).await;

    // STEP 4: Setup a normal melt (this should succeed with sufficient funds)
    let melt_request = create_test_melt_request(&proofs, &quote);
    let verification = mint.verify_inputs(melt_request.inputs()).await.unwrap();
    let saga = MeltSaga::new(
        std::sync::Arc::new(mint.clone()),
        mint.localstore(),
        mint.pubsub_manager(),
    );
    let setup_result = saga
        .setup_melt(
            &melt_request,
            verification,
            PaymentMethod::Known(KnownMethod::Bolt11),
        )
        .await;

    // With 10000 msats input and 9000 msats quote, this should succeed
    assert!(
        setup_result.is_ok(),
        "Setup should succeed with sufficient funds"
    );

    // Clean up
    drop(setup_result);

    // Verify proofs are now marked pending (setup succeeded)
    assert_proofs_state(&mint, &input_ys, Some(State::Pending)).await;

    // SUCCESS: Balance validation works correctly!
    // Note: Testing actual insufficient funds would require creating a quote
    // that costs more than the proofs, but that's prevented at quote creation time
}

/// Test: Invalid quote ID rejection
#[tokio::test]
async fn test_invalid_quote_id() {
    // STEP 1: Setup test environment
    let mint = create_test_mint().await.unwrap();
    let proofs = mint_test_proofs(&mint, Amount::from(10_000)).await.unwrap();

    // STEP 2: Create a melt request with non-existent quote ID
    use cdk_common::nuts::MeltRequest;
    use cdk_common::QuoteId;

    let fake_quote_id = QuoteId::new_uuid();
    let melt_request = MeltRequest::new(fake_quote_id.clone(), proofs.clone(), None);

    // STEP 3: Try to setup melt saga (should fail due to invalid quote)
    let verification_result = mint.verify_inputs(melt_request.inputs()).await;

    // Verification might succeed (just checks signatures) or fail (if database issues)
    if let Ok(verification) = verification_result {
        let saga = MeltSaga::new(
            std::sync::Arc::new(mint.clone()),
            mint.localstore(),
            mint.pubsub_manager(),
        );
        let setup_result = saga
            .setup_melt(
                &melt_request,
                verification,
                PaymentMethod::Known(KnownMethod::Bolt11),
            )
            .await;

        // STEP 4: Verify setup fails with unknown quote error
        assert!(
            setup_result.is_err(),
            "Setup should fail with invalid quote ID"
        );

        if let Err(error) = setup_result {
            let error_msg = error.to_string().to_lowercase();
            assert!(
                error_msg.contains("quote")
                    || error_msg.contains("unknown")
                    || error_msg.contains("not found"),
                "Error should mention quote issue, got: {}",
                error
            );
        }

        // Note: We don't query database state after a failed setup because
        // the database may be in a transaction rollback state which can cause timeouts
    } else {
        // If verification fails due to database issues, that's also acceptable
        // for this test (we're mainly testing quote validation)
        eprintln!("Note: Verification failed (expected in some environments)");
    }

    // SUCCESS: Invalid quote ID handling works correctly!
}

/// Test: Quote already paid rejection
#[tokio::test]
async fn test_quote_already_paid() {
    // STEP 1: Setup test environment
    let mint = create_test_mint().await.unwrap();

    // STEP 2: Create and complete a full melt operation
    let proofs1 = mint_test_proofs(&mint, Amount::from(10_000)).await.unwrap();
    let quote = create_test_melt_quote(&mint, Amount::from(9_000)).await;
    let melt_request1 = create_test_melt_request(&proofs1, &quote);

    // Complete the full melt flow
    let verification1 = mint.verify_inputs(melt_request1.inputs()).await.unwrap();
    let saga1 = MeltSaga::new(
        std::sync::Arc::new(mint.clone()),
        mint.localstore(),
        mint.pubsub_manager(),
    );
    let setup_saga1 = saga1
        .setup_melt(
            &melt_request1,
            verification1,
            PaymentMethod::Known(KnownMethod::Bolt11),
        )
        .await
        .unwrap();

    let (payment_saga, decision) = setup_saga1
        .attempt_internal_settlement(&melt_request1)
        .await
        .unwrap();

    let confirmed_saga = payment_saga.make_payment(decision).await.unwrap();
    let _response = confirmed_saga.finalize().await.unwrap();

    // Verify quote is now paid
    let paid_quote = mint
        .localstore
        .get_melt_quote(&quote.id)
        .await
        .unwrap()
        .unwrap();
    assert_eq!(
        paid_quote.state,
        MeltQuoteState::Paid,
        "Quote should be paid"
    );

    // STEP 3: Try to setup new melt saga with the already-paid quote
    let proofs2 = mint_test_proofs(&mint, Amount::from(10_000)).await.unwrap();
    let melt_request2 = create_test_melt_request(&proofs2, &paid_quote);

    let verification2 = mint.verify_inputs(melt_request2.inputs()).await.unwrap();
    let saga2 = MeltSaga::new(
        std::sync::Arc::new(mint.clone()),
        mint.localstore(),
        mint.pubsub_manager(),
    );
    let setup_result2 = saga2
        .setup_melt(
            &melt_request2,
            verification2,
            PaymentMethod::Known(KnownMethod::Bolt11),
        )
        .await;

    // STEP 4: Verify setup fails
    assert!(
        setup_result2.is_err(),
        "Setup should fail with already paid quote"
    );

    if let Err(error) = setup_result2 {
        let error_msg = error.to_string().to_lowercase();
        assert!(
            error_msg.contains("paid")
                || error_msg.contains("quote")
                || error_msg.contains("state"),
            "Error should mention paid quote, got: {}",
            error
        );
    }

    // SUCCESS: Already paid quote rejected!
}

/// Test: Quote already pending rejection
#[tokio::test]
async fn test_quote_already_pending() {
    // STEP 1: Setup test environment
    let mint = create_test_mint().await.unwrap();

    // STEP 2: Setup first melt saga (this puts quote in PENDING state)
    let proofs1 = mint_test_proofs(&mint, Amount::from(10_000)).await.unwrap();
    let quote = create_test_melt_quote(&mint, Amount::from(9_000)).await;
    let melt_request1 = create_test_melt_request(&proofs1, &quote);

    let verification1 = mint.verify_inputs(melt_request1.inputs()).await.unwrap();
    let saga1 = MeltSaga::new(
        std::sync::Arc::new(mint.clone()),
        mint.localstore(),
        mint.pubsub_manager(),
    );
    let _setup_saga1 = saga1
        .setup_melt(
            &melt_request1,
            verification1,
            PaymentMethod::Known(KnownMethod::Bolt11),
        )
        .await
        .unwrap();

    // Verify quote is now pending
    let pending_quote = mint
        .localstore
        .get_melt_quote(&quote.id)
        .await
        .unwrap()
        .unwrap();
    assert_eq!(
        pending_quote.state,
        MeltQuoteState::Pending,
        "Quote should be pending"
    );

    // STEP 3: Try to setup second saga with same quote (different proofs)
    let proofs2 = mint_test_proofs(&mint, Amount::from(10_000)).await.unwrap();
    let melt_request2 = create_test_melt_request(&proofs2, &pending_quote);

    let verification2 = mint.verify_inputs(melt_request2.inputs()).await.unwrap();
    let saga2 = MeltSaga::new(
        std::sync::Arc::new(mint.clone()),
        mint.localstore(),
        mint.pubsub_manager(),
    );
    let setup_result2 = saga2
        .setup_melt(
            &melt_request2,
            verification2,
            PaymentMethod::Known(KnownMethod::Bolt11),
        )
        .await;

    // STEP 4: Verify second setup fails
    assert!(
        setup_result2.is_err(),
        "Setup should fail with pending quote"
    );

    if let Err(error) = setup_result2 {
        let error_msg = error.to_string().to_lowercase();
        assert!(
            error_msg.contains("pending")
                || error_msg.contains("quote")
                || error_msg.contains("state"),
            "Error should mention pending quote, got: {}",
            error
        );
    }

    // SUCCESS: Concurrent quote use prevented!
}

// ============================================================================
// Edge Cases
// ============================================================================

/// Test: Empty input proofs
#[tokio::test]
async fn test_empty_inputs() {
    // STEP 1: Setup test environment
    let mint = create_test_mint().await.unwrap();

    // STEP 2: Create a melt request with empty proofs
    use cdk_common::nuts::{MeltRequest, Proofs};

    let quote = create_test_melt_quote(&mint, Amount::from(9_000)).await;
    let empty_proofs = Proofs::new();

    let melt_request = MeltRequest::new(quote.id.clone(), empty_proofs, None);

    // STEP 3: Try to verify inputs (should fail with empty proofs)
    let verification_result = mint.verify_inputs(melt_request.inputs()).await;

    // Verification should fail with empty inputs
    assert!(
        verification_result.is_err(),
        "Verification should fail with empty proofs"
    );

    let error = verification_result.unwrap_err();
    let error_msg = error.to_string().to_lowercase();
    assert!(
        error_msg.contains("empty") || error_msg.contains("no") || error_msg.contains("input"),
        "Error should mention empty inputs, got: {}",
        error
    );

    // STEP 4: Verify no saga persisted
    let sagas = mint
        .localstore
        .get_incomplete_sagas(OperationKind::Melt)
        .await
        .unwrap();
    assert!(sagas.is_empty(), "No saga should be persisted");

    // SUCCESS: Empty inputs rejected!
}

/// Test: Recovery with empty input_ys in saga
#[tokio::test]
async fn test_recovery_empty_input_ys() {
    // TODO: Implement this test
    // 1. Manually create saga with empty input_ys
    // 2. Run recovery
    // 3. Verify saga is skipped gracefully
    // 4. Verify logged warning
}

/// Test: Saga with no change outputs (simple melt scenario)
///
/// This test verifies that recovery works correctly when there are no
/// change outputs to clean up (e.g., when input amount exactly matches quote amount)
#[tokio::test]
async fn test_recovery_no_melt_request() {
    // STEP 1: Setup test environment
    let mint = create_test_mint().await.unwrap();

    // Create proofs that exactly match the quote amount (no change needed)
    let amount = Amount::from(10_000);
    let proofs = mint_test_proofs(&mint, amount).await.unwrap();
    let quote = create_test_melt_quote(&mint, amount).await;

    // Create melt request without change outputs
    let melt_request = create_test_melt_request(&proofs, &quote);
    assert!(
        melt_request.outputs().is_none(),
        "Should have no change outputs"
    );

    // STEP 2: Create incomplete saga
    let verification = mint.verify_inputs(melt_request.inputs()).await.unwrap();
    let saga = MeltSaga::new(
        std::sync::Arc::new(mint.clone()),
        mint.localstore(),
        mint.pubsub_manager(),
    );
    let setup_saga = saga
        .setup_melt(
            &melt_request,
            verification,
            PaymentMethod::Known(KnownMethod::Bolt11),
        )
        .await
        .unwrap();

    let operation_id = *setup_saga.state_data.operation.id();
    let input_ys = proofs.ys().unwrap();

    // Drop saga (simulate crash)
    drop(setup_saga);

    // Verify saga exists
    assert_saga_exists(&mint, &operation_id).await;
    assert_proofs_state(&mint, &input_ys, Some(State::Pending)).await;

    // STEP 3: Run recovery
    // Should handle gracefully even with no change outputs to clean up
    mint.recover_from_incomplete_melt_sagas()
        .await
        .expect("Recovery should succeed without change outputs");

    // STEP 4: Verify recovery completed successfully
    assert_saga_not_exists(&mint, &operation_id).await;
    assert_proofs_state(&mint, &input_ys, None).await;

    // SUCCESS: Recovery works even without change outputs!
}

// ============================================================================
// Integration with check_pending_melt_quotes
// ============================================================================

/// Test: Saga recovery runs before quote checking on startup
///
/// This test verifies that saga recovery executes before quote checking,
/// preventing conflicts where both mechanisms might try to handle the same state.
#[tokio::test]
async fn test_recovery_order_on_startup() {
    // STEP 1: Setup test environment
    let mint = create_test_mint().await.unwrap();

    // STEP 2: Create incomplete saga with a pending quote
    let proofs = mint_test_proofs(&mint, Amount::from(10_000)).await.unwrap();
    let quote = create_test_melt_quote(&mint, Amount::from(9_000)).await;
    let melt_request = create_test_melt_request(&proofs, &quote);

    let verification = mint.verify_inputs(melt_request.inputs()).await.unwrap();
    let saga = MeltSaga::new(
        std::sync::Arc::new(mint.clone()),
        mint.localstore(),
        mint.pubsub_manager(),
    );
    let setup_saga = saga
        .setup_melt(
            &melt_request,
            verification,
            PaymentMethod::Known(KnownMethod::Bolt11),
        )
        .await
        .unwrap();

    let operation_id = *setup_saga.state_data.operation.id();
    let input_ys = proofs.ys().unwrap();

    // Drop saga (simulate crash) - this leaves quote in PENDING state
    drop(setup_saga);

    // Verify initial state: saga exists, quote is pending, proofs are pending
    assert_saga_exists(&mint, &operation_id).await;
    assert_proofs_state(&mint, &input_ys, Some(State::Pending)).await;

    let pending_quote = mint
        .localstore
        .get_melt_quote(&quote.id)
        .await
        .unwrap()
        .unwrap();
    assert_eq!(
        pending_quote.state,
        MeltQuoteState::Pending,
        "Quote should be pending"
    );

    // STEP 3: Manually trigger recovery (simulating startup)
    // Note: In production, mint.start() calls this automatically
    mint.recover_from_incomplete_melt_sagas()
        .await
        .expect("Recovery should succeed");

    // STEP 4: Verify saga recovery completed correctly
    // - Saga should be deleted
    // - Proofs should be removed (returned to client)
    // - Quote should be reset to UNPAID
    assert_saga_not_exists(&mint, &operation_id).await;
    assert_proofs_state(&mint, &input_ys, None).await;

    let recovered_quote = mint
        .localstore
        .get_melt_quote(&quote.id)
        .await
        .unwrap()
        .unwrap();
    assert_eq!(
        recovered_quote.state,
        MeltQuoteState::Unpaid,
        "Quote should be reset to unpaid"
    );

    // STEP 5: Verify no conflicts - system is in consistent state
    // Quote can be used again with new proofs
    let new_proofs = mint_test_proofs(&mint, Amount::from(10_000)).await.unwrap();
    let new_request = create_test_melt_request(&new_proofs, &recovered_quote);

    let new_verification = mint.verify_inputs(new_request.inputs()).await.unwrap();
    let new_saga = MeltSaga::new(
        std::sync::Arc::new(mint.clone()),
        mint.localstore(),
        mint.pubsub_manager(),
    );
    let _new_setup = new_saga
        .setup_melt(
            &new_request,
            new_verification,
            PaymentMethod::Known(KnownMethod::Bolt11),
        )
        .await
        .unwrap();

    // SUCCESS: Recovery order is correct, no conflicts!
}

/// Test: Saga recovery and quote checking don't duplicate work
///
/// This test verifies that compensation is idempotent - running recovery
/// multiple times doesn't cause errors or duplicate work.
#[tokio::test]
async fn test_no_duplicate_recovery() {
    // STEP 1: Setup test environment
    let mint = create_test_mint().await.unwrap();

    // STEP 2: Create incomplete saga with pending quote
    let proofs = mint_test_proofs(&mint, Amount::from(10_000)).await.unwrap();
    let quote = create_test_melt_quote(&mint, Amount::from(9_000)).await;
    let melt_request = create_test_melt_request(&proofs, &quote);

    let verification = mint.verify_inputs(melt_request.inputs()).await.unwrap();
    let saga = MeltSaga::new(
        std::sync::Arc::new(mint.clone()),
        mint.localstore(),
        mint.pubsub_manager(),
    );
    let setup_saga = saga
        .setup_melt(
            &melt_request,
            verification,
            PaymentMethod::Known(KnownMethod::Bolt11),
        )
        .await
        .unwrap();

    let operation_id = *setup_saga.state_data.operation.id();
    let input_ys = proofs.ys().unwrap();

    // Drop saga (simulate crash)
    drop(setup_saga);

    // Verify saga exists and proofs are pending
    assert_saga_exists(&mint, &operation_id).await;
    assert_proofs_state(&mint, &input_ys, Some(State::Pending)).await;

    // STEP 3: Run recovery first time
    mint.recover_from_incomplete_melt_sagas()
        .await
        .expect("First recovery should succeed");

    // Verify saga deleted and proofs removed
    assert_saga_not_exists(&mint, &operation_id).await;
    assert_proofs_state(&mint, &input_ys, None).await;

    let recovered_quote = mint
        .localstore
        .get_melt_quote(&quote.id)
        .await
        .unwrap()
        .unwrap();
    assert_eq!(recovered_quote.state, MeltQuoteState::Unpaid);

    // STEP 4: Run recovery again (simulating duplicate execution)
    // Should be idempotent - no errors even though saga is already cleaned up
    mint.recover_from_incomplete_melt_sagas()
        .await
        .expect("Second recovery should succeed (idempotent)");

    // STEP 5: Verify state unchanged - still consistent
    assert_saga_not_exists(&mint, &operation_id).await;
    assert_proofs_state(&mint, &input_ys, None).await;

    let still_recovered_quote = mint
        .localstore
        .get_melt_quote(&quote.id)
        .await
        .unwrap()
        .unwrap();
    assert_eq!(still_recovered_quote.state, MeltQuoteState::Unpaid);

    // SUCCESS: Recovery is idempotent, no duplicate work or errors!
}

// ============================================================================
// Production Readiness Tests
// ============================================================================

/// Test: Operation ID uniqueness across multiple sagas
#[tokio::test]
async fn test_operation_id_uniqueness_and_tracking() {
    // STEP 1: Setup test environment
    let mint = create_test_mint().await.unwrap();

    // STEP 2: Create 10 sagas and collect their operation IDs
    // Using same amount for each to avoid FakeWallet limit issues
    let mut operation_ids = Vec::new();

    for _ in 0..10 {
        let proofs = mint_test_proofs(&mint, Amount::from(10_000)).await.unwrap();
        let quote = create_test_melt_quote(&mint, Amount::from(9_000)).await;
        let melt_request = create_test_melt_request(&proofs, &quote);

        let verification = mint.verify_inputs(melt_request.inputs()).await.unwrap();
        let saga = MeltSaga::new(
            std::sync::Arc::new(mint.clone()),
            mint.localstore(),
            mint.pubsub_manager(),
        );
        let setup_saga = saga
            .setup_melt(
                &melt_request,
                verification,
                PaymentMethod::Known(KnownMethod::Bolt11),
            )
            .await
            .unwrap();

        let operation_id = *setup_saga.state_data.operation.id();
        operation_ids.push(operation_id);

        // Keep saga alive
        drop(setup_saga);
    }

    // STEP 3: Verify all operation IDs are unique
    let unique_ids: std::collections::HashSet<_> = operation_ids.iter().collect();
    assert_eq!(
        unique_ids.len(),
        operation_ids.len(),
        "All {} operation IDs should be unique",
        operation_ids.len()
    );

    // STEP 4: Verify all sagas are trackable in database
    let sagas = mint
        .localstore
        .get_incomplete_sagas(OperationKind::Melt)
        .await
        .unwrap();

    for operation_id in &operation_ids {
        assert!(
            sagas.iter().any(|s| s.operation_id == *operation_id),
            "Saga {} should be trackable in database",
            operation_id
        );
    }

    // SUCCESS: All operation IDs are unique and trackable!
}

/// Test: Saga drop without finalize doesn't panic
#[tokio::test]
async fn test_saga_drop_without_finalize() {
    // STEP 1: Setup test environment
    let mint = create_test_mint().await.unwrap();
    let proofs = mint_test_proofs(&mint, Amount::from(10_000)).await.unwrap();
    let quote = create_test_melt_quote(&mint, Amount::from(9_000)).await;
    let melt_request = create_test_melt_request(&proofs, &quote);

    // STEP 2: Setup saga
    let verification = mint.verify_inputs(melt_request.inputs()).await.unwrap();
    let saga = MeltSaga::new(
        std::sync::Arc::new(mint.clone()),
        mint.localstore(),
        mint.pubsub_manager(),
    );
    let setup_saga = saga
        .setup_melt(
            &melt_request,
            verification,
            PaymentMethod::Known(KnownMethod::Bolt11),
        )
        .await
        .unwrap();
    let operation_id = *setup_saga.state_data.operation.id();

    // STEP 3: Drop saga without finalizing (simulates crash)
    drop(setup_saga);

    // STEP 4: Verify no panic occurred and saga remains in database
    let saga_in_db = assert_saga_exists(&mint, &operation_id).await;
    assert_eq!(saga_in_db.operation_id, operation_id);

    // SUCCESS: Drop without finalize doesn't panic!
}

/// Test: Saga drop after payment is recoverable and finalizes correctly
///
/// This test verifies that when a saga is dropped after payment but before finalize,
/// the recovery process correctly finalizes the melt (marks proofs as spent) rather
/// than compensating (returning proofs to user). This is critical for preventing
/// fund loss where the mint pays the LN invoice but returns the proofs.
#[tokio::test]
async fn test_saga_drop_after_payment() {
    // STEP 1: Setup test environment
    let mint = create_test_mint().await.unwrap();
    let proofs = mint_test_proofs(&mint, Amount::from(10_000)).await.unwrap();
    let input_ys = proofs.ys().unwrap();
    let quote = create_test_melt_quote(&mint, Amount::from(9_000)).await;
    let melt_request = create_test_melt_request(&proofs, &quote);

    // STEP 2: Setup saga and make payment
    let verification = mint.verify_inputs(melt_request.inputs()).await.unwrap();
    let saga = MeltSaga::new(
        std::sync::Arc::new(mint.clone()),
        mint.localstore(),
        mint.pubsub_manager(),
    );
    let setup_saga = saga
        .setup_melt(
            &melt_request,
            verification,
            PaymentMethod::Known(KnownMethod::Bolt11),
        )
        .await
        .unwrap();
    let operation_id = *setup_saga.state_data.operation.id();

    // Verify proofs are PENDING after setup
    assert_proofs_state(&mint, &input_ys, Some(State::Pending)).await;

    // Attempt internal settlement
    let (payment_saga, decision) = setup_saga
        .attempt_internal_settlement(&melt_request)
        .await
        .unwrap();

    // Make payment
    let confirmed_saga = payment_saga.make_payment(decision).await.unwrap();

    // STEP 3: Verify saga state is now PaymentAttempted (not SetupComplete)
    let saga_in_db = assert_saga_exists(&mint, &operation_id).await;
    match &saga_in_db.state {
        cdk_common::mint::SagaStateEnum::Melt(state) => {
            assert_eq!(
                *state,
                MeltSagaState::PaymentAttempted,
                "Saga state should be PaymentAttempted after make_payment"
            );
        }
        _ => panic!("Expected Melt saga state"),
    }

    // STEP 4: Drop before finalize (simulates crash after payment)
    drop(confirmed_saga);

    // STEP 5: Run recovery to complete the operation
    mint.recover_from_incomplete_melt_sagas()
        .await
        .expect("Recovery should succeed");

    // STEP 6: Verify saga was recovered and cleaned up
    assert_saga_not_exists(&mint, &operation_id).await;

    // STEP 7: Verify proofs were marked SPENT (not returned to user)
    // This is the critical check - if compensation ran instead of finalize,
    // proofs would be None (returned) instead of Spent
    assert_proofs_state(&mint, &input_ys, Some(State::Spent)).await;

    // STEP 8: Verify quote is marked as PAID
    let final_quote = mint
        .localstore
        .get_melt_quote(&quote.id)
        .await
        .unwrap()
        .expect("Quote should exist");
    assert_eq!(
        final_quote.state,
        MeltQuoteState::Paid,
        "Quote should be marked as Paid after recovery finalization"
    );

    // SUCCESS: Drop after payment correctly finalizes (doesn't compensate)!
}

/// Test: PaymentAttempted state triggers LN backend check during recovery
///
/// This test verifies that when recovery finds a saga in PaymentAttempted state,
/// it checks the LN backend to determine whether to finalize or compensate,
/// rather than blindly compensating like SetupComplete state.
#[tokio::test]
async fn test_payment_attempted_state_triggers_ln_check() {
    // STEP 1: Setup test environment
    let mint = create_test_mint().await.unwrap();
    let proofs = mint_test_proofs(&mint, Amount::from(10_000)).await.unwrap();
    let input_ys = proofs.ys().unwrap();
    let quote = create_test_melt_quote(&mint, Amount::from(9_000)).await;
    let melt_request = create_test_melt_request(&proofs, &quote);

    // STEP 2: Setup saga and make payment
    let verification = mint.verify_inputs(melt_request.inputs()).await.unwrap();
    let saga = MeltSaga::new(
        std::sync::Arc::new(mint.clone()),
        mint.localstore(),
        mint.pubsub_manager(),
    );
    let setup_saga = saga
        .setup_melt(
            &melt_request,
            verification,
            PaymentMethod::Known(KnownMethod::Bolt11),
        )
        .await
        .unwrap();
    let operation_id = *setup_saga.state_data.operation.id();

    // Check initial state is SetupComplete
    let saga_before_payment = assert_saga_exists(&mint, &operation_id).await;
    match &saga_before_payment.state {
        cdk_common::mint::SagaStateEnum::Melt(state) => {
            assert_eq!(
                *state,
                MeltSagaState::SetupComplete,
                "Initial state should be SetupComplete"
            );
        }
        _ => panic!("Expected Melt saga state"),
    }

    // Attempt internal settlement and make payment
    let (payment_saga, decision) = setup_saga
        .attempt_internal_settlement(&melt_request)
        .await
        .unwrap();
    let confirmed_saga = payment_saga.make_payment(decision).await.unwrap();

    // STEP 3: Verify state transitioned to PaymentAttempted
    let saga_after_payment = assert_saga_exists(&mint, &operation_id).await;
    match &saga_after_payment.state {
        cdk_common::mint::SagaStateEnum::Melt(state) => {
            assert_eq!(
                *state,
                MeltSagaState::PaymentAttempted,
                "State should be PaymentAttempted after make_payment"
            );
        }
        _ => panic!("Expected Melt saga state"),
    }

    // STEP 4: Drop saga (simulate crash after payment but before finalize)
    drop(confirmed_saga);

    // STEP 5: Run recovery - should check LN backend and finalize
    mint.recover_from_incomplete_melt_sagas()
        .await
        .expect("Recovery should succeed");

    // STEP 6: Verify correct outcome - finalized, not compensated
    assert_saga_not_exists(&mint, &operation_id).await;

    // Proofs should be SPENT (finalized), not None (compensated)
    assert_proofs_state(&mint, &input_ys, Some(State::Spent)).await;

    // Quote should be PAID
    let final_quote = mint
        .localstore
        .get_melt_quote(&quote.id)
        .await
        .unwrap()
        .expect("Quote should exist");
    assert_eq!(
        final_quote.state,
        MeltQuoteState::Paid,
        "Quote should be Paid - LN backend check should have triggered finalization"
    );

    // SUCCESS: PaymentAttempted state correctly triggers LN check and finalizes!
}

/// Test: SetupComplete state compensates without LN check
///
/// This test verifies that when recovery finds a saga in SetupComplete state,
/// it compensates (returns proofs) without checking LN backend, because
/// payment was never sent.
#[tokio::test]
async fn test_setup_complete_state_compensates() {
    // STEP 1: Setup test environment
    let mint = create_test_mint().await.unwrap();
    let proofs = mint_test_proofs(&mint, Amount::from(10_000)).await.unwrap();
    let input_ys = proofs.ys().unwrap();
    let quote = create_test_melt_quote(&mint, Amount::from(9_000)).await;
    let melt_request = create_test_melt_request(&proofs, &quote);

    // STEP 2: Setup saga but don't make payment
    let verification = mint.verify_inputs(melt_request.inputs()).await.unwrap();
    let saga = MeltSaga::new(
        std::sync::Arc::new(mint.clone()),
        mint.localstore(),
        mint.pubsub_manager(),
    );
    let setup_saga = saga
        .setup_melt(
            &melt_request,
            verification,
            PaymentMethod::Known(KnownMethod::Bolt11),
        )
        .await
        .unwrap();
    let operation_id = *setup_saga.state_data.operation.id();

    // Verify state is SetupComplete
    let saga_in_db = assert_saga_exists(&mint, &operation_id).await;
    match &saga_in_db.state {
        cdk_common::mint::SagaStateEnum::Melt(state) => {
            assert_eq!(
                *state,
                MeltSagaState::SetupComplete,
                "State should be SetupComplete"
            );
        }
        _ => panic!("Expected Melt saga state"),
    }

    // Verify proofs are PENDING
    assert_proofs_state(&mint, &input_ys, Some(State::Pending)).await;

    // STEP 3: Drop saga (simulate crash before payment)
    drop(setup_saga);

    // STEP 4: Run recovery - should compensate without LN check
    mint.recover_from_incomplete_melt_sagas()
        .await
        .expect("Recovery should succeed");

    // STEP 5: Verify correct outcome - compensated, not finalized
    assert_saga_not_exists(&mint, &operation_id).await;

    // Proofs should be None (compensated/returned), not Spent
    assert_proofs_state(&mint, &input_ys, None).await;

    // Quote should be UNPAID (reset)
    let final_quote = mint
        .localstore
        .get_melt_quote(&quote.id)
        .await
        .unwrap()
        .expect("Quote should exist");
    assert_eq!(
        final_quote.state,
        MeltQuoteState::Unpaid,
        "Quote should be Unpaid - compensation should have reset it"
    );

    // SUCCESS: SetupComplete state correctly compensates!
}

// ============================================================================
// Test Helpers
// ============================================================================

/// Helper: Create a test melt quote
///
/// # Arguments
/// * `mint` - Test mint instance
/// * `amount` - Amount in sats for the quote
///
/// # Returns
/// A valid unpaid melt quote
///
/// # How it works
/// Uses `create_fake_invoice()` from cdk-fake-wallet to generate a valid
/// bolt11 invoice that FakeWallet will process. The FakeInvoiceDescription
/// controls payment behavior (success/failure).
async fn create_test_melt_quote(
    mint: &crate::mint::Mint,
    amount: Amount,
) -> cdk_common::mint::MeltQuote {
    use cdk_common::melt::MeltQuoteRequest;
    use cdk_common::nuts::MeltQuoteBolt11Request;
    use cdk_common::CurrencyUnit;
    use cdk_fake_wallet::{create_fake_invoice, FakeInvoiceDescription};

    // Create fake invoice description (controls payment behavior)
    let fake_description = FakeInvoiceDescription {
        pay_invoice_state: MeltQuoteState::Paid, // Payment will succeed
        check_payment_state: MeltQuoteState::Paid, // Check will show paid
        pay_err: false,                          // No payment error
        check_err: false,                        // No check error
    };

    // Create valid bolt11 invoice (amount in millisats)
    // Amount is already in millisats, just convert to u64
    let amount_msats: u64 = amount.into();
    let invoice = create_fake_invoice(
        amount_msats,
        serde_json::to_string(&fake_description).unwrap(),
    );

    // Create melt quote request
    let bolt11_request = MeltQuoteBolt11Request {
        request: invoice,
        unit: CurrencyUnit::Sat,
        options: None,
    };

    let request = MeltQuoteRequest::Bolt11(bolt11_request);

    // Get quote from mint
    let quote_response = mint.get_melt_quote(request).await.unwrap();

    // Retrieve the full quote from database
    let quote = mint
        .localstore
        .get_melt_quote(&quote_response.quote)
        .await
        .unwrap()
        .expect("Quote should exist in database");

    quote
}

/// Helper: Create a test melt request
///
/// # Arguments
/// * `proofs` - Input proofs for the melt
/// * `quote` - Melt quote to use
///
/// # Returns
/// A MeltRequest ready to be used with setup_melt()
fn create_test_melt_request(
    proofs: &cdk_common::nuts::Proofs,
    quote: &cdk_common::mint::MeltQuote,
) -> cdk_common::nuts::MeltRequest<cdk_common::QuoteId> {
    use cdk_common::nuts::MeltRequest;

    MeltRequest::new(
        quote.id.clone(),
        proofs.clone(),
        None, // No change outputs for simplicity in tests
    )
}

/// Helper: Verify saga exists in database
async fn assert_saga_exists(mint: &crate::mint::Mint, operation_id: &uuid::Uuid) -> Saga {
    let sagas = mint
        .localstore
        .get_incomplete_sagas(OperationKind::Melt)
        .await
        .unwrap();

    sagas
        .into_iter()
        .find(|s| s.operation_id == *operation_id)
        .expect("Saga should exist in database")
}

/// Helper: Verify saga does not exist in database
async fn assert_saga_not_exists(mint: &crate::mint::Mint, operation_id: &uuid::Uuid) {
    let sagas = mint
        .localstore
        .get_incomplete_sagas(OperationKind::Melt)
        .await
        .unwrap();

    assert!(
        !sagas.iter().any(|s| s.operation_id == *operation_id),
        "Saga should not exist in database"
    );
}

/// Helper: Verify proofs are in expected state
async fn assert_proofs_state(
    mint: &crate::mint::Mint,
    ys: &[cdk_common::PublicKey],
    expected_state: Option<State>,
) {
    let states = mint.localstore.get_proofs_states(ys).await.unwrap();

    for state in states {
        assert_eq!(state, expected_state, "Proof state mismatch");
    }
}

// ============================================================================
// Duplicate request_lookup_id Constraint Tests
// ============================================================================

/// Test: Cannot set melt quote to pending if another quote with same lookup_id is already pending
///
/// This test verifies that when two melt quotes share the same request_lookup_id,
/// only one can be in PENDING state at a time.
#[tokio::test]
async fn test_duplicate_lookup_id_prevents_second_pending() {
    use cdk_common::melt::MeltQuoteRequest;
    use cdk_common::nuts::MeltQuoteBolt11Request;
    use cdk_common::CurrencyUnit;
    use cdk_fake_wallet::{create_fake_invoice, FakeInvoiceDescription};

    // STEP 1: Setup test environment
    let mint = create_test_mint().await.unwrap();

    // Create a fake invoice description
    let fake_description = FakeInvoiceDescription {
        pay_invoice_state: MeltQuoteState::Paid,
        check_payment_state: MeltQuoteState::Paid,
        pay_err: false,
        check_err: false,
    };

    // Create a single invoice that will be used for both quotes
    let amount_msats: u64 = 9000;
    let invoice = create_fake_invoice(
        amount_msats,
        serde_json::to_string(&fake_description).unwrap(),
    );

    // STEP 2: Create two melt quotes for the same invoice (same request_lookup_id)
    let bolt11_request1 = MeltQuoteBolt11Request {
        request: invoice.clone(),
        unit: CurrencyUnit::Sat,
        options: None,
    };
    let quote_response1 = mint
        .get_melt_quote(MeltQuoteRequest::Bolt11(bolt11_request1))
        .await
        .unwrap();

    let bolt11_request2 = MeltQuoteBolt11Request {
        request: invoice,
        unit: CurrencyUnit::Sat,
        options: None,
    };
    let quote_response2 = mint
        .get_melt_quote(MeltQuoteRequest::Bolt11(bolt11_request2))
        .await
        .unwrap();

    // Retrieve full quotes
    let quote1 = mint
        .localstore
        .get_melt_quote(&quote_response1.quote)
        .await
        .unwrap()
        .expect("Quote 1 should exist");

    let quote2 = mint
        .localstore
        .get_melt_quote(&quote_response2.quote)
        .await
        .unwrap()
        .expect("Quote 2 should exist");

    // Verify both quotes have the same lookup_id
    assert_eq!(
        quote1.request_lookup_id, quote2.request_lookup_id,
        "Both quotes should have the same request_lookup_id"
    );

    // STEP 3: Setup first melt saga (puts quote1 in PENDING state)
    let proofs1 = mint_test_proofs(&mint, Amount::from(10_000)).await.unwrap();
    let melt_request1 = create_test_melt_request(&proofs1, &quote1);

    let verification1 = mint.verify_inputs(melt_request1.inputs()).await.unwrap();
    let saga1 = MeltSaga::new(
        std::sync::Arc::new(mint.clone()),
        mint.localstore(),
        mint.pubsub_manager(),
    );
    let setup_saga1 = saga1
        .setup_melt(
            &melt_request1,
            verification1,
            PaymentMethod::Known(KnownMethod::Bolt11),
        )
        .await
        .unwrap();

    // Continue through the payment flow to release any transaction locks
    // The quote will stay in PENDING state because FakeWallet returns Paid
    // but we don't call finalize()
    let (payment_saga1, decision1) = setup_saga1
        .attempt_internal_settlement(&melt_request1)
        .await
        .unwrap();

    // Make payment but don't finalize - keeps quote in PENDING
    let confirmed_saga1 = payment_saga1.make_payment(decision1).await.unwrap();

    // Drop the saga to release resources (simulates crash before finalize)
    drop(confirmed_saga1);

    // Verify quote1 is now pending
    let pending_quote1 = mint
        .localstore
        .get_melt_quote(&quote1.id)
        .await
        .unwrap()
        .unwrap();
    assert_eq!(
        pending_quote1.state,
        MeltQuoteState::Pending,
        "Quote 1 should be pending"
    );

    // STEP 4: Try to setup second saga with quote2 (same lookup_id)
    let proofs2 = mint_test_proofs(&mint, Amount::from(10_000)).await.unwrap();
    let melt_request2 = create_test_melt_request(&proofs2, &quote2);

    let verification2 = mint.verify_inputs(melt_request2.inputs()).await.unwrap();
    let saga2 = MeltSaga::new(
        std::sync::Arc::new(mint.clone()),
        mint.localstore(),
        mint.pubsub_manager(),
    );
    let setup_result2 = saga2
        .setup_melt(
            &melt_request2,
            verification2,
            PaymentMethod::Known(KnownMethod::Bolt11),
        )
        .await;

    // STEP 5: Verify second setup fails due to duplicate pending lookup_id
    assert!(
        setup_result2.is_err(),
        "Setup should fail when another quote with same lookup_id is already pending"
    );

    if let Err(error) = setup_result2 {
        let error_msg = error.to_string().to_lowercase();
        assert!(
            error_msg.contains("duplicate")
                || error_msg.contains("pending")
                || error_msg.contains("already paid"),
            "Error should mention duplicate, pending, or already paid, got: {}",
            error
        );
    }

    // Verify quote2 is still unpaid
    let still_unpaid_quote2 = mint
        .localstore
        .get_melt_quote(&quote2.id)
        .await
        .unwrap()
        .unwrap();

    assert_eq!(
        still_unpaid_quote2.state,
        MeltQuoteState::Unpaid,
        "Quote 2 should still be unpaid"
    );

    // SUCCESS: Duplicate pending lookup_id prevented!
}

/// Test: Cannot set melt quote to pending if another quote with same lookup_id is already paid
///
/// This test verifies that once a melt quote with a specific request_lookup_id is paid,
/// no other quote with the same lookup_id can transition to pending.
#[tokio::test]
async fn test_paid_lookup_id_prevents_pending() {
    use cdk_common::melt::MeltQuoteRequest;
    use cdk_common::nuts::MeltQuoteBolt11Request;
    use cdk_common::CurrencyUnit;
    use cdk_fake_wallet::{create_fake_invoice, FakeInvoiceDescription};

    // STEP 1: Setup test environment
    let mint = create_test_mint().await.unwrap();

    // Create a fake invoice description
    let fake_description = FakeInvoiceDescription {
        pay_invoice_state: MeltQuoteState::Paid,
        check_payment_state: MeltQuoteState::Paid,
        pay_err: false,
        check_err: false,
    };

    // Create a single invoice that will be used for both quotes
    let amount_msats: u64 = 9000;
    let invoice = create_fake_invoice(
        amount_msats,
        serde_json::to_string(&fake_description).unwrap(),
    );

    // STEP 2: Create two melt quotes for the same invoice (same request_lookup_id)
    let bolt11_request1 = MeltQuoteBolt11Request {
        request: invoice.clone(),
        unit: CurrencyUnit::Sat,
        options: None,
    };
    let quote_response1 = mint
        .get_melt_quote(MeltQuoteRequest::Bolt11(bolt11_request1))
        .await
        .unwrap();

    let bolt11_request2 = MeltQuoteBolt11Request {
        request: invoice,
        unit: CurrencyUnit::Sat,
        options: None,
    };
    let quote_response2 = mint
        .get_melt_quote(MeltQuoteRequest::Bolt11(bolt11_request2))
        .await
        .unwrap();

    // Retrieve full quotes
    let quote1 = mint
        .localstore
        .get_melt_quote(&quote_response1.quote)
        .await
        .unwrap()
        .expect("Quote 1 should exist");
    let quote2 = mint
        .localstore
        .get_melt_quote(&quote_response2.quote)
        .await
        .unwrap()
        .expect("Quote 2 should exist");

    // STEP 3: Complete the first melt (marks quote1 as PAID)
    let proofs1 = mint_test_proofs(&mint, Amount::from(10_000)).await.unwrap();
    let melt_request1 = create_test_melt_request(&proofs1, &quote1);

    let verification1 = mint.verify_inputs(melt_request1.inputs()).await.unwrap();
    let saga1 = MeltSaga::new(
        std::sync::Arc::new(mint.clone()),
        mint.localstore(),
        mint.pubsub_manager(),
    );
    let setup_saga1 = saga1
        .setup_melt(
            &melt_request1,
            verification1,
            PaymentMethod::Known(KnownMethod::Bolt11),
        )
        .await
        .unwrap();

    // Complete the full melt flow for quote1
    let (payment_saga, decision) = setup_saga1
        .attempt_internal_settlement(&melt_request1)
        .await
        .unwrap();
    let confirmed_saga = payment_saga.make_payment(decision).await.unwrap();
    let _response = confirmed_saga.finalize().await.unwrap();

    // Verify quote1 is now paid
    let paid_quote1 = mint
        .localstore
        .get_melt_quote(&quote1.id)
        .await
        .unwrap()
        .unwrap();
    assert_eq!(
        paid_quote1.state,
        MeltQuoteState::Paid,
        "Quote 1 should be paid"
    );

    // STEP 4: Try to setup second saga with quote2 (same lookup_id as paid quote)
    let proofs2 = mint_test_proofs(&mint, Amount::from(10_000)).await.unwrap();
    let melt_request2 = create_test_melt_request(&proofs2, &quote2);

    let verification2 = mint.verify_inputs(melt_request2.inputs()).await.unwrap();
    let saga2 = MeltSaga::new(
        std::sync::Arc::new(mint.clone()),
        mint.localstore(),
        mint.pubsub_manager(),
    );
    let setup_result2 = saga2
        .setup_melt(
            &melt_request2,
            verification2,
            PaymentMethod::Known(KnownMethod::Bolt11),
        )
        .await;

    // STEP 5: Verify second setup fails due to already paid lookup_id
    assert!(
        setup_result2.is_err(),
        "Setup should fail when another quote with same lookup_id is already paid"
    );

    if let Err(error) = setup_result2 {
        let error_msg = error.to_string().to_lowercase();
        assert!(
            error_msg.contains("duplicate")
                || error_msg.contains("paid")
                || error_msg.contains("pending"),
            "Error should mention duplicate or paid, got: {}",
            error
        );
    }

    // SUCCESS: Paid lookup_id prevents new pending!
}

/// Test: Different lookup_ids allow concurrent pending quotes
///
/// This test verifies that melt quotes with different request_lookup_ids
/// can both be in PENDING state simultaneously.
#[tokio::test]
async fn test_different_lookup_ids_allow_concurrent_pending() {
    // STEP 1: Setup test environment
    let mint = create_test_mint().await.unwrap();

    // STEP 2: Create two quotes with different lookup_ids (different invoices)
    let quote1 = create_test_melt_quote(&mint, Amount::from(9_000)).await;
    let quote2 = create_test_melt_quote(&mint, Amount::from(8_000)).await;

    // Verify quotes have different lookup_ids
    assert_ne!(
        quote1.request_lookup_id, quote2.request_lookup_id,
        "Quotes should have different request_lookup_ids"
    );

    // STEP 3: Setup first saga (puts quote1 in PENDING state)
    let proofs1 = mint_test_proofs(&mint, Amount::from(10_000)).await.unwrap();
    let melt_request1 = create_test_melt_request(&proofs1, &quote1);

    let verification1 = mint.verify_inputs(melt_request1.inputs()).await.unwrap();
    let saga1 = MeltSaga::new(
        std::sync::Arc::new(mint.clone()),
        mint.localstore(),
        mint.pubsub_manager(),
    );
    let _setup_saga1 = saga1
        .setup_melt(
            &melt_request1,
            verification1,
            PaymentMethod::Known(KnownMethod::Bolt11),
        )
        .await
        .unwrap();

    // STEP 4: Setup second saga (puts quote2 in PENDING state)
    let proofs2 = mint_test_proofs(&mint, Amount::from(10_000)).await.unwrap();
    let melt_request2 = create_test_melt_request(&proofs2, &quote2);

    let verification2 = mint.verify_inputs(melt_request2.inputs()).await.unwrap();
    let saga2 = MeltSaga::new(
        std::sync::Arc::new(mint.clone()),
        mint.localstore(),
        mint.pubsub_manager(),
    );
    let _setup_saga2 = saga2
        .setup_melt(
            &melt_request2,
            verification2,
            PaymentMethod::Known(KnownMethod::Bolt11),
        )
        .await
        .unwrap();

    // STEP 5: Verify both quotes are pending
    let pending_quote1 = mint
        .localstore
        .get_melt_quote(&quote1.id)
        .await
        .unwrap()
        .unwrap();
    let pending_quote2 = mint
        .localstore
        .get_melt_quote(&quote2.id)
        .await
        .unwrap()
        .unwrap();

    assert_eq!(
        pending_quote1.state,
        MeltQuoteState::Pending,
        "Quote 1 should be pending"
    );
    assert_eq!(
        pending_quote2.state,
        MeltQuoteState::Pending,
        "Quote 2 should be pending"
    );

    // SUCCESS: Different lookup_ids allow concurrent pending!
}