bsv-sdk 0.2.82

Pure Rust implementation of the BSV Blockchain SDK
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
#![cfg(feature = "network")]
//! Unit tests for RemittanceManager core functionality.
//!
//! Kept as an integration test file to avoid pre-existing wallet module
//! compilation errors in the lib test target — consistent with Phase 1/2 pattern.

use std::collections::HashMap;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex as StdMutex};

use async_trait::async_trait;

use bsv::remittance::comms_layer::CommsLayer;
use bsv::remittance::error::RemittanceError;
use bsv::remittance::identity_layer::{
    AssessIdentityResult, IdentityLayer, RespondToRequestResult,
};
use bsv::remittance::manager::{
    ComposeInvoiceInput, IdentityPhase, IdentityRuntimeOptions, RemittanceEvent, RemittanceManager,
    RemittanceManagerConfig, RemittanceManagerRuntimeOptions, RemittanceManagerState, Thread,
    ThreadFlags, ThreadIdentity, ThreadRole,
};
use bsv::remittance::remittance_module::{
    AcceptSettlementResult, BuildSettlementResult, RemittanceModule,
};
use bsv::remittance::types::{
    sat_unit, Amount, IdentityVerificationAcknowledgment, IdentityVerificationRequest,
    IdentityVerificationResponse, InstrumentBase, Invoice, LineItem, ModuleContext, PeerMessage,
    Receipt, RemittanceEnvelope, RemittanceKind, RemittanceThreadState, Settlement,
};
use bsv::wallet::error::WalletError;
use bsv::wallet::interfaces::{
    AbortActionArgs, AbortActionResult, AcquireCertificateArgs, AuthenticatedResult, Certificate,
    CreateActionArgs, CreateActionResult, CreateHmacArgs, CreateHmacResult, CreateSignatureArgs,
    CreateSignatureResult, DecryptArgs, DecryptResult, DiscoverByAttributesArgs,
    DiscoverByIdentityKeyArgs, DiscoverCertificatesResult, EncryptArgs, EncryptResult,
    GetHeaderArgs, GetHeaderResult, GetHeightResult, GetNetworkResult, GetPublicKeyArgs,
    GetPublicKeyResult, GetVersionResult, InternalizeActionArgs, InternalizeActionResult,
    ListActionsArgs, ListActionsResult, ListCertificatesArgs, ListCertificatesResult,
    ListOutputsArgs, ListOutputsResult, ProveCertificateArgs, ProveCertificateResult,
    RelinquishCertificateArgs, RelinquishCertificateResult, RelinquishOutputArgs,
    RelinquishOutputResult, RevealCounterpartyKeyLinkageArgs, RevealCounterpartyKeyLinkageResult,
    RevealSpecificKeyLinkageArgs, RevealSpecificKeyLinkageResult, SignActionArgs, SignActionResult,
    VerifyHmacArgs, VerifyHmacResult, VerifySignatureArgs, VerifySignatureResult, WalletInterface,
};

// ---------------------------------------------------------------------------
// MockWallet — get_public_key returns a test identity key
// ---------------------------------------------------------------------------

struct MockWallet;

#[async_trait]
impl WalletInterface for MockWallet {
    async fn create_action(
        &self,
        _a: CreateActionArgs,
        _o: Option<&str>,
    ) -> Result<CreateActionResult, WalletError> {
        unimplemented!()
    }
    async fn sign_action(
        &self,
        _a: SignActionArgs,
        _o: Option<&str>,
    ) -> Result<SignActionResult, WalletError> {
        unimplemented!()
    }
    async fn abort_action(
        &self,
        _a: AbortActionArgs,
        _o: Option<&str>,
    ) -> Result<AbortActionResult, WalletError> {
        unimplemented!()
    }
    async fn list_actions(
        &self,
        _a: ListActionsArgs,
        _o: Option<&str>,
    ) -> Result<ListActionsResult, WalletError> {
        unimplemented!()
    }
    async fn internalize_action(
        &self,
        _a: InternalizeActionArgs,
        _o: Option<&str>,
    ) -> Result<InternalizeActionResult, WalletError> {
        unimplemented!()
    }
    async fn list_outputs(
        &self,
        _a: ListOutputsArgs,
        _o: Option<&str>,
    ) -> Result<ListOutputsResult, WalletError> {
        unimplemented!()
    }
    async fn relinquish_output(
        &self,
        _a: RelinquishOutputArgs,
        _o: Option<&str>,
    ) -> Result<RelinquishOutputResult, WalletError> {
        unimplemented!()
    }
    async fn get_public_key(
        &self,
        _a: GetPublicKeyArgs,
        _o: Option<&str>,
    ) -> Result<GetPublicKeyResult, WalletError> {
        // Return a valid compressed public key (the secp256k1 generator point in DER hex).
        // This is a well-known uncompressed point used only for testing.
        let pk = bsv::primitives::public_key::PublicKey::from_string(
            "0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798",
        )
        .map_err(|e| WalletError::InvalidParameter(e.to_string()))?;
        Ok(GetPublicKeyResult { public_key: pk })
    }
    async fn reveal_counterparty_key_linkage(
        &self,
        _a: RevealCounterpartyKeyLinkageArgs,
        _o: Option<&str>,
    ) -> Result<RevealCounterpartyKeyLinkageResult, WalletError> {
        unimplemented!()
    }
    async fn reveal_specific_key_linkage(
        &self,
        _a: RevealSpecificKeyLinkageArgs,
        _o: Option<&str>,
    ) -> Result<RevealSpecificKeyLinkageResult, WalletError> {
        unimplemented!()
    }
    async fn encrypt(
        &self,
        _a: EncryptArgs,
        _o: Option<&str>,
    ) -> Result<EncryptResult, WalletError> {
        unimplemented!()
    }
    async fn decrypt(
        &self,
        _a: DecryptArgs,
        _o: Option<&str>,
    ) -> Result<DecryptResult, WalletError> {
        unimplemented!()
    }
    async fn create_hmac(
        &self,
        _a: CreateHmacArgs,
        _o: Option<&str>,
    ) -> Result<CreateHmacResult, WalletError> {
        unimplemented!()
    }
    async fn verify_hmac(
        &self,
        _a: VerifyHmacArgs,
        _o: Option<&str>,
    ) -> Result<VerifyHmacResult, WalletError> {
        unimplemented!()
    }
    async fn create_signature(
        &self,
        _a: CreateSignatureArgs,
        _o: Option<&str>,
    ) -> Result<CreateSignatureResult, WalletError> {
        unimplemented!()
    }
    async fn verify_signature(
        &self,
        _a: VerifySignatureArgs,
        _o: Option<&str>,
    ) -> Result<VerifySignatureResult, WalletError> {
        unimplemented!()
    }
    async fn acquire_certificate(
        &self,
        _a: AcquireCertificateArgs,
        _o: Option<&str>,
    ) -> Result<Certificate, WalletError> {
        unimplemented!()
    }
    async fn list_certificates(
        &self,
        _a: ListCertificatesArgs,
        _o: Option<&str>,
    ) -> Result<ListCertificatesResult, WalletError> {
        unimplemented!()
    }
    async fn prove_certificate(
        &self,
        _a: ProveCertificateArgs,
        _o: Option<&str>,
    ) -> Result<ProveCertificateResult, WalletError> {
        unimplemented!()
    }
    async fn relinquish_certificate(
        &self,
        _a: RelinquishCertificateArgs,
        _o: Option<&str>,
    ) -> Result<RelinquishCertificateResult, WalletError> {
        unimplemented!()
    }
    async fn discover_by_identity_key(
        &self,
        _a: DiscoverByIdentityKeyArgs,
        _o: Option<&str>,
    ) -> Result<DiscoverCertificatesResult, WalletError> {
        unimplemented!()
    }
    async fn discover_by_attributes(
        &self,
        _a: DiscoverByAttributesArgs,
        _o: Option<&str>,
    ) -> Result<DiscoverCertificatesResult, WalletError> {
        unimplemented!()
    }
    async fn is_authenticated(&self, _o: Option<&str>) -> Result<AuthenticatedResult, WalletError> {
        unimplemented!()
    }
    async fn wait_for_authentication(
        &self,
        _o: Option<&str>,
    ) -> Result<AuthenticatedResult, WalletError> {
        unimplemented!()
    }
    async fn get_height(&self, _o: Option<&str>) -> Result<GetHeightResult, WalletError> {
        unimplemented!()
    }
    async fn get_header_for_height(
        &self,
        _a: GetHeaderArgs,
        _o: Option<&str>,
    ) -> Result<GetHeaderResult, WalletError> {
        unimplemented!()
    }
    async fn get_network(&self, _o: Option<&str>) -> Result<GetNetworkResult, WalletError> {
        unimplemented!()
    }
    async fn get_version(&self, _o: Option<&str>) -> Result<GetVersionResult, WalletError> {
        unimplemented!()
    }
}

// ---------------------------------------------------------------------------
// MockComms
// ---------------------------------------------------------------------------

/// Tracks all sent messages (both live and queued) as (recipient, message_box, body).
struct MockComms {
    sent: Arc<StdMutex<Vec<(String, String, String)>>>,
    /// When true, send_live_message returns an error to test queued fallback.
    fail_live: bool,
    /// Configurable list for list_messages to return.
    queued_messages: Arc<StdMutex<Vec<PeerMessage>>>,
    /// Tracks acknowledged message IDs.
    acknowledged: Arc<StdMutex<Vec<String>>>,
    /// Stored live listener callback (for verifying start_listening).
    live_callback: Arc<StdMutex<Option<Arc<dyn Fn(PeerMessage) + Send + Sync>>>>,
    /// Flag set when listen_for_live_messages is called.
    listening_flag: Arc<AtomicBool>,
}

impl MockComms {
    fn new() -> Self {
        Self {
            sent: Arc::new(StdMutex::new(Vec::new())),
            fail_live: false,
            queued_messages: Arc::new(StdMutex::new(Vec::new())),
            acknowledged: Arc::new(StdMutex::new(Vec::new())),
            live_callback: Arc::new(StdMutex::new(None)),
            listening_flag: Arc::new(AtomicBool::new(false)),
        }
    }

    #[allow(dead_code)]
    fn new_with_fail_live() -> Self {
        let mut c = Self::new();
        c.fail_live = true;
        c
    }

    #[allow(dead_code)]
    fn sent_count(&self) -> usize {
        self.sent.lock().unwrap().len()
    }

    /// Set messages to return from list_messages.
    #[allow(dead_code)]
    fn set_queued_messages(&self, msgs: Vec<PeerMessage>) {
        *self.queued_messages.lock().unwrap() = msgs;
    }
}

#[async_trait]
impl CommsLayer for MockComms {
    async fn send_message(
        &self,
        recipient: &str,
        message_box: &str,
        body: &str,
        _host_override: Option<&str>,
    ) -> Result<String, RemittanceError> {
        self.sent.lock().unwrap().push((
            recipient.to_string(),
            message_box.to_string(),
            body.to_string(),
        ));
        Ok("mock-transport-id".to_string())
    }

    async fn list_messages(
        &self,
        _message_box: &str,
        _host: Option<&str>,
    ) -> Result<Vec<PeerMessage>, RemittanceError> {
        let msgs = self.queued_messages.lock().unwrap().clone();
        Ok(msgs)
    }

    async fn acknowledge_message(&self, message_ids: &[String]) -> Result<(), RemittanceError> {
        let mut ack = self.acknowledged.lock().unwrap();
        for id in message_ids {
            ack.push(id.clone());
        }
        Ok(())
    }

    async fn send_live_message(
        &self,
        recipient: &str,
        message_box: &str,
        body: &str,
        _host_override: Option<&str>,
    ) -> Result<String, RemittanceError> {
        if self.fail_live {
            return Err(RemittanceError::Protocol("live not supported".into()));
        }
        // Record live messages in the same vec for observability.
        self.sent.lock().unwrap().push((
            recipient.to_string(),
            message_box.to_string(),
            body.to_string(),
        ));
        Ok("mock-live-id".to_string())
    }

    async fn listen_for_live_messages(
        &self,
        _message_box: &str,
        _override_host: Option<&str>,
        on_message: Arc<dyn Fn(PeerMessage) + Send + Sync>,
    ) -> Result<(), RemittanceError> {
        self.listening_flag.store(true, Ordering::SeqCst);
        *self.live_callback.lock().unwrap() = Some(on_message);
        Ok(())
    }
}

// ---------------------------------------------------------------------------
// MockIdentity
// ---------------------------------------------------------------------------

struct MockIdentity;

#[async_trait]
impl IdentityLayer for MockIdentity {
    async fn determine_certificates_to_request(
        &self,
        _counterparty: &str,
        thread_id: &str,
        _ctx: &ModuleContext,
    ) -> Result<IdentityVerificationRequest, RemittanceError> {
        Ok(IdentityVerificationRequest {
            kind: RemittanceKind::IdentityVerificationRequest,
            thread_id: thread_id.to_string(),
            request: bsv::remittance::types::IdentityRequest {
                types: HashMap::new(),
                certifiers: vec![],
            },
        })
    }

    async fn respond_to_request(
        &self,
        _counterparty: &str,
        thread_id: &str,
        _request: &IdentityVerificationRequest,
        _ctx: &ModuleContext,
    ) -> Result<RespondToRequestResult, RemittanceError> {
        Ok(RespondToRequestResult::Respond {
            response: IdentityVerificationResponse {
                kind: RemittanceKind::IdentityVerificationResponse,
                thread_id: thread_id.to_string(),
                certificates: vec![],
            },
        })
    }

    async fn assess_received_certificate_sufficiency(
        &self,
        _counterparty: &str,
        received: &IdentityVerificationResponse,
        _thread_id: &str,
    ) -> Result<AssessIdentityResult, RemittanceError> {
        Ok(AssessIdentityResult::Acknowledge(
            IdentityVerificationAcknowledgment {
                kind: RemittanceKind::IdentityVerificationAcknowledgment,
                thread_id: received.thread_id.clone(),
            },
        ))
    }
}

// ---------------------------------------------------------------------------
// MockModule
// ---------------------------------------------------------------------------

struct MockModule;

#[async_trait]
impl RemittanceModule for MockModule {
    type OptionTerms = serde_json::Value;
    type SettlementArtifact = serde_json::Value;
    type ReceiptData = serde_json::Value;

    fn id(&self) -> &str {
        "mock"
    }
    fn name(&self) -> &str {
        "Mock Module"
    }
    fn allow_unsolicited_settlements(&self) -> bool {
        false
    }

    async fn build_settlement(
        &self,
        _thread_id: &str,
        _invoice: Option<&Invoice>,
        _option: &serde_json::Value,
        _note: Option<&str>,
        _ctx: &ModuleContext,
    ) -> Result<BuildSettlementResult<serde_json::Value>, RemittanceError> {
        Ok(BuildSettlementResult::Settle {
            artifact: serde_json::json!({}),
        })
    }

    async fn accept_settlement(
        &self,
        _thread_id: &str,
        _invoice: Option<&Invoice>,
        _settlement: &serde_json::Value,
        _sender: &str,
        _ctx: &ModuleContext,
    ) -> Result<AcceptSettlementResult<serde_json::Value>, RemittanceError> {
        Ok(AcceptSettlementResult::Accept { receipt_data: None })
    }
}

// ---------------------------------------------------------------------------
// MockModuleWithOptions — supports create_option, returns fixed terms
// ---------------------------------------------------------------------------

struct MockModuleWithOptions;

#[async_trait]
impl RemittanceModule for MockModuleWithOptions {
    type OptionTerms = serde_json::Value;
    type SettlementArtifact = serde_json::Value;
    type ReceiptData = serde_json::Value;

    fn id(&self) -> &str {
        "mock"
    }
    fn name(&self) -> &str {
        "Mock Module With Options"
    }
    fn allow_unsolicited_settlements(&self) -> bool {
        false
    }
    fn supports_create_option(&self) -> bool {
        true
    }

    async fn create_option(
        &self,
        _thread_id: &str,
        _invoice: &Invoice,
        _ctx: &ModuleContext,
    ) -> Result<serde_json::Value, RemittanceError> {
        Ok(serde_json::json!({ "minAmount": 100 }))
    }

    async fn build_settlement(
        &self,
        _thread_id: &str,
        _invoice: Option<&Invoice>,
        _option: &serde_json::Value,
        _note: Option<&str>,
        _ctx: &ModuleContext,
    ) -> Result<BuildSettlementResult<serde_json::Value>, RemittanceError> {
        Ok(BuildSettlementResult::Settle {
            artifact: serde_json::json!({ "tx": "mock-tx" }),
        })
    }

    async fn accept_settlement(
        &self,
        _thread_id: &str,
        _invoice: Option<&Invoice>,
        _settlement: &serde_json::Value,
        _sender: &str,
        _ctx: &ModuleContext,
    ) -> Result<AcceptSettlementResult<serde_json::Value>, RemittanceError> {
        Ok(AcceptSettlementResult::Accept { receipt_data: None })
    }
}

// ---------------------------------------------------------------------------
// MockModuleTracked — sets called_flag when build_settlement is called
// Also allows unsolicited settlements.
// ---------------------------------------------------------------------------

struct MockModuleTracked {
    called_flag: Arc<AtomicBool>,
}

#[async_trait]
impl RemittanceModule for MockModuleTracked {
    type OptionTerms = serde_json::Value;
    type SettlementArtifact = serde_json::Value;
    type ReceiptData = serde_json::Value;

    fn id(&self) -> &str {
        "mock"
    }
    fn name(&self) -> &str {
        "Mock Module Tracked"
    }
    fn allow_unsolicited_settlements(&self) -> bool {
        true
    }
    fn supports_create_option(&self) -> bool {
        true
    }

    async fn create_option(
        &self,
        _thread_id: &str,
        _invoice: &Invoice,
        _ctx: &ModuleContext,
    ) -> Result<serde_json::Value, RemittanceError> {
        Ok(serde_json::json!({ "minAmount": 50 }))
    }

    async fn build_settlement(
        &self,
        _thread_id: &str,
        _invoice: Option<&Invoice>,
        _option: &serde_json::Value,
        _note: Option<&str>,
        _ctx: &ModuleContext,
    ) -> Result<BuildSettlementResult<serde_json::Value>, RemittanceError> {
        self.called_flag.store(true, Ordering::SeqCst);
        Ok(BuildSettlementResult::Settle {
            artifact: serde_json::json!({ "tx": "tracked-tx" }),
        })
    }

    async fn accept_settlement(
        &self,
        _thread_id: &str,
        _invoice: Option<&Invoice>,
        _settlement: &serde_json::Value,
        _sender: &str,
        _ctx: &ModuleContext,
    ) -> Result<AcceptSettlementResult<serde_json::Value>, RemittanceError> {
        Ok(AcceptSettlementResult::Accept { receipt_data: None })
    }
}

// ---------------------------------------------------------------------------
// MockModuleWithReceipt — accept_settlement returns receipt_data
// ---------------------------------------------------------------------------

struct MockModuleWithReceipt {
    accept_called: Arc<AtomicBool>,
}

#[async_trait]
impl RemittanceModule for MockModuleWithReceipt {
    type OptionTerms = serde_json::Value;
    type SettlementArtifact = serde_json::Value;
    type ReceiptData = serde_json::Value;

    fn id(&self) -> &str {
        "mock"
    }
    fn name(&self) -> &str {
        "Mock Module With Receipt"
    }
    fn allow_unsolicited_settlements(&self) -> bool {
        true
    }

    async fn build_settlement(
        &self,
        _thread_id: &str,
        _invoice: Option<&Invoice>,
        _option: &serde_json::Value,
        _note: Option<&str>,
        _ctx: &ModuleContext,
    ) -> Result<BuildSettlementResult<serde_json::Value>, RemittanceError> {
        Ok(BuildSettlementResult::Settle {
            artifact: serde_json::json!({ "tx": "receipt-module-tx" }),
        })
    }

    async fn accept_settlement(
        &self,
        _thread_id: &str,
        _invoice: Option<&Invoice>,
        _settlement: &serde_json::Value,
        _sender: &str,
        _ctx: &ModuleContext,
    ) -> Result<AcceptSettlementResult<serde_json::Value>, RemittanceError> {
        self.accept_called.store(true, Ordering::SeqCst);
        Ok(AcceptSettlementResult::Accept {
            receipt_data: Some(serde_json::json!({ "confirmed": true })),
        })
    }
}

// ---------------------------------------------------------------------------
// Test helpers
// ---------------------------------------------------------------------------

/// Build a manager with a MockModuleWithReceipt (tracks accept_settlement calls).
fn make_manager_with_receipt_module(
    comms: Arc<MockComms>,
    accept_called: Arc<AtomicBool>,
) -> RemittanceManager {
    let comms_dyn: Arc<dyn bsv::remittance::comms_layer::CommsLayer> = comms;
    RemittanceManager::new(
        RemittanceManagerConfig {
            message_box: None,
            originator: None,
            logger: None,
            options: Some(RemittanceManagerRuntimeOptions {
                auto_issue_receipt: true,
                ..Default::default()
            }),
            on_event: None,
            state_saver: None,
            state_loader: None,
            now: Some(Box::new(|| 1_000_000u64)),
            thread_id_factory: None,
        },
        Arc::new(MockWallet),
        comms_dyn,
        Some(Arc::new(MockIdentity)),
        vec![Box::new(MockModuleWithReceipt { accept_called })],
    )
}

fn make_manager() -> RemittanceManager {
    make_manager_with_config(RemittanceManagerConfig {
        message_box: None,
        originator: None,
        logger: None,
        options: None,
        on_event: None,
        state_saver: None,
        state_loader: None,
        now: None,
        thread_id_factory: None,
    })
}

fn make_manager_with_config(config: RemittanceManagerConfig) -> RemittanceManager {
    RemittanceManager::new(
        config,
        Arc::new(MockWallet),
        Arc::new(MockComms::new()),
        Some(Arc::new(MockIdentity)),
        vec![Box::new(MockModule)],
    )
}

/// Build a manager with a specific MockComms (for observing messages).
fn make_manager_with_comms(comms: Arc<MockComms>) -> RemittanceManager {
    let comms_dyn: Arc<dyn bsv::remittance::comms_layer::CommsLayer> = comms;
    RemittanceManager::new(
        RemittanceManagerConfig {
            message_box: None,
            originator: None,
            logger: None,
            options: None,
            on_event: None,
            state_saver: None,
            state_loader: None,
            now: Some(Box::new(|| 1_000_000u64)),
            thread_id_factory: None,
        },
        Arc::new(MockWallet),
        comms_dyn,
        Some(Arc::new(MockIdentity)),
        vec![Box::new(MockModuleWithOptions)],
    )
}

/// Build a manager with a tracked module (supports unsolicited settlements).
fn make_manager_with_tracked_module(
    comms: Arc<MockComms>,
    called_flag: Arc<AtomicBool>,
) -> RemittanceManager {
    let comms_dyn: Arc<dyn bsv::remittance::comms_layer::CommsLayer> = comms;
    RemittanceManager::new(
        RemittanceManagerConfig {
            message_box: None,
            originator: None,
            logger: None,
            options: None,
            on_event: None,
            state_saver: None,
            state_loader: None,
            now: Some(Box::new(|| 1_000_000u64)),
            thread_id_factory: None,
        },
        Arc::new(MockWallet),
        comms_dyn,
        Some(Arc::new(MockIdentity)),
        vec![Box::new(MockModuleTracked { called_flag })],
    )
}

fn sample_thread(thread_id: &str) -> Thread {
    Thread {
        thread_id: thread_id.to_string(),
        counterparty: "bob".to_string(),
        my_role: ThreadRole::Maker,
        their_role: ThreadRole::Taker,
        created_at: 0,
        updated_at: 0,
        state: RemittanceThreadState::New,
        state_log: vec![],
        processed_message_ids: vec![],
        protocol_log: vec![],
        identity: ThreadIdentity::default(),
        flags: ThreadFlags::default(),
        invoice: None,
        settlement: None,
        receipt: None,
        termination: None,
        last_error: None,
    }
}

fn sample_invoice_input() -> ComposeInvoiceInput {
    ComposeInvoiceInput {
        note: Some("test invoice".to_string()),
        line_items: vec![LineItem {
            id: None,
            description: "Widget".to_string(),
            quantity: None,
            unit_price: None,
            amount: Some(Amount {
                value: "1000".to_string(),
                unit: sat_unit(),
            }),
            metadata: None,
        }],
        total: Amount {
            value: "1000".to_string(),
            unit: sat_unit(),
        },
        invoice_number: "INV-001".to_string(),
        arbitrary: None,
        expires_at: None,
    }
}

/// Build a taker thread already in Invoiced state with a mock invoice containing module options.
fn invoiced_taker_thread(thread_id: &str) -> Thread {
    let invoice = Invoice {
        kind: RemittanceKind::Invoice,
        expires_at: Some(2_000_000),
        options: {
            let mut map = HashMap::new();
            map.insert("mock".to_string(), serde_json::json!({ "minAmount": 50 }));
            map
        },
        base: InstrumentBase {
            thread_id: thread_id.to_string(),
            payee: "alice".to_string(),
            payer: "bob".to_string(),
            note: None,
            line_items: vec![],
            total: Amount {
                value: "1000".to_string(),
                unit: sat_unit(),
            },
            invoice_number: "INV-001".to_string(),
            created_at: 1_000_000,
            arbitrary: None,
        },
    };
    Thread {
        thread_id: thread_id.to_string(),
        counterparty: "alice".to_string(),
        my_role: ThreadRole::Taker,
        their_role: ThreadRole::Maker,
        created_at: 0,
        updated_at: 0,
        state: RemittanceThreadState::Invoiced,
        state_log: vec![],
        processed_message_ids: vec![],
        protocol_log: vec![],
        identity: ThreadIdentity::default(),
        flags: ThreadFlags::default(),
        invoice: Some(invoice),
        settlement: None,
        receipt: None,
        termination: None,
        last_error: None,
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[tokio::test]
async fn test_constructor() {
    let manager = make_manager();
    // Unknown thread returns None
    let result = manager.get_thread("nonexistent").await;
    assert!(result.is_none());
}

#[tokio::test]
async fn test_init_restores_state() {
    let thread = sample_thread("thread-abc");
    let thread_clone = thread.clone();

    let config = RemittanceManagerConfig {
        message_box: None,
        originator: None,
        logger: None,
        options: None,
        on_event: None,
        state_saver: None,
        state_loader: Some(Box::new(move || {
            Some(RemittanceManagerState {
                v: 1,
                threads: vec![thread_clone.clone()],
                default_payment_option_id: None,
            })
        })),
        now: Some(Box::new(|| 0u64)),
        thread_id_factory: None,
    };
    let manager = make_manager_with_config(config);
    manager.init().await.unwrap();

    let restored = manager.get_thread("thread-abc").await;
    assert!(restored.is_some());
    assert_eq!(restored.unwrap().counterparty, "bob");
}

#[tokio::test]
async fn test_save_state_envelope() {
    let thread = sample_thread("t-save");

    let config = RemittanceManagerConfig {
        message_box: None,
        originator: None,
        logger: None,
        options: None,
        on_event: None,
        state_saver: None,
        state_loader: Some(Box::new(move || {
            Some(RemittanceManagerState {
                v: 1,
                threads: vec![thread.clone()],
                default_payment_option_id: None,
            })
        })),
        now: Some(Box::new(|| 0u64)),
        thread_id_factory: None,
    };
    let manager = make_manager_with_config(config);
    manager.init().await.unwrap();

    let state = manager.save_state().await;
    assert_eq!(state.v, 1);
    assert_eq!(state.threads.len(), 1);
    assert_eq!(state.threads[0].thread_id, "t-save");

    // Roundtrip through serde_json
    let json = serde_json::to_string(&state).unwrap();
    let roundtripped: RemittanceManagerState = serde_json::from_str(&json).unwrap();
    assert_eq!(roundtripped.v, 1);
    assert_eq!(roundtripped.threads.len(), 1);
    assert_eq!(roundtripped.threads[0].thread_id, "t-save");
}

#[tokio::test]
async fn test_state_roundtrip() {
    let state = RemittanceManagerState {
        v: 1,
        threads: vec![sample_thread("t-rt")],
        default_payment_option_id: Some("direct".to_string()),
    };

    let json = serde_json::to_string(&state).unwrap();
    let parsed: RemittanceManagerState = serde_json::from_str(&json).unwrap();

    assert_eq!(parsed.v, 1);
    assert_eq!(parsed.threads.len(), 1);
    assert_eq!(parsed.threads[0].thread_id, "t-rt");
    assert_eq!(parsed.default_payment_option_id.as_deref(), Some("direct"));
}

#[tokio::test]
async fn test_thread_serde() {
    let thread = sample_thread("camel-test");
    let json = serde_json::to_string(&thread).unwrap();

    // camelCase field names in JSON
    assert!(
        json.contains("\"threadId\""),
        "expected threadId in JSON: {}",
        json
    );
    assert!(
        json.contains("\"myRole\""),
        "expected myRole in JSON: {}",
        json
    );
    assert!(
        json.contains("\"stateLog\""),
        "expected stateLog in JSON: {}",
        json
    );
    assert!(
        json.contains("\"counterparty\""),
        "expected counterparty in JSON: {}",
        json
    );
    assert!(
        json.contains("\"createdAt\""),
        "expected createdAt in JSON: {}",
        json
    );
    assert!(
        json.contains("\"updatedAt\""),
        "expected updatedAt in JSON: {}",
        json
    );
}

#[tokio::test]
async fn test_invalid_transition() {
    let thread = sample_thread("t-inv");

    let config = RemittanceManagerConfig {
        message_box: None,
        originator: None,
        logger: None,
        options: None,
        on_event: None,
        state_saver: None,
        state_loader: Some(Box::new(move || {
            Some(RemittanceManagerState {
                v: 1,
                threads: vec![thread.clone()],
                default_payment_option_id: None,
            })
        })),
        now: Some(Box::new(|| 0u64)),
        thread_id_factory: None,
    };
    let manager = make_manager_with_config(config);
    manager.init().await.unwrap();

    // New -> Receipted is not a valid transition (New allows: IdentityRequested, Invoiced, Settled, Terminated, Errored)
    let result = manager
        .transition_thread_state("t-inv", RemittanceThreadState::Receipted, None)
        .await;

    assert!(
        matches!(result, Err(RemittanceError::InvalidStateTransition { .. })),
        "expected InvalidStateTransition, got {:?}",
        result
    );
}

#[tokio::test]
async fn test_get_thread_or_throw() {
    let manager = make_manager();
    manager.init().await.unwrap();

    // Unknown thread should return error
    let err = manager.get_thread_or_throw("unknown-id").await;
    assert!(matches!(err, Err(RemittanceError::Protocol(_))));

    // Known thread should return Ok
    manager.insert_thread(sample_thread("known-id")).await;
    let ok = manager.get_thread_or_throw("known-id").await;
    assert!(ok.is_ok());
    assert_eq!(ok.unwrap().thread_id, "known-id");
}

#[tokio::test]
async fn test_runtime_defaults() {
    let opts = RemittanceManagerRuntimeOptions::default();
    // receipt_provided and identity_poll_interval_ms corrected to match TS SDK (PARITY-10).
    assert!(opts.receipt_provided);
    assert!(opts.auto_issue_receipt);
    assert_eq!(opts.invoice_expiry_seconds, 3600);
    assert_eq!(opts.identity_timeout_ms, 30_000);
    assert_eq!(opts.identity_poll_interval_ms, 500);
}

#[tokio::test]
async fn test_event_listener() {
    let events: Arc<StdMutex<Vec<String>>> = Arc::new(StdMutex::new(Vec::new()));
    let events_clone = Arc::clone(&events);

    let config = RemittanceManagerConfig {
        message_box: None,
        originator: None,
        logger: None,
        options: None,
        on_event: None,
        state_saver: None,
        state_loader: None,
        now: Some(Box::new(|| 0u64)),
        thread_id_factory: None,
    };
    let manager = make_manager_with_config(config);
    manager.init().await.unwrap();

    // Register a listener that records event type names
    let listener: Arc<dyn Fn(RemittanceEvent) + Send + Sync> =
        Arc::new(move |event: RemittanceEvent| {
            let label = match &event {
                RemittanceEvent::StateChanged { .. } => "StateChanged",
                RemittanceEvent::ThreadCreated { .. } => "ThreadCreated",
                _ => "Other",
            };
            events_clone.lock().unwrap().push(label.to_string());
        });
    manager.on_event(listener).await;

    // Insert a thread in New state, then transition to IdentityRequested (valid).
    manager.insert_thread(sample_thread("evt-thread")).await;
    manager
        .transition_thread_state(
            "evt-thread",
            RemittanceThreadState::IdentityRequested,
            Some("test".to_string()),
        )
        .await
        .unwrap();

    let recorded = events.lock().unwrap().clone();
    assert!(
        recorded.contains(&"StateChanged".to_string()),
        "expected StateChanged event, got {:?}",
        recorded
    );
}

// ---------------------------------------------------------------------------
// Plan 02 tests — invoice lifecycle, pay, unsolicited settlement, etc.
// ---------------------------------------------------------------------------

#[tokio::test]
async fn test_send_invoice_lifecycle() {
    let comms = Arc::new(MockComms::new());
    let manager = make_manager_with_comms(Arc::clone(&comms));
    manager.init().await.unwrap();

    let handle = manager
        .send_invoice("counterparty", sample_invoice_input(), None)
        .await
        .expect("send_invoice should succeed");

    let thread = handle.handle.get_thread().await.unwrap();
    assert_eq!(
        thread.state,
        RemittanceThreadState::Invoiced,
        "thread should be Invoiced"
    );
    assert!(
        thread.invoice.is_some(),
        "invoice should be stored on thread"
    );
    assert!(thread.flags.has_invoiced, "has_invoiced flag should be set");

    // MockComms.send_live_message records the message; verify at least one was sent.
    let sent_count = comms.sent.lock().unwrap().len();
    assert!(
        sent_count >= 1,
        "at least one message should have been sent, got {}",
        sent_count
    );
}

#[tokio::test]
async fn test_send_invoice_for_thread() {
    let comms = Arc::new(MockComms::new());
    let manager = make_manager_with_comms(Arc::clone(&comms));
    manager.init().await.unwrap();

    // Pre-insert a thread in IdentityAcknowledged state.
    let mut thread = sample_thread("existing-thread");
    thread.state = RemittanceThreadState::IdentityAcknowledged;
    thread.counterparty = "bob".to_string();
    manager.insert_thread(thread).await;

    let handle = manager
        .send_invoice_for_thread("existing-thread", sample_invoice_input(), None)
        .await
        .expect("send_invoice_for_thread should succeed");

    let thread = handle.handle.get_thread().await.unwrap();
    assert_eq!(thread.state, RemittanceThreadState::Invoiced);
    assert!(
        thread.invoice.is_some(),
        "invoice should be stored on thread"
    );
}

#[tokio::test]
async fn test_find_invoices_payable() {
    let comms = Arc::new(MockComms::new());
    let manager = make_manager_with_comms(Arc::clone(&comms));
    manager.init().await.unwrap();

    // Thread 1: taker + Invoiced — should be returned.
    let t1 = invoiced_taker_thread("t-payable");

    // Thread 2: maker + Invoiced — should NOT be returned.
    let mut t2 = invoiced_taker_thread("t-maker-invoiced");
    t2.my_role = ThreadRole::Maker;
    t2.their_role = ThreadRole::Taker;

    // Thread 3: taker + Settled — should NOT be returned.
    let mut t3 = invoiced_taker_thread("t-settled");
    t3.state = RemittanceThreadState::Settled;

    manager.insert_thread(t1).await;
    manager.insert_thread(t2).await;
    manager.insert_thread(t3).await;

    let payable = manager.find_invoices_payable(None).await;
    assert_eq!(
        payable.len(),
        1,
        "only 1 thread should be payable, got {:?}",
        payable.len()
    );
    assert_eq!(payable[0].handle.thread_id(), "t-payable");
}

#[tokio::test]
async fn test_pay() {
    let comms = Arc::new(MockComms::new());
    let called_flag = Arc::new(AtomicBool::new(false));
    let manager = make_manager_with_tracked_module(Arc::clone(&comms), Arc::clone(&called_flag));
    manager.init().await.unwrap();

    // Insert a taker thread in Invoiced state.
    let thread = invoiced_taker_thread("t-pay");
    manager.insert_thread(thread).await;

    let handle = manager
        .pay("t-pay", Some("mock"), None)
        .await
        .expect("pay should succeed");

    assert!(
        called_flag.load(Ordering::SeqCst),
        "build_settlement_erased should have been called"
    );

    let thread = handle.get_thread().await.unwrap();
    assert_eq!(
        thread.state,
        RemittanceThreadState::Settled,
        "thread should be Settled after pay"
    );
    assert!(
        thread.settlement.is_some(),
        "settlement should be stored on thread"
    );
    assert!(thread.flags.has_paid, "has_paid flag should be set");

    let sent_count = comms.sent.lock().unwrap().len();
    assert!(
        sent_count >= 1,
        "at least one settlement message should have been sent"
    );
}

#[tokio::test]
async fn test_unsolicited_settlement() {
    let comms = Arc::new(MockComms::new());
    let called_flag = Arc::new(AtomicBool::new(false));
    let manager = make_manager_with_tracked_module(Arc::clone(&comms), Arc::clone(&called_flag));
    manager.init().await.unwrap();

    let handle = manager
        .send_unsolicited_settlement(
            "alice",
            "mock",
            "mock",
            serde_json::json!({"amount": 500}),
            None,
            None,
        )
        .await
        .expect("send_unsolicited_settlement should succeed");

    let thread = handle.get_thread().await.unwrap();
    assert!(
        matches!(thread.my_role, ThreadRole::Taker),
        "thread role should be Taker"
    );
    assert_eq!(
        thread.state,
        RemittanceThreadState::Settled,
        "thread should be Settled"
    );
    assert!(thread.settlement.is_some(), "settlement should be stored");

    let sent_count = comms.sent.lock().unwrap().len();
    assert!(sent_count >= 1, "settlement message should have been sent");
}

#[tokio::test]
async fn test_identity_exchange() {
    let identity_opts = IdentityRuntimeOptions {
        maker_request_identity: Some(IdentityPhase::BeforeInvoicing),
        taker_request_identity: None,
    };
    // Use a single MockComms instance for both observation and manager.
    let comms = Arc::new(MockComms::new());
    let comms_dyn: Arc<dyn bsv::remittance::comms_layer::CommsLayer> = comms.clone();
    let manager = RemittanceManager::new(
        RemittanceManagerConfig {
            message_box: None,
            originator: None,
            logger: None,
            options: Some(RemittanceManagerRuntimeOptions {
                identity_options: Some(identity_opts),
                ..Default::default()
            }),
            on_event: None,
            state_saver: None,
            state_loader: None,
            now: Some(Box::new(|| 1_000_000u64)),
            thread_id_factory: None,
        },
        Arc::new(MockWallet),
        comms_dyn,
        Some(Arc::new(MockIdentity)),
        vec![Box::new(MockModuleWithOptions)],
    );
    manager.init().await.unwrap();

    // send_invoice with identity options configured — should send identity request first.
    let _handle = manager
        .send_invoice("counterparty", sample_invoice_input(), None)
        .await
        .expect("send_invoice should succeed even with identity exchange");

    let sent = comms.sent.lock().unwrap().clone();
    assert!(
        sent.len() >= 2,
        "expected at least 2 messages (identity request + invoice), got {}",
        sent.len()
    );
    // The first message should be the identity verification request.
    let first_body: serde_json::Value = serde_json::from_str(&sent[0].2).unwrap();
    assert_eq!(
        first_body.get("kind").and_then(|v| v.as_str()),
        Some("identityVerificationRequest"),
        "first message should be identityVerificationRequest, got {:?}",
        first_body.get("kind")
    );
}

#[tokio::test]
async fn test_compose_invoice_includes_module_options() {
    let comms = Arc::new(MockComms::new());
    let manager = make_manager_with_comms(Arc::clone(&comms));
    manager.init().await.unwrap();

    // send_invoice to trigger compose_invoice; then inspect the stored invoice.
    let handle = manager
        .send_invoice("bob", sample_invoice_input(), None)
        .await
        .expect("send_invoice should succeed");

    let thread = handle.handle.get_thread().await.unwrap();
    let invoice = thread.invoice.expect("invoice should be stored");

    assert!(
        invoice.options.contains_key("mock"),
        "invoice.options should contain 'mock' module option, got {:?}",
        invoice.options.keys().collect::<Vec<_>>()
    );
    let option_val = &invoice.options["mock"];
    assert_eq!(
        option_val.get("minAmount").and_then(|v| v.as_u64()),
        Some(100),
        "mock option should have minAmount=100, got {:?}",
        option_val
    );
}

#[tokio::test]
async fn test_preselect_option() {
    let comms = Arc::new(MockComms::new());
    let called_flag = Arc::new(AtomicBool::new(false));
    let manager = make_manager_with_tracked_module(Arc::clone(&comms), Arc::clone(&called_flag));
    manager.init().await.unwrap();

    // Set default option.
    manager.preselect_payment_option_id("mock").await;

    // Verify it was stored.
    let default_opt = manager.get_default_payment_option_id().await;
    assert_eq!(
        default_opt.as_deref(),
        Some("mock"),
        "default option should be 'mock'"
    );

    // Insert an Invoiced taker thread and pay without explicit option_id.
    manager
        .insert_thread(invoiced_taker_thread("t-preselect"))
        .await;
    let handle = manager
        .pay("t-preselect", None, None) // no explicit option_id — should use default
        .await
        .expect("pay with preselected option should succeed");

    assert!(
        called_flag.load(Ordering::SeqCst),
        "mock module should have been called via preselected option"
    );
    let thread = handle.get_thread().await.unwrap();
    assert_eq!(thread.state, RemittanceThreadState::Settled);
}

// ---------------------------------------------------------------------------
// Plan 03 tests — sync_threads, start_listening, wait_for_receipt, dedup
// ---------------------------------------------------------------------------

/// Build a PeerMessage with the given fields.
fn make_peer_message(id: &str, sender: &str, body: &str) -> PeerMessage {
    PeerMessage {
        message_id: id.to_string(),
        sender: sender.to_string(),
        recipient: "me".to_string(),
        message_box: "remittance".to_string(),
        body: body.to_string(),
    }
}

/// Serialize a RemittanceEnvelope with Invoice kind.
fn make_invoice_envelope(thread_id: &str, invoice: Invoice) -> String {
    let payload = serde_json::to_value(&invoice).unwrap();
    let env = RemittanceEnvelope {
        v: 1,
        id: "test-env-id".to_string(),
        kind: RemittanceKind::Invoice,
        thread_id: thread_id.to_string(),
        created_at: 1_000_000,
        payload,
    };
    serde_json::to_string(&env).unwrap()
}

/// Build a minimal Invoice for testing.
fn test_invoice(thread_id: &str) -> Invoice {
    Invoice {
        kind: RemittanceKind::Invoice,
        expires_at: Some(9_999_999),
        options: {
            let mut m = HashMap::new();
            m.insert("mock".to_string(), serde_json::json!({ "minAmount": 100 }));
            m
        },
        base: InstrumentBase {
            thread_id: thread_id.to_string(),
            payee: "alice".to_string(),
            payer: "bob".to_string(),
            note: None,
            line_items: vec![],
            total: Amount {
                value: "1000".to_string(),
                unit: sat_unit(),
            },
            invoice_number: "INV-T01".to_string(),
            created_at: 1_000_000,
            arbitrary: None,
        },
    }
}

/// Build a Settlement envelope body for an existing thread.
fn make_settlement_envelope(thread_id: &str) -> String {
    let settlement = Settlement {
        kind: RemittanceKind::Settlement,
        thread_id: thread_id.to_string(),
        module_id: "mock".to_string(),
        option_id: "mock".to_string(),
        sender: "bob".to_string(),
        created_at: 1_000_000,
        artifact: serde_json::json!({ "tx": "abc" }),
        note: None,
    };
    let payload = serde_json::to_value(&settlement).unwrap();
    let env = RemittanceEnvelope {
        v: 1,
        id: "settle-env-id".to_string(),
        kind: RemittanceKind::Settlement,
        thread_id: thread_id.to_string(),
        created_at: 1_000_000,
        payload,
    };
    serde_json::to_string(&env).unwrap()
}

/// Build a Receipt envelope body for an existing thread.
fn make_receipt_envelope(thread_id: &str) -> String {
    let receipt = Receipt {
        kind: RemittanceKind::Receipt,
        thread_id: thread_id.to_string(),
        module_id: "mock".to_string(),
        option_id: "mock".to_string(),
        payee: "alice".to_string(),
        payer: "bob".to_string(),
        created_at: 1_000_000,
        receipt_data: serde_json::json!({ "confirmed": true }),
    };
    let payload = serde_json::to_value(&receipt).unwrap();
    let env = RemittanceEnvelope {
        v: 1,
        id: "receipt-env-id".to_string(),
        kind: RemittanceKind::Receipt,
        thread_id: thread_id.to_string(),
        created_at: 1_000_000,
        payload,
    };
    serde_json::to_string(&env).unwrap()
}

#[tokio::test]
async fn test_sync_threads() {
    let comms = Arc::new(MockComms::new());
    let thread_id = "sync-thread-001";
    let invoice = test_invoice(thread_id);
    let body = make_invoice_envelope(thread_id, invoice);
    let msg = make_peer_message("msg-001", "alice", &body);

    // Queue one message for list_messages to return.
    comms.set_queued_messages(vec![msg]);

    let manager = make_manager_with_comms(Arc::clone(&comms));
    manager.init().await.unwrap();

    manager
        .sync_threads(None)
        .await
        .expect("sync_threads should succeed");

    // Thread should have been created and transitioned to Invoiced.
    let thread = manager.get_thread(thread_id).await;
    assert!(
        thread.is_some(),
        "thread should have been created by sync_threads"
    );
    let thread = thread.unwrap();
    assert_eq!(
        thread.state,
        RemittanceThreadState::Invoiced,
        "thread should be Invoiced"
    );
    assert!(thread.invoice.is_some(), "invoice should be stored");

    // Message should have been acknowledged.
    let acked = comms.acknowledged.lock().unwrap().clone();
    assert!(
        acked.contains(&"msg-001".to_string()),
        "message should have been acknowledged"
    );
}

#[tokio::test]
async fn test_start_listening() {
    let comms = Arc::new(MockComms::new());
    let manager = make_manager_with_comms(Arc::clone(&comms));
    manager.init().await.unwrap();

    manager
        .start_listening(None)
        .await
        .expect("start_listening should succeed");

    // Verify listen_for_live_messages was called.
    assert!(
        comms.listening_flag.load(Ordering::SeqCst),
        "listening_flag should be set after start_listening"
    );
    assert!(
        comms.live_callback.lock().unwrap().is_some(),
        "live_callback should be stored after start_listening"
    );
}

#[tokio::test]
async fn test_wait_for_receipt_notify() {
    use tokio::time::{timeout, Duration};

    let comms = Arc::new(MockComms::new());
    let accept_called = Arc::new(AtomicBool::new(false));
    let manager = make_manager_with_receipt_module(Arc::clone(&comms), Arc::clone(&accept_called));
    manager.init().await.unwrap();

    // Set up an Invoiced taker thread.
    let thread_id = "wait-receipt-thread";
    manager
        .insert_thread(invoiced_taker_thread(thread_id))
        .await;

    // Transition to Settled first (so we can send receipt).
    manager
        .transition_thread_state(thread_id, RemittanceThreadState::Settled, None)
        .await
        .unwrap();

    // Queue a Receipt message via comms and trigger via sync_threads in a spawned task.
    let body = make_receipt_envelope(thread_id);
    let msg = make_peer_message("rcpt-001", "alice", &body);
    comms.set_queued_messages(vec![msg]);

    let manager_clone = manager.clone();
    tokio::spawn(async move {
        // Small delay to ensure wait_for_receipt is already waiting.
        tokio::time::sleep(Duration::from_millis(50)).await;

        // Process the queued receipt message to trigger Receipted transition.
        let _ = manager_clone.sync_threads(None).await;
    });

    // Wait for receipt (with timeout to prevent hanging).
    let result = timeout(
        Duration::from_secs(2),
        manager.wait_for_receipt(thread_id, None),
    )
    .await
    .expect("wait_for_receipt should complete within 2 seconds")
    .expect("wait_for_receipt should succeed");

    let receipt = match result {
        bsv::remittance::manager::WaitReceiptResult::Receipt(r) => r,
        bsv::remittance::manager::WaitReceiptResult::Terminated(_) => {
            panic!("expected Receipt, got Terminated");
        }
    };
    assert_eq!(
        receipt.receipt_data,
        serde_json::json!({ "confirmed": true }),
        "receipt_data should match"
    );
}

#[tokio::test]
async fn test_deduplication() {
    let comms = Arc::new(MockComms::new());
    let thread_id = "dedup-thread";
    let invoice = test_invoice(thread_id);
    let body = make_invoice_envelope(thread_id, invoice);

    // Same message_id sent twice.
    let msg1 = make_peer_message("dedup-msg-001", "alice", &body);
    let msg2 = make_peer_message("dedup-msg-001", "alice", &body);

    let manager = make_manager_with_comms(Arc::clone(&comms));
    manager.init().await.unwrap();

    // Queue both messages (same message_id) and process via sync_threads.
    // sync_threads calls handle_inbound_message internally for each message.
    comms.set_queued_messages(vec![msg1, msg2]);
    manager.sync_threads(None).await.unwrap();

    // Thread should exist and be in Invoiced (not double-transitioned).
    let thread = manager.get_thread(thread_id).await.unwrap();
    assert_eq!(
        thread.state,
        RemittanceThreadState::Invoiced,
        "thread should be in Invoiced (not Settled or other double-transition)"
    );

    // Processed IDs should contain dedup-msg-001 exactly once.
    let count = thread
        .processed_message_ids
        .iter()
        .filter(|id| id.as_str() == "dedup-msg-001")
        .count();
    assert_eq!(
        count, 1,
        "dedup-msg-001 should appear exactly once in processed_message_ids"
    );
}

#[tokio::test]
async fn test_thread_handle() {
    let comms = Arc::new(MockComms::new());
    let manager = make_manager_with_comms(Arc::clone(&comms));
    manager.init().await.unwrap();

    let thread_id = "handle-test-thread";
    manager.insert_thread(sample_thread(thread_id)).await;

    // Get a ThreadHandle.
    let handle = manager
        .get_thread_handle(thread_id)
        .await
        .expect("get_thread_handle should succeed");

    assert_eq!(handle.thread_id(), thread_id);

    // get_thread() on handle returns the correct thread.
    let thread = handle
        .get_thread()
        .await
        .expect("handle.get_thread should succeed");
    assert_eq!(thread.thread_id, thread_id);
    assert_eq!(thread.state, RemittanceThreadState::New);
}

#[tokio::test]
async fn test_inbound_invoice() {
    let comms = Arc::new(MockComms::new());
    let manager = make_manager_with_comms(Arc::clone(&comms));
    manager.init().await.unwrap();

    let thread_id = "inbound-invoice-thread";
    let invoice = test_invoice(thread_id);
    let body = make_invoice_envelope(thread_id, invoice);
    let msg = make_peer_message("inv-msg-001", "alice", &body);

    comms.set_queued_messages(vec![msg]);
    manager
        .sync_threads(None)
        .await
        .expect("sync_threads should succeed");

    let thread = manager
        .get_thread(thread_id)
        .await
        .expect("thread should have been created");
    // We are taker (they sent the invoice as maker).
    assert!(
        matches!(thread.my_role, ThreadRole::Taker),
        "our role should be Taker"
    );
    assert_eq!(
        thread.state,
        RemittanceThreadState::Invoiced,
        "thread should be Invoiced"
    );
    assert!(
        thread.invoice.is_some(),
        "invoice should be stored on thread"
    );
    assert!(thread.flags.has_invoiced, "has_invoiced flag should be set");
}

#[tokio::test]
async fn test_inbound_settlement_with_auto_receipt() {
    let comms = Arc::new(MockComms::new());
    let accept_called = Arc::new(AtomicBool::new(false));
    let manager = make_manager_with_receipt_module(Arc::clone(&comms), Arc::clone(&accept_called));
    manager.init().await.unwrap();

    // Pre-insert an Invoiced thread (taker sent us a settlement, so we are maker).
    let thread_id = "settle-recv-thread";
    let mut thread = sample_thread(thread_id);
    thread.my_role = ThreadRole::Maker;
    thread.their_role = ThreadRole::Taker;
    thread.state = RemittanceThreadState::Invoiced;
    thread.invoice = Some(test_invoice(thread_id));
    thread.flags.has_invoiced = true;
    manager.insert_thread(thread).await;

    let body = make_settlement_envelope(thread_id);
    let msg = make_peer_message("settle-msg-001", "bob", &body);

    comms.set_queued_messages(vec![msg]);
    manager
        .sync_threads(None)
        .await
        .expect("sync_threads for settlement should succeed");

    // accept_settlement should have been called on the module.
    assert!(
        accept_called.load(Ordering::SeqCst),
        "module.accept_settlement should have been called"
    );

    let thread = manager.get_thread(thread_id).await.unwrap();
    // auto_issue_receipt=true → should be Receipted, not just Settled.
    assert_eq!(
        thread.state,
        RemittanceThreadState::Receipted,
        "thread should be Receipted after auto-receipt, got {:?}",
        thread.state
    );
    assert!(thread.receipt.is_some(), "receipt should be stored");

    // A receipt message should have been sent back to the counterparty.
    let sent = comms.sent.lock().unwrap();
    let receipt_sent = sent.iter().any(|(_, _, body)| {
        if let Ok(v) = serde_json::from_str::<serde_json::Value>(body) {
            v.get("kind").and_then(|k| k.as_str()) == Some("receipt")
        } else {
            false
        }
    });
    assert!(
        receipt_sent,
        "a receipt message should have been sent via comms"
    );
}

// ---------------------------------------------------------------------------
// Plan 04 tests — full 7-state lifecycle (TEST-03)
// ---------------------------------------------------------------------------

/// Verifies that all 7 thread states appear in the state_log (as `to` values).
fn assert_all_seven_states_in_log(
    thread_id: &str,
    log: &[bsv::remittance::manager::StateLogEntry],
) {
    use RemittanceThreadState::*;
    let expected = [
        IdentityRequested,
        IdentityResponded,
        IdentityAcknowledged,
        Invoiced,
        Settled,
        Receipted,
    ];
    for state in &expected {
        assert!(
            log.iter().any(|e| &e.to == state),
            "state_log for thread {} missing state {:?}; log: {:?}",
            thread_id,
            state,
            log
        );
    }
}

#[tokio::test]
async fn test_full_lifecycle_new_through_receipted() {
    // Build a manager with auto_issue_receipt=true and a MockModuleWithReceipt
    // so that inbound settlement auto-receipts.
    let comms = Arc::new(MockComms::new());
    let accept_called = Arc::new(AtomicBool::new(false));
    let manager = make_manager_with_receipt_module(Arc::clone(&comms), Arc::clone(&accept_called));
    manager.init().await.unwrap();

    let thread_id = "lifecycle-all-7";

    // --- Step 1: New -> IdentityRequested ---
    // Insert a fresh thread in New state and manually drive it through
    // the identity sub-states before invoice and settlement.
    let initial = sample_thread(thread_id);
    manager.insert_thread(initial).await;

    // New -> IdentityRequested (valid per allowed_transitions)
    manager
        .transition_thread_state(
            thread_id,
            RemittanceThreadState::IdentityRequested,
            Some("identity request sent".to_string()),
        )
        .await
        .expect("New -> IdentityRequested must succeed");

    let t = manager.get_thread(thread_id).await.unwrap();
    assert_eq!(t.state, RemittanceThreadState::IdentityRequested);

    // --- Step 2: IdentityRequested -> IdentityResponded ---
    manager
        .transition_thread_state(
            thread_id,
            RemittanceThreadState::IdentityResponded,
            Some("identity response received".to_string()),
        )
        .await
        .expect("IdentityRequested -> IdentityResponded must succeed");

    let t = manager.get_thread(thread_id).await.unwrap();
    assert_eq!(t.state, RemittanceThreadState::IdentityResponded);

    // --- Step 3: IdentityResponded -> IdentityAcknowledged ---
    manager
        .transition_thread_state(
            thread_id,
            RemittanceThreadState::IdentityAcknowledged,
            Some("identity acknowledged".to_string()),
        )
        .await
        .expect("IdentityResponded -> IdentityAcknowledged must succeed");

    let t = manager.get_thread(thread_id).await.unwrap();
    assert_eq!(t.state, RemittanceThreadState::IdentityAcknowledged);

    // --- Step 4: IdentityAcknowledged -> Invoiced ---
    // Attach invoice and set invoiced flag before transitioning so the thread
    // can accept an inbound settlement later.
    // Transition to Invoiced and then replace thread data via a new insert
    // (insert_thread overwrites the existing entry).
    manager
        .transition_thread_state(
            thread_id,
            RemittanceThreadState::Invoiced,
            Some("invoice sent".to_string()),
        )
        .await
        .expect("IdentityAcknowledged -> Invoiced must succeed");

    let t = manager.get_thread(thread_id).await.unwrap();
    assert_eq!(t.state, RemittanceThreadState::Invoiced);

    // --- Step 5: Invoiced -> Settled -> Receipted via inbound settlement ---
    // The thread is now Invoiced/Maker. Inject an inbound settlement message.
    // The MockModuleWithReceipt accepts it and auto_issue_receipt fires a receipt.

    // Attach invoice to thread so accept_settlement has context.
    // We do this by re-inserting the thread with invoice data preserved;
    // insert_thread replaces the entry so we rebuild with existing state.
    let invoiced_thread = {
        let snapshot = manager.get_thread(thread_id).await.unwrap();
        Thread {
            invoice: Some(test_invoice(thread_id)),
            flags: ThreadFlags {
                has_invoiced: true,
                ..snapshot.flags
            },
            my_role: ThreadRole::Maker,
            their_role: ThreadRole::Taker,
            ..snapshot
        }
    };
    // Preserve the state log accumulated so far by using the snapshot above
    // and then re-inserting. The state is already Invoiced so no transition needed.
    manager.insert_thread(invoiced_thread).await;

    // Verify state is still Invoiced after re-insert.
    let t = manager.get_thread(thread_id).await.unwrap();
    assert_eq!(
        t.state,
        RemittanceThreadState::Invoiced,
        "should still be Invoiced after re-insert"
    );

    // Queue an inbound settlement message from the taker.
    let body = make_settlement_envelope(thread_id);
    let msg = make_peer_message("lifecycle-settle-001", "bob", &body);
    comms.set_queued_messages(vec![msg]);

    // sync_threads processes the settlement; auto-receipt fires because auto_issue_receipt=true.
    manager
        .sync_threads(None)
        .await
        .expect("sync_threads for settlement should succeed");

    // --- Assertions ---
    assert!(
        accept_called.load(Ordering::SeqCst),
        "accept_settlement must have been called"
    );

    let final_thread = manager.get_thread(thread_id).await.unwrap();

    // Final state must be Receipted.
    assert_eq!(
        final_thread.state,
        RemittanceThreadState::Receipted,
        "final state should be Receipted, got {:?}",
        final_thread.state
    );

    // Settlement and receipt must be stored.
    assert!(
        final_thread.settlement.is_some(),
        "settlement should be stored on thread"
    );
    assert!(
        final_thread.receipt.is_some(),
        "receipt should be stored on thread"
    );

    // State log must contain entries for all transitions driven (IdentityRequested
    // through Receipted — 6 transitions covering all 7 states New->Receipted).
    assert_all_seven_states_in_log(thread_id, &final_thread.state_log);

    // Verify a receipt message was sent outbound.
    let sent = comms.sent.lock().unwrap();
    let receipt_sent = sent.iter().any(|(_, _, body)| {
        if let Ok(v) = serde_json::from_str::<serde_json::Value>(body) {
            v.get("kind").and_then(|k| k.as_str()) == Some("receipt")
        } else {
            false
        }
    });
    assert!(
        receipt_sent,
        "a receipt message should have been sent outbound"
    );
}

// ---------------------------------------------------------------------------
// Phase 05.1 plan 01 — PARITY-06, PARITY-07, PARITY-10 tests
// ---------------------------------------------------------------------------

/// Build a manager configured with makerRequestIdentity=BeforeSettlement.
fn make_manager_with_identity_before_settlement(comms: Arc<MockComms>) -> RemittanceManager {
    let comms_dyn: Arc<dyn bsv::remittance::comms_layer::CommsLayer> = comms;
    RemittanceManager::new(
        RemittanceManagerConfig {
            message_box: None,
            originator: None,
            logger: None,
            options: Some(RemittanceManagerRuntimeOptions {
                identity_options: Some(IdentityRuntimeOptions {
                    maker_request_identity: Some(IdentityPhase::BeforeSettlement),
                    taker_request_identity: None,
                }),
                receipt_provided: true,
                auto_issue_receipt: false,
                ..Default::default()
            }),
            on_event: None,
            state_saver: None,
            state_loader: None,
            now: Some(Box::new(|| 1_000_000u64)),
            thread_id_factory: None,
        },
        Arc::new(MockWallet),
        comms_dyn,
        Some(Arc::new(MockIdentity)),
        vec![Box::new(MockModule)],
    )
}

/// Build a maker thread in Invoiced state with has_identified=false.
fn invoiced_maker_thread_unidentified(thread_id: &str) -> Thread {
    let invoice = Invoice {
        kind: RemittanceKind::Invoice,
        expires_at: Some(9_999_999),
        options: {
            let mut m = HashMap::new();
            m.insert("mock".to_string(), serde_json::json!({ "minAmount": 50 }));
            m
        },
        base: InstrumentBase {
            thread_id: thread_id.to_string(),
            payee: "alice".to_string(),
            payer: "bob".to_string(),
            note: None,
            line_items: vec![],
            total: Amount {
                value: "1000".to_string(),
                unit: sat_unit(),
            },
            invoice_number: "INV-GUARD".to_string(),
            created_at: 1_000_000,
            arbitrary: None,
        },
    };
    Thread {
        thread_id: thread_id.to_string(),
        counterparty: "bob".to_string(),
        my_role: ThreadRole::Maker,
        their_role: ThreadRole::Taker,
        created_at: 0,
        updated_at: 0,
        state: RemittanceThreadState::Invoiced,
        state_log: vec![],
        processed_message_ids: vec![],
        protocol_log: vec![],
        identity: ThreadIdentity::default(),
        flags: ThreadFlags {
            has_invoiced: true,
            has_identified: false,
            ..Default::default()
        },
        invoice: Some(invoice),
        settlement: None,
        receipt: None,
        termination: None,
        last_error: None,
    }
}

/// Build a maker thread in Invoiced state with has_identified=true.
fn invoiced_maker_thread_identified(thread_id: &str) -> Thread {
    let mut t = invoiced_maker_thread_unidentified(thread_id);
    t.flags.has_identified = true;
    t
}

/// Build a taker thread in Invoiced state with has_identified=false.
fn invoiced_taker_thread_unidentified(thread_id: &str) -> Thread {
    let mut t = invoiced_maker_thread_unidentified(thread_id);
    t.my_role = ThreadRole::Taker;
    t.their_role = ThreadRole::Maker;
    t.counterparty = "alice".to_string();
    t
}

// PARITY-06 + PARITY-12: Guard fires when maker has not identified and config requires it.
#[tokio::test]
async fn test_identity_before_settlement_guard() {
    let comms = Arc::new(MockComms::new());
    let manager = make_manager_with_identity_before_settlement(comms.clone());

    let thread_id = "guard-test-01";
    manager
        .insert_thread(invoiced_maker_thread_unidentified(thread_id))
        .await;

    // Queue inbound settlement.
    let body = make_settlement_envelope(thread_id);
    let msg = make_peer_message("guard-msg-01", "bob", &body);
    comms.set_queued_messages(vec![msg]);

    manager
        .sync_threads(None)
        .await
        .expect("sync should not error");

    let t = manager.get_thread(thread_id).await.unwrap();
    // Thread must be Terminated — settlement was blocked.
    assert_eq!(
        t.state,
        RemittanceThreadState::Terminated,
        "thread should be Terminated when identity required but not completed; got {:?}",
        t.state
    );

    // A Termination message must have been sent.
    let sent = comms.sent.lock().unwrap();
    let term_sent = sent.iter().any(|(_, _, body)| {
        if let Ok(v) = serde_json::from_str::<serde_json::Value>(body) {
            v.get("kind").and_then(|k| k.as_str()) == Some("termination")
        } else {
            false
        }
    });
    assert!(
        term_sent,
        "a termination message should have been sent when identity guard fires"
    );
}

// PARITY-06 + PARITY-12: Guard does not fire when has_identified=true.
#[tokio::test]
async fn test_identity_before_settlement_guard_passes_when_identified() {
    let comms = Arc::new(MockComms::new());
    let manager = make_manager_with_identity_before_settlement(comms.clone());

    let thread_id = "guard-test-02";
    manager
        .insert_thread(invoiced_maker_thread_identified(thread_id))
        .await;

    // Queue inbound settlement.
    let body = make_settlement_envelope(thread_id);
    let msg = make_peer_message("guard-msg-02", "bob", &body);
    comms.set_queued_messages(vec![msg]);

    manager
        .sync_threads(None)
        .await
        .expect("sync should not error");

    let t = manager.get_thread(thread_id).await.unwrap();
    // Settlement was accepted — thread should be Settled (auto_issue_receipt=false).
    assert_eq!(
        t.state,
        RemittanceThreadState::Settled,
        "thread should be Settled when identity is completed; got {:?}",
        t.state
    );
}

// PARITY-12: Guard does not fire when my_role=Taker (only Maker role is guarded).
#[tokio::test]
async fn test_identity_before_settlement_guard_taker_skips() {
    let comms = Arc::new(MockComms::new());
    let manager = make_manager_with_identity_before_settlement(comms.clone());

    let thread_id = "guard-test-03";
    manager
        .insert_thread(invoiced_taker_thread_unidentified(thread_id))
        .await;

    // Queue inbound settlement (taker receiving settlement is unusual but allowed by guard logic).
    let body = make_settlement_envelope(thread_id);
    let msg = make_peer_message("guard-msg-03", "alice", &body);
    comms.set_queued_messages(vec![msg]);

    manager
        .sync_threads(None)
        .await
        .expect("sync should not error");

    let t = manager.get_thread(thread_id).await.unwrap();
    // Taker is never blocked by maker identity guard — settlement proceeds.
    assert_ne!(
        t.state,
        RemittanceThreadState::Terminated,
        "taker thread should NOT be terminated by maker identity guard; got {:?}",
        t.state
    );
}

// PARITY-07: Inbound IdentityVerificationRequest on unknown thread with makerRequestIdentity set
// => creates thread with my_role=Taker (I am the responder, maker requested).
#[tokio::test]
async fn test_role_inference_identity_request() {
    let comms = Arc::new(MockComms::new());
    let comms_dyn: Arc<dyn bsv::remittance::comms_layer::CommsLayer> = comms.clone();
    let manager = RemittanceManager::new(
        RemittanceManagerConfig {
            message_box: None,
            originator: None,
            logger: None,
            options: Some(RemittanceManagerRuntimeOptions {
                identity_options: Some(IdentityRuntimeOptions {
                    maker_request_identity: Some(IdentityPhase::BeforeSettlement),
                    taker_request_identity: None,
                }),
                ..Default::default()
            }),
            on_event: None,
            state_saver: None,
            state_loader: None,
            now: Some(Box::new(|| 1_000_000u64)),
            thread_id_factory: None,
        },
        Arc::new(MockWallet),
        comms_dyn,
        Some(Arc::new(MockIdentity)),
        vec![Box::new(MockModule)],
    );

    let thread_id = "role-infer-req-01";
    let request = IdentityVerificationRequest {
        kind: RemittanceKind::IdentityVerificationRequest,
        thread_id: thread_id.to_string(),
        request: bsv::remittance::types::IdentityRequest {
            types: HashMap::new(),
            certifiers: vec![],
        },
    };
    let payload = serde_json::to_value(&request).unwrap();
    let env = RemittanceEnvelope {
        v: 1,
        id: "role-env-01".to_string(),
        kind: RemittanceKind::IdentityVerificationRequest,
        thread_id: thread_id.to_string(),
        created_at: 1_000_000,
        payload,
    };
    let body = serde_json::to_string(&env).unwrap();
    let msg = make_peer_message("role-msg-01", "alice", &body);
    comms.set_queued_messages(vec![msg]);

    manager
        .sync_threads(None)
        .await
        .expect("sync should not error");

    let t = manager.get_thread(thread_id).await.unwrap();
    // Maker requested identity, so inbound request means I am the responder/taker.
    assert!(
        matches!(t.my_role, ThreadRole::Taker),
        "my_role should be Taker when makerRequestIdentity is set and inbound is a Request; got {:?}",
        t.my_role
    );
}

// PARITY-07: Inbound IdentityVerificationResponse on unknown thread with makerRequestIdentity set
// => creates thread with my_role=Maker (I requested, they responded).
#[tokio::test]
async fn test_role_inference_identity_response() {
    let comms = Arc::new(MockComms::new());
    let comms_dyn: Arc<dyn bsv::remittance::comms_layer::CommsLayer> = comms.clone();
    let manager = RemittanceManager::new(
        RemittanceManagerConfig {
            message_box: None,
            originator: None,
            logger: None,
            options: Some(RemittanceManagerRuntimeOptions {
                identity_options: Some(IdentityRuntimeOptions {
                    maker_request_identity: Some(IdentityPhase::BeforeSettlement),
                    taker_request_identity: None,
                }),
                ..Default::default()
            }),
            on_event: None,
            state_saver: None,
            state_loader: None,
            now: Some(Box::new(|| 1_000_000u64)),
            thread_id_factory: None,
        },
        Arc::new(MockWallet),
        comms_dyn,
        Some(Arc::new(MockIdentity)),
        vec![Box::new(MockModule)],
    );

    let thread_id = "role-infer-resp-01";
    let response = IdentityVerificationResponse {
        kind: RemittanceKind::IdentityVerificationResponse,
        thread_id: thread_id.to_string(),
        certificates: vec![],
    };
    let payload = serde_json::to_value(&response).unwrap();
    let env = RemittanceEnvelope {
        v: 1,
        id: "role-env-02".to_string(),
        kind: RemittanceKind::IdentityVerificationResponse,
        thread_id: thread_id.to_string(),
        created_at: 1_000_000,
        payload,
    };
    let body = serde_json::to_string(&env).unwrap();
    let msg = make_peer_message("role-msg-02", "alice", &body);
    comms.set_queued_messages(vec![msg]);

    manager
        .sync_threads(None)
        .await
        .expect("sync should not error");

    let t = manager.get_thread(thread_id).await.unwrap();
    // Maker requested identity and I am the maker — inbound response means I am Maker.
    assert!(
        matches!(t.my_role, ThreadRole::Maker),
        "my_role should be Maker when makerRequestIdentity is set and inbound is a Response; got {:?}",
        t.my_role
    );
}

// PARITY-07: Inbound Receipt or Termination on unknown thread defaults to my_role=Taker.
#[tokio::test]
async fn test_role_inference_receipt_termination() {
    let comms = Arc::new(MockComms::new());
    let comms_dyn: Arc<dyn bsv::remittance::comms_layer::CommsLayer> = comms.clone();
    let manager = RemittanceManager::new(
        RemittanceManagerConfig {
            message_box: None,
            originator: None,
            logger: None,
            options: None,
            on_event: None,
            state_saver: None,
            state_loader: None,
            now: Some(Box::new(|| 1_000_000u64)),
            thread_id_factory: None,
        },
        Arc::new(MockWallet),
        comms_dyn,
        Some(Arc::new(MockIdentity)),
        vec![Box::new(MockModule)],
    );

    // Test Termination on unknown thread (Receipt is harder to test without a prior settlement).
    let thread_id = "role-infer-term-01";
    use bsv::remittance::types::Termination;
    let termination = Termination {
        code: "test".to_string(),
        message: "test termination".to_string(),
        details: None,
    };
    let payload = serde_json::to_value(&termination).unwrap();
    let env = RemittanceEnvelope {
        v: 1,
        id: "role-env-03".to_string(),
        kind: RemittanceKind::Termination,
        thread_id: thread_id.to_string(),
        created_at: 1_000_000,
        payload,
    };
    let body = serde_json::to_string(&env).unwrap();
    let msg = make_peer_message("role-msg-03", "alice", &body);
    comms.set_queued_messages(vec![msg]);

    manager
        .sync_threads(None)
        .await
        .expect("sync should not error");

    let t = manager.get_thread(thread_id).await.unwrap();
    // Inbound Termination on unknown thread defaults to Taker.
    assert!(
        matches!(t.my_role, ThreadRole::Taker),
        "my_role should be Taker for inbound Termination on unknown thread; got {:?}",
        t.my_role
    );
}

// PARITY-10: Default options must match TypeScript SDK defaults.
#[tokio::test]
async fn test_runtime_options_defaults() {
    let opts = RemittanceManagerRuntimeOptions::default();
    assert!(
        opts.receipt_provided,
        "receipt_provided should default to true (TS SDK parity)"
    );
    assert_eq!(
        opts.identity_poll_interval_ms, 500,
        "identity_poll_interval_ms should default to 500ms (TS SDK parity)"
    );
}

// PARITY-11: on_event returns a listener ID; remove_event_listener unsubscribes.
#[tokio::test]
async fn test_on_event_unsubscribe() {
    use std::sync::atomic::{AtomicUsize, Ordering};

    let manager = make_manager();

    let call_count = Arc::new(AtomicUsize::new(0));

    // Register a listener that increments a counter on each event.
    let counter = Arc::clone(&call_count);
    let listener_id = manager
        .on_event(Arc::new(move |_event| {
            counter.fetch_add(1, Ordering::SeqCst);
        }))
        .await;

    // Emit an event — listener should fire.
    manager
        .emit_event(RemittanceEvent::ThreadCreated {
            thread_id: "test-unsub".into(),
            thread: sample_thread("test-unsub"),
        })
        .await;
    assert_eq!(
        call_count.load(Ordering::SeqCst),
        1,
        "listener should fire once"
    );

    // Unsubscribe.
    let removed = manager.remove_event_listener(listener_id).await;
    assert!(
        removed,
        "remove_event_listener should return true for a valid ID"
    );

    // Emit another event — listener should NOT fire.
    manager
        .emit_event(RemittanceEvent::ThreadCreated {
            thread_id: "test-unsub-2".into(),
            thread: sample_thread("test-unsub-2"),
        })
        .await;
    assert_eq!(
        call_count.load(Ordering::SeqCst),
        1,
        "listener should not fire after unsubscribe"
    );

    // Removing the same ID again should return false.
    let removed_again = manager.remove_event_listener(listener_id).await;
    assert!(!removed_again, "double-remove should return false");
}

// ---------------------------------------------------------------------------
// TS SDK parity tests — end-to-end narrative, identity before invoicing,
// and module-level termination
// ---------------------------------------------------------------------------

// MockModuleTerminator — build_settlement always returns Terminate.
struct MockModuleTerminator;

#[async_trait]
impl RemittanceModule for MockModuleTerminator {
    type OptionTerms = serde_json::Value;
    type SettlementArtifact = serde_json::Value;
    type ReceiptData = serde_json::Value;

    fn id(&self) -> &str {
        "terminator"
    }
    fn name(&self) -> &str {
        "Terminator Module"
    }
    fn allow_unsolicited_settlements(&self) -> bool {
        false
    }
    fn supports_create_option(&self) -> bool {
        true
    }

    async fn create_option(
        &self,
        _thread_id: &str,
        _invoice: &Invoice,
        _ctx: &ModuleContext,
    ) -> Result<serde_json::Value, RemittanceError> {
        Ok(serde_json::json!({}))
    }

    async fn build_settlement(
        &self,
        _thread_id: &str,
        _invoice: Option<&Invoice>,
        _option: &serde_json::Value,
        _note: Option<&str>,
        _ctx: &ModuleContext,
    ) -> Result<BuildSettlementResult<serde_json::Value>, RemittanceError> {
        Ok(BuildSettlementResult::Terminate {
            termination: bsv::remittance::types::Termination {
                code: "rejected".to_string(),
                message: "No thanks".to_string(),
                details: None,
            },
        })
    }

    async fn accept_settlement(
        &self,
        _thread_id: &str,
        _invoice: Option<&Invoice>,
        _settlement: &serde_json::Value,
        _sender: &str,
        _ctx: &ModuleContext,
    ) -> Result<AcceptSettlementResult<serde_json::Value>, RemittanceError> {
        Ok(AcceptSettlementResult::Accept { receipt_data: None })
    }
}

/// TS SDK parity: "processes an invoice, settlement, and receipt end-to-end"
///
/// Full narrative: maker sends invoice -> taker syncs and receives it ->
/// taker pays -> maker syncs and receives settlement (auto-receipt fires) ->
/// taker syncs and receives receipt.
#[tokio::test]
async fn test_end_to_end_invoice_settlement_receipt() {
    // --- Set up the maker manager (auto_issue_receipt=true) ---
    let maker_comms = Arc::new(MockComms::new());
    let maker_accept_called = Arc::new(AtomicBool::new(false));
    let maker_manager = make_manager_with_receipt_module(
        Arc::clone(&maker_comms),
        Arc::clone(&maker_accept_called),
    );
    maker_manager.init().await.unwrap();

    // --- Set up the taker manager (tracks build_settlement via MockModuleTracked) ---
    let taker_comms = Arc::new(MockComms::new());
    let taker_build_called = Arc::new(AtomicBool::new(false));
    let taker_manager =
        make_manager_with_tracked_module(Arc::clone(&taker_comms), Arc::clone(&taker_build_called));
    taker_manager.init().await.unwrap();

    // --- Step 1: Maker sends invoice ---
    let invoice_handle = maker_manager
        .send_invoice("taker-key", sample_invoice_input(), None)
        .await
        .expect("maker.send_invoice should succeed");

    let thread_id = invoice_handle.handle.thread_id().to_string();

    // Verify maker's thread is Invoiced.
    let maker_thread = maker_manager.get_thread(&thread_id).await.unwrap();
    assert_eq!(maker_thread.state, RemittanceThreadState::Invoiced);
    assert!(maker_thread.invoice.is_some());

    // --- Step 2: Taker syncs and receives the invoice ---
    // Simulate: extract the invoice message sent by maker and queue it for taker.
    let maker_sent = maker_comms.sent.lock().unwrap().clone();
    assert!(
        !maker_sent.is_empty(),
        "maker should have sent at least one message"
    );

    // Find the invoice envelope in maker's sent messages.
    let invoice_body = maker_sent
        .iter()
        .find(|(_, _, body)| {
            serde_json::from_str::<serde_json::Value>(body)
                .ok()
                .and_then(|v| {
                    v.get("kind")
                        .and_then(|k| k.as_str())
                        .map(|s| s.to_string())
                })
                == Some("invoice".to_string())
        })
        .map(|(_, _, body)| body.clone())
        .expect("maker should have sent an invoice message");

    let taker_invoice_msg = make_peer_message("e2e-inv-001", "maker-key", &invoice_body);
    taker_comms.set_queued_messages(vec![taker_invoice_msg]);
    taker_manager
        .sync_threads(None)
        .await
        .expect("taker sync for invoice should succeed");

    // Taker should now have the thread in Invoiced state.
    let taker_thread = taker_manager
        .get_thread(&thread_id)
        .await
        .expect("taker should have the thread after syncing invoice");
    assert_eq!(taker_thread.state, RemittanceThreadState::Invoiced);
    assert!(taker_thread.invoice.is_some());

    // --- Step 3: Taker pays ---
    let pay_handle = taker_manager
        .pay(&thread_id, Some("mock"), None)
        .await
        .expect("taker.pay should succeed");

    let taker_thread = pay_handle.get_thread().await.unwrap();
    assert_eq!(taker_thread.state, RemittanceThreadState::Settled);
    assert!(taker_thread.settlement.is_some());
    assert!(taker_thread.flags.has_paid);

    // --- Step 4: Maker syncs and receives settlement (auto-receipt fires) ---
    let taker_sent = taker_comms.sent.lock().unwrap().clone();
    let settlement_body = taker_sent
        .iter()
        .find(|(_, _, body)| {
            serde_json::from_str::<serde_json::Value>(body)
                .ok()
                .and_then(|v| {
                    v.get("kind")
                        .and_then(|k| k.as_str())
                        .map(|s| s.to_string())
                })
                == Some("settlement".to_string())
        })
        .map(|(_, _, body)| body.clone())
        .expect("taker should have sent a settlement message");

    // Maker needs the thread in correct state to accept settlement.
    // The maker thread from send_invoice is already Invoiced/Maker — perfect.
    let maker_settle_msg = make_peer_message("e2e-settle-001", "taker-key", &settlement_body);
    maker_comms.set_queued_messages(vec![maker_settle_msg]);
    maker_manager
        .sync_threads(None)
        .await
        .expect("maker sync for settlement should succeed");

    // accept_settlement should have been called.
    assert!(
        maker_accept_called.load(Ordering::SeqCst),
        "maker's module.accept_settlement should have been called"
    );

    // Maker should be Receipted (auto_issue_receipt=true).
    let maker_thread = maker_manager.get_thread(&thread_id).await.unwrap();
    assert_eq!(
        maker_thread.state,
        RemittanceThreadState::Receipted,
        "maker should be Receipted after auto-receipt"
    );
    assert!(maker_thread.settlement.is_some());
    assert!(maker_thread.receipt.is_some());

    // --- Step 5: Taker syncs and receives receipt ---
    let maker_sent_after = maker_comms.sent.lock().unwrap().clone();
    let receipt_body = maker_sent_after
        .iter()
        .find(|(_, _, body)| {
            serde_json::from_str::<serde_json::Value>(body)
                .ok()
                .and_then(|v| {
                    v.get("kind")
                        .and_then(|k| k.as_str())
                        .map(|s| s.to_string())
                })
                == Some("receipt".to_string())
        })
        .map(|(_, _, body)| body.clone())
        .expect("maker should have sent a receipt message");

    let taker_receipt_msg = make_peer_message("e2e-rcpt-001", "maker-key", &receipt_body);
    taker_comms.set_queued_messages(vec![taker_receipt_msg]);
    taker_manager
        .sync_threads(None)
        .await
        .expect("taker sync for receipt should succeed");

    let taker_final = taker_manager.get_thread(&thread_id).await.unwrap();
    assert_eq!(
        taker_final.state,
        RemittanceThreadState::Receipted,
        "taker should be Receipted after receiving receipt"
    );
    assert!(
        taker_final.receipt.is_some(),
        "taker should have receipt stored"
    );
}

/// TS SDK parity: "waits for identity verification before invoicing when required"
///
/// Configures makerRequestIdentity=BeforeInvoicing, sends invoice, verifies
/// identity request is sent first and the taker thread gets hasIdentified=true
/// after syncing the identity exchange messages.
#[tokio::test]
async fn test_identity_before_invoicing_full_flow() {
    let maker_comms = Arc::new(MockComms::new());
    let comms_dyn: Arc<dyn bsv::remittance::comms_layer::CommsLayer> = maker_comms.clone();
    let maker_manager = RemittanceManager::new(
        RemittanceManagerConfig {
            message_box: None,
            originator: None,
            logger: None,
            options: Some(RemittanceManagerRuntimeOptions {
                identity_options: Some(IdentityRuntimeOptions {
                    maker_request_identity: Some(IdentityPhase::BeforeInvoicing),
                    taker_request_identity: None,
                }),
                ..Default::default()
            }),
            on_event: None,
            state_saver: None,
            state_loader: None,
            now: Some(Box::new(|| 1_000_000u64)),
            thread_id_factory: None,
        },
        Arc::new(MockWallet),
        comms_dyn,
        Some(Arc::new(MockIdentity)),
        vec![Box::new(MockModuleWithOptions)],
    );
    maker_manager.init().await.unwrap();

    // --- Maker sends invoice (identity exchange happens first internally) ---
    let invoice_handle = maker_manager
        .send_invoice("taker-key", sample_invoice_input(), None)
        .await
        .expect("send_invoice with identity should succeed");

    let thread_id = invoice_handle.handle.thread_id().to_string();

    // Verify at least 2 messages were sent: identity request first, then invoice.
    let sent = maker_comms.sent.lock().unwrap().clone();
    assert!(
        sent.len() >= 2,
        "expected at least 2 messages (identity request + invoice), got {}",
        sent.len()
    );

    // First message should be identityVerificationRequest.
    let first_body: serde_json::Value = serde_json::from_str(&sent[0].2).unwrap();
    assert_eq!(
        first_body.get("kind").and_then(|v| v.as_str()),
        Some("identityVerificationRequest"),
        "first message should be identityVerificationRequest"
    );

    // --- Set up taker manager with same identity config ---
    let taker_comms = Arc::new(MockComms::new());
    let taker_comms_dyn: Arc<dyn bsv::remittance::comms_layer::CommsLayer> = taker_comms.clone();
    let taker_manager = RemittanceManager::new(
        RemittanceManagerConfig {
            message_box: None,
            originator: None,
            logger: None,
            options: Some(RemittanceManagerRuntimeOptions {
                identity_options: Some(IdentityRuntimeOptions {
                    maker_request_identity: Some(IdentityPhase::BeforeInvoicing),
                    taker_request_identity: None,
                }),
                ..Default::default()
            }),
            on_event: None,
            state_saver: None,
            state_loader: None,
            now: Some(Box::new(|| 1_000_000u64)),
            thread_id_factory: None,
        },
        Arc::new(MockWallet),
        taker_comms_dyn,
        Some(Arc::new(MockIdentity)),
        vec![Box::new(MockModuleWithOptions)],
    );
    taker_manager.init().await.unwrap();

    // --- Step 1: Taker syncs maker's messages (identity request + invoice) ---
    // The taker processes the identity request (auto-responds via MockIdentity)
    // and the invoice.
    let taker_msgs: Vec<PeerMessage> = sent
        .iter()
        .enumerate()
        .map(|(i, (_, _, body))| make_peer_message(&format!("id-inv-msg-{}", i), "maker-key", body))
        .collect();
    taker_comms.set_queued_messages(taker_msgs);
    taker_manager
        .sync_threads(None)
        .await
        .expect("taker sync should succeed");

    // Taker should have responded to identity request (IdentityResponded state)
    // and received the invoice. hasIdentified is NOT yet true because the taker
    // has not received the maker's acknowledgment yet.
    let taker_thread = taker_manager
        .get_thread(&thread_id)
        .await
        .expect("taker should have the thread after syncing");
    assert!(
        taker_thread.invoice.is_some(),
        "taker should have received the invoice"
    );

    // Taker should have sent an identity response back.
    let taker_sent = taker_comms.sent.lock().unwrap().clone();
    let response_body = taker_sent
        .iter()
        .find(|(_, _, body)| {
            serde_json::from_str::<serde_json::Value>(body)
                .ok()
                .and_then(|v| {
                    v.get("kind")
                        .and_then(|k| k.as_str())
                        .map(|s| s.to_string())
                })
                == Some("identityVerificationResponse".to_string())
        })
        .map(|(_, _, body)| body.clone())
        .expect("taker should have sent an identityVerificationResponse");

    // --- Step 2: Maker syncs taker's identity response -> sends acknowledgment ---
    let maker_resp_msg = make_peer_message("id-resp-001", "taker-key", &response_body);
    maker_comms.set_queued_messages(vec![maker_resp_msg]);
    maker_manager
        .sync_threads(None)
        .await
        .expect("maker sync for identity response should succeed");

    // Maker should now have has_identified=true.
    let maker_thread = maker_manager.get_thread(&thread_id).await.unwrap();
    assert!(
        maker_thread.flags.has_identified,
        "maker's hasIdentified flag should be true after processing identity response"
    );

    // Maker should have sent an acknowledgment.
    let maker_sent_after = maker_comms.sent.lock().unwrap().clone();
    let ack_body = maker_sent_after
        .iter()
        .find(|(_, _, body)| {
            serde_json::from_str::<serde_json::Value>(body)
                .ok()
                .and_then(|v| {
                    v.get("kind")
                        .and_then(|k| k.as_str())
                        .map(|s| s.to_string())
                })
                == Some("identityVerificationAcknowledgment".to_string())
        })
        .map(|(_, _, body)| body.clone())
        .expect("maker should have sent an identityVerificationAcknowledgment");

    // --- Step 3: Taker syncs maker's acknowledgment -> hasIdentified=true ---
    let taker_ack_msg = make_peer_message("id-ack-001", "maker-key", &ack_body);
    taker_comms.set_queued_messages(vec![taker_ack_msg]);
    taker_manager
        .sync_threads(None)
        .await
        .expect("taker sync for acknowledgment should succeed");

    let taker_final = taker_manager.get_thread(&thread_id).await.unwrap();
    assert!(
        taker_final.flags.has_identified,
        "taker's hasIdentified flag should be true after identity exchange; got {:?}",
        taker_final.flags
    );
    assert!(
        taker_final.invoice.is_some(),
        "taker should still have the invoice"
    );
}

/// TS SDK parity: "sends termination when a module refuses to build a settlement"
///
/// Module's buildSettlement returns { action: 'terminate', termination },
/// verify the thread is terminated and a termination message is sent.
#[tokio::test]
async fn test_module_refuses_settlement_sends_termination() {
    let comms = Arc::new(MockComms::new());
    let comms_dyn: Arc<dyn bsv::remittance::comms_layer::CommsLayer> = comms.clone();
    let manager = RemittanceManager::new(
        RemittanceManagerConfig {
            message_box: None,
            originator: None,
            logger: None,
            options: None,
            on_event: None,
            state_saver: None,
            state_loader: None,
            now: Some(Box::new(|| 1_000_000u64)),
            thread_id_factory: None,
        },
        Arc::new(MockWallet),
        comms_dyn,
        Some(Arc::new(MockIdentity)),
        vec![Box::new(MockModuleTerminator)],
    );
    manager.init().await.unwrap();

    // Insert a taker thread in Invoiced state with the terminator module option.
    let invoice = Invoice {
        kind: RemittanceKind::Invoice,
        expires_at: Some(2_000_000),
        options: {
            let mut map = HashMap::new();
            map.insert("terminator".to_string(), serde_json::json!({}));
            map
        },
        base: InstrumentBase {
            thread_id: "term-test".to_string(),
            payee: "alice".to_string(),
            payer: "bob".to_string(),
            note: None,
            line_items: vec![],
            total: Amount {
                value: "1000".to_string(),
                unit: sat_unit(),
            },
            invoice_number: "INV-TERM".to_string(),
            created_at: 1_000_000,
            arbitrary: None,
        },
    };
    let thread = Thread {
        thread_id: "term-test".to_string(),
        counterparty: "alice".to_string(),
        my_role: ThreadRole::Taker,
        their_role: ThreadRole::Maker,
        created_at: 0,
        updated_at: 0,
        state: RemittanceThreadState::Invoiced,
        state_log: vec![],
        processed_message_ids: vec![],
        protocol_log: vec![],
        identity: ThreadIdentity::default(),
        flags: ThreadFlags {
            has_invoiced: true,
            ..Default::default()
        },
        invoice: Some(invoice),
        settlement: None,
        receipt: None,
        termination: None,
        last_error: None,
    };
    manager.insert_thread(thread).await;

    // Pay with the terminator module — should terminate instead of settling.
    let handle = manager
        .pay("term-test", Some("terminator"), None)
        .await
        .expect("pay should succeed even when module terminates");

    let thread = handle.get_thread().await.unwrap();
    assert_eq!(
        thread.state,
        RemittanceThreadState::Terminated,
        "thread should be Terminated when module refuses settlement; got {:?}",
        thread.state
    );
    assert!(
        thread.termination.is_some(),
        "termination should be stored on thread"
    );

    // Verify the termination details match what the module returned.
    let termination = thread.termination.as_ref().unwrap();
    assert_eq!(termination.code, "rejected");
    assert_eq!(termination.message, "No thanks");

    // Verify a termination message was sent to the counterparty.
    let sent = comms.sent.lock().unwrap().clone();
    let term_sent = sent.iter().any(|(_, _, body)| {
        if let Ok(v) = serde_json::from_str::<serde_json::Value>(body) {
            v.get("kind").and_then(|k| k.as_str()) == Some("termination")
        } else {
            false
        }
    });
    assert!(
        term_sent,
        "a termination message should have been sent to the counterparty"
    );
}