payrix 0.3.0

Rust client for the Payrix payment processing API
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
//! Merchant onboarding workflow for Payrix.
//!
//! This module provides a high-level interface for onboarding merchants to Payrix.
//! It encapsulates the complex nested API structure into user-friendly types and
//! handles the conversion to the Payrix API format internally.
//!
//! # Documentation Sources
//!
//! This implementation is based on the following Payrix/Worldpay documentation:
//!
//! - [Worldpay Developer Hub - Payrix Pro](https://docs.worldpay.com/apis/payrix) -
//!   Primary API documentation
//! - [Merchant Boarding via API](https://resource.payrix.com/resources/merchant-boarding-via-api) -
//!   API boarding process and JSON structure
//! - [New Merchant Boarding Flow](https://resource.payrix.com/docs/new-merchant-boarding-flow) -
//!   Boarding status flow and underwriting process
//! - [Required Merchant Onboarding API Fields](https://payrix.atlassian.net/wiki/spaces/PRC/pages/826081337) -
//!   Field requirements for /entities, /merchants, /members, /accounts endpoints
//! - [Payrix Pro API Documentation](https://resource.payrix.com/resources/api-how-to-add-a-new-merchant) -
//!   How to add a new merchant via API
//! - [Merchant Boarding: API - Canada](https://resource.payrix.com/resources/merchant-boarding-api-payrix-canada) -
//!   Example JSON payloads for merchant boarding
//!
//! # Overview
//!
//! Merchant onboarding in Payrix requires submitting business information, bank accounts,
//! and beneficial owner details in a specific nested JSON format. This module simplifies
//! that process by providing:
//!
//! - **User-friendly request types** that clearly define required and optional fields
//! - **Automatic conversion** to Payrix's nested JSON structure
//! - **Status tracking** to monitor the boarding process
//!
//! # Workflow Steps
//!
//! 1. Create an [`OnboardMerchantRequest`] with all required information
//! 2. Call [`onboard_merchant()`] to submit the application
//! 3. Check the result's `boarding_status` for immediate approval or pending review
//! 4. Use [`check_boarding_status()`] to poll for status updates if needed
//!
//! # Boarding Status Flow
//!
//! After submission, a merchant can be in one of these states:
//!
//! | Status | Description |
//! |--------|-------------|
//! | `Boarded` | Approved and ready to process payments |
//! | `Pending` | Under automated review (typically resolves within 30 seconds) |
//! | `ManualReview` | Requires manual underwriting review |
//! | `Incomplete` | Missing required information |
//!
//! # Example
//!
//! ```no_run
//! use payrix::{PayrixClient, Environment};
//! use payrix::workflows::merchant_onboarding::*;
//! use payrix::types::{MerchantType, MerchantEnvironment, MemberType, AccountHolderType, AccountType, DateYmd};
//!
//! # async fn example() -> payrix::Result<()> {
//! let client = PayrixClient::new("api-key", Environment::Test)?;
//!
//! let request = OnboardMerchantRequest {
//!     business: BusinessInfo {
//!         business_type: MerchantType::LimitedLiabilityCorporation,
//!         legal_name: "Payrix Rust LLC".to_string(),
//!         address: Address {
//!             line1: "123 Main Street".to_string(),
//!             line2: Some("Suite 100".to_string()),
//!             city: "Springfield".to_string(),
//!             state: "IL".to_string(),
//!             zip: "62701".to_string(),
//!             country: "USA".to_string(),
//!         },
//!         phone: "5551234567".to_string(),
//!         email: "payrixrust@gmail.com".to_string(),
//!         website: Some("https://github.com/outlawpractice/payrix-rs".to_string()),
//!         ein: "123456789".to_string(),
//!     },
//!     merchant: MerchantConfig {
//!         dba: "Payrix Rust LLC".to_string(),
//!         mcc: "8111".to_string(),
//!         environment: MerchantEnvironment::Ecommerce,
//!         annual_cc_sales: 50000000,  // $500,000.00 in cents
//!         avg_ticket: 5000,           // $50.00 in cents
//!         established: DateYmd::new("20200101").unwrap(),
//!         is_new_business: false,
//!     },
//!     accounts: vec![
//!         // Primary operating account - accepts deposits and fee withdrawals
//!         BankAccountInfo {
//!             name: Some("Operating Account".to_string()),
//!             routing_number: Some("123456789".to_string()),
//!             account_number: Some("987654321".to_string()),
//!             holder_type: AccountHolderType::Business,
//!             account_method: BankAccountMethod::Checking,
//!             transaction_type: AccountType::All, // Merchant account
//!             currency: Some("USD".to_string()),
//!             is_primary: true,
//!             plaid_public_token: None,
//!         },
//!         // Trust account - deposits only (no fee withdrawals)
//!         BankAccountInfo {
//!             name: Some("Trust Account".to_string()),
//!             routing_number: Some("123456789".to_string()),
//!             account_number: Some("987654322".to_string()),
//!             holder_type: AccountHolderType::Business,
//!             account_method: BankAccountMethod::Checking,
//!             transaction_type: AccountType::Credit,  // Trust account - deposits only
//!             currency: Some("USD".to_string()),
//!             is_primary: false,
//!             plaid_public_token: None,
//!         },
//!     ],
//!     members: vec![MemberInfo {
//!         member_type: MemberType::Owner,
//!         first_name: "John".to_string(),
//!         last_name: "Doe".to_string(),
//!         title: Some("CEO".to_string()),
//!         ownership_percentage: 100,
//!         date_of_birth: "19800115".to_string(),  // YYYYMMDD format
//!         ssn: "123456789".to_string(),
//!         email: "john@acme.com".to_string(),
//!         phone: "5559876543".to_string(),
//!         address: Address {
//!             line1: "456 Oak Avenue".to_string(),
//!             line2: None,
//!             city: "Springfield".to_string(),
//!             state: "IL".to_string(),
//!             zip: "62702".to_string(),
//!             country: "USA".to_string(),
//!         },
//!     }],
//!     terms_acceptance: TermsAcceptance {
//!         version: "4.21".to_string(),
//!         accepted_at: "2024-01-15 10:30:00".to_string(),
//!     },
//! };
//!
//! let result = onboard_merchant(&client, request).await?;
//!
//! match result.boarding_status {
//!     BoardingStatus::Boarded => {
//!         println!("Merchant approved! ID: {}", result.merchant_id);
//!     }
//!     BoardingStatus::Pending => {
//!         println!("Application pending review...");
//!         // Poll for updates
//!         let status = check_boarding_status(&client, &result.merchant_id).await?;
//!         println!("Current status: {:?}", status.status);
//!     }
//!     BoardingStatus::ManualReview => {
//!         println!("Requires manual review");
//!     }
//!     _ => {
//!         println!("Status: {:?}", result.boarding_status);
//!     }
//! }
//! # Ok(())
//! # }
//! ```
//!
//! # Required Fields
//!
//! The following information is required for merchant onboarding:
//!
//! **Business Information:**
//! - Legal business name
//! - Business type (LLC, Corporation, etc.)
//! - Complete address
//! - Phone and email
//! - EIN (Tax ID)
//!
//! **Merchant Configuration:**
//! - DBA (Doing Business As) name
//! - MCC (Merchant Category Code)
//! - Processing environment
//! - Expected annual sales and average ticket
//! - Date established
//!
//! **Bank Account:**
//! - At least one bank account with routing and account numbers
//!
//! **Beneficial Owners:**
//! - At least one owner/control person with personal details
//! - SSN and date of birth for identity verification
//! - Ownership percentage (must total 100% for all owners)
//!
//! **Terms Acceptance:**
//! - Version of terms accepted
//! - Timestamp of acceptance

use serde::{Deserialize, Serialize};

use crate::client::PayrixClient;
use crate::entity::EntityType;
use crate::error::Result;
use crate::types::{
    Account, AccountHolderType, AccountType, DateYmd, Entity, Member, MemberType, Merchant,
    MerchantEnvironment, MerchantStatus, MerchantType,
};

// ============================================================================
// Public Request Types
// ============================================================================

/// Complete request for onboarding a new merchant.
///
/// This structure contains all the information required to onboard a merchant
/// to Payrix. The workflow will convert these user-friendly types to the
/// Payrix API's nested JSON format internally.
///
/// # Required Components
///
/// - `business` - Legal business entity information
/// - `merchant` - Merchant processing configuration
/// - `accounts` - At least one bank account for funding
/// - `members` - Beneficial owners/control persons
/// - `terms_acceptance` - Acknowledgment of terms and conditions
#[derive(Debug, Clone)]
pub struct OnboardMerchantRequest {
    /// Business entity information (legal name, address, tax ID)
    pub business: BusinessInfo,

    /// Merchant processing configuration (DBA, MCC, volumes)
    pub merchant: MerchantConfig,

    /// Bank accounts for funding (at least one required)
    pub accounts: Vec<BankAccountInfo>,

    /// Beneficial owners and control persons (at least one required)
    pub members: Vec<MemberInfo>,

    /// Terms and conditions acceptance record
    pub terms_acceptance: TermsAcceptance,
}

/// Business entity information.
///
/// Contains the legal details about the business being onboarded,
/// including business structure, address, and tax identification.
#[derive(Debug, Clone)]
pub struct BusinessInfo {
    /// Business structure type (LLC, Corporation, Sole Proprietor, etc.)
    ///
    /// This determines the legal structure of the business and affects
    /// compliance requirements.
    pub business_type: MerchantType,

    /// Legal business name as registered with the state.
    ///
    /// This should match the name on file with the IRS and state registration.
    pub legal_name: String,

    /// Business address.
    ///
    /// This should be the primary business location, not a P.O. Box.
    pub address: Address,

    /// Business phone number (digits only, no formatting).
    ///
    /// Example: "5551234567"
    pub phone: String,

    /// Business email address.
    ///
    /// This will be used for business communications from Payrix.
    pub email: String,

    /// Business website URL (optional).
    ///
    /// Include the full URL with protocol (e.g., "<https://www.example.com>").
    pub website: Option<String>,

    /// Employer Identification Number (EIN) / Tax ID.
    ///
    /// 9-digit federal tax identification number, no dashes or spaces.
    /// Example: "123456789"
    pub ein: String,
}

/// Merchant processing configuration.
///
/// Contains information about how the merchant will process payments,
/// including expected volumes and business category.
#[derive(Debug, Clone)]
pub struct MerchantConfig {
    /// "Doing Business As" name.
    ///
    /// The public-facing name customers see on their statements.
    /// May be different from the legal business name.
    pub dba: String,

    /// Merchant Category Code (MCC).
    ///
    /// A 4-digit code that classifies the type of business.
    /// Examples:
    /// - "5812" - Restaurants
    /// - "5999" - Miscellaneous retail
    /// - "8111" - Legal services
    pub mcc: String,

    /// Processing environment.
    ///
    /// Indicates how transactions will primarily be processed.
    pub environment: MerchantEnvironment,

    /// Expected annual credit card sales volume in cents.
    ///
    /// Example: 50000000 = $500,000.00 per year
    pub annual_cc_sales: i64,

    /// Average transaction amount in cents.
    ///
    /// Example: 5000 = $50.00 average ticket
    pub avg_ticket: i64,

    /// Date the business was established (YYYYMMDD format).
    ///
    /// Use `DateYmd::new("20200101")` for January 1, 2020.
    pub established: DateYmd,

    /// Whether this is a new business (less than 2 years old).
    pub is_new_business: bool,
}

/// Bank account method (checking or savings).
///
/// Combined with `AccountHolderType` to determine the Payrix API method value:
/// - Individual + Checking = 8
/// - Individual + Savings = 9
/// - Business + Checking = 10
/// - Business + Savings = 11
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum BankAccountMethod {
    /// Checking account (default)
    #[default]
    Checking,
    /// Savings account
    Savings,
}

/// Bank account information for funding.
///
/// At least one bank account is required for merchant onboarding.
/// Accounts can be configured for different purposes:
///
/// - **Deposits only** (`transaction_type: Credit`) - e.g., a trust account that can only receive funds
/// - **Withdrawals only** (`transaction_type: Debit`) - for fee debits only
/// - **Both** (`transaction_type: All`) - standard merchant account for deposits and fee withdrawals
///
/// # Multiple Account Scenarios
///
/// A common configuration is two accounts:
/// 1. A trust account (Credit only) for receiving customer payments
/// 2. A merchant operating account (All) for deposits and fee withdrawals
///
/// # Plaid Integration
///
/// For instant account verification via Plaid, provide the `plaid_public_token`
/// instead of routing/account numbers. The Payrix API will retrieve the bank
/// details from Plaid.
#[derive(Clone)]
pub struct BankAccountInfo {
    /// Account name/label (optional).
    ///
    /// A descriptive name for the account, e.g., "Operating Account" or "Trust Account".
    pub name: Option<String>,

    /// Bank routing number (ABA number).
    ///
    /// 9-digit routing number, no dashes or spaces.
    /// Example: "123456789"
    ///
    /// Not required if using Plaid (`plaid_public_token` is provided).
    pub routing_number: Option<String>,

    /// Bank account number.
    ///
    /// The full account number, no dashes or spaces.
    ///
    /// Not required if using Plaid (`plaid_public_token` is provided).
    pub account_number: Option<String>,

    /// Account holder type.
    ///
    /// Whether this is a personal or business account.
    pub holder_type: AccountHolderType,

    /// Bank account method.
    ///
    /// Whether this is a checking or savings account.
    /// Defaults to `Checking` if not specified.
    pub account_method: BankAccountMethod,

    /// Transaction type this account supports.
    ///
    /// - `Credit` - Deposits/credits only (e.g., trust account)
    /// - `Debit` - Withdrawals/debits only (e.g., fee account)
    /// - `All` - Both deposits and withdrawals (standard merchant account)
    ///
    /// Defaults to `All` if not specified.
    pub transaction_type: AccountType,

    /// Currency code.
    ///
    /// ISO 4217 currency code, e.g., "USD", "CAD".
    /// Defaults to "USD" if not specified.
    pub currency: Option<String>,

    /// Whether this is the primary account.
    ///
    /// At least one account must be marked as primary.
    /// The primary account is used for standard deposits and fee withdrawals.
    pub is_primary: bool,

    /// Plaid public token for instant account verification.
    ///
    /// If provided, the Payrix API will retrieve bank details from Plaid,
    /// and `routing_number`/`account_number` are not required.
    ///
    /// Obtain this token from Plaid Link in your frontend application.
    pub plaid_public_token: Option<String>,
}

/// Beneficial owner or control person information.
///
/// KYC/AML regulations require collecting information about individuals
/// who own or control the business. At least one member is required.
///
/// # Member Types
///
/// - `Owner` - Individual with 25% or more ownership
/// - `ControlPerson` - Individual with significant control (e.g., CEO, CFO)
/// - `Principal` - Other key individual
#[derive(Clone)]
pub struct MemberInfo {
    /// Type of member relationship.
    pub member_type: MemberType,

    /// First name.
    pub first_name: String,

    /// Last name.
    pub last_name: String,

    /// Title or position (optional).
    ///
    /// Example: "CEO", "Owner", "CFO"
    pub title: Option<String>,

    /// Ownership percentage (0-100).
    ///
    /// Sum of all owners should equal 100.
    pub ownership_percentage: i32,

    /// Date of birth in YYYYMMDD format.
    ///
    /// Required for identity verification.
    /// Example: "19800115" for January 15, 1980.
    ///
    /// Note: This is a String rather than DateYmd because dates of birth
    /// typically predate the year 2000, which is outside DateYmd's valid range.
    pub date_of_birth: String,

    /// Social Security Number.
    ///
    /// Full 9-digit SSN, no dashes or spaces. Required for identity verification.
    /// Example: "123456789"
    ///
    /// **Security Note:** This field is transmitted securely and stored encrypted.
    pub ssn: String,

    /// Email address.
    pub email: String,

    /// Phone number (digits only).
    pub phone: String,

    /// Home address.
    ///
    /// Must be a residential address, not a business address.
    pub address: Address,
}

/// Physical address.
///
/// Used for both business and residential addresses.
#[derive(Debug, Clone)]
pub struct Address {
    /// Street address line 1.
    pub line1: String,

    /// Street address line 2 (optional).
    ///
    /// Apartment, suite, unit, etc.
    pub line2: Option<String>,

    /// City.
    pub city: String,

    /// State or province code.
    ///
    /// Use 2-letter state codes for US (e.g., "CA", "NY", "TX").
    pub state: String,

    /// ZIP or postal code.
    pub zip: String,

    /// Country code.
    ///
    /// Use "USA" for United States, "CAN" for Canada.
    pub country: String,
}

/// Terms and conditions acceptance record.
///
/// Documents when and what version of the terms were accepted.
/// This is required for compliance and legal purposes.
#[derive(Debug, Clone)]
pub struct TermsAcceptance {
    /// Version of terms and conditions accepted.
    ///
    /// Example: "4.21"
    pub version: String,

    /// Timestamp when terms were accepted.
    ///
    /// Format: "YYYY-MM-DD HH:mm:ss"
    /// Example: "2024-01-15 10:30:00"
    pub accepted_at: String,
}

// ============================================================================
// Public Response Types
// ============================================================================

/// Result of merchant onboarding operation.
///
/// Contains the created resources and current boarding status.
#[derive(Debug, Clone)]
pub struct OnboardMerchantResult {
    /// The created entity ID.
    ///
    /// This is the parent business entity in Payrix.
    pub entity_id: String,

    /// The created merchant ID.
    ///
    /// Use this ID for subsequent operations and status checks.
    pub merchant_id: String,

    /// Current boarding status.
    ///
    /// Check this to determine if the merchant was approved immediately
    /// or requires further review.
    pub boarding_status: BoardingStatus,

    /// The full entity response from Payrix.
    pub entity: Entity,

    /// The full merchant response from Payrix.
    pub merchant: Merchant,

    /// Created bank accounts.
    pub accounts: Vec<Account>,

    /// Created beneficial owners/members.
    pub members: Vec<Member>,
}

/// Boarding status for merchant applications.
///
/// This is a user-friendly enum that maps to the underlying Payrix
/// merchant status values relevant to onboarding.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BoardingStatus {
    /// Not ready for boarding (internal state).
    ///
    /// The merchant has not yet been submitted for underwriting.
    NotReady,

    /// Submitted for boarding.
    ///
    /// The application has been submitted and underwriting has been triggered.
    /// This typically transitions quickly to another state.
    Submitted,

    /// Successfully boarded and approved.
    ///
    /// The merchant is approved to process payments.
    Boarded,

    /// Requires manual underwriting review.
    ///
    /// Additional documentation or review is needed before approval.
    ManualReview,

    /// Account has been closed.
    Closed,

    /// Application is incomplete.
    ///
    /// Missing required information that must be provided.
    Incomplete,

    /// Pending automated review.
    ///
    /// The application is being reviewed by automated systems.
    /// Typically resolves within 30 seconds.
    Pending,
}

impl From<MerchantStatus> for BoardingStatus {
    fn from(status: MerchantStatus) -> Self {
        match status {
            MerchantStatus::NotReady => BoardingStatus::NotReady,
            MerchantStatus::Ready => BoardingStatus::Submitted,
            MerchantStatus::Boarded => BoardingStatus::Boarded,
            MerchantStatus::Manual => BoardingStatus::ManualReview,
            MerchantStatus::Closed => BoardingStatus::Closed,
            MerchantStatus::Incomplete => BoardingStatus::Incomplete,
            MerchantStatus::Pending => BoardingStatus::Pending,
        }
    }
}

impl std::fmt::Display for BoardingStatus {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            BoardingStatus::NotReady => write!(f, "Not Ready"),
            BoardingStatus::Submitted => write!(f, "Submitted"),
            BoardingStatus::Boarded => write!(f, "Boarded"),
            BoardingStatus::ManualReview => write!(f, "Manual Review"),
            BoardingStatus::Closed => write!(f, "Closed"),
            BoardingStatus::Incomplete => write!(f, "Incomplete"),
            BoardingStatus::Pending => write!(f, "Pending"),
        }
    }
}

/// Result of checking boarding status.
///
/// Contains the current status and related information.
#[derive(Debug, Clone)]
pub struct BoardingStatusResult {
    /// Current boarding status.
    pub status: BoardingStatus,

    /// Merchant ID.
    pub merchant_id: String,

    /// Entity ID (parent business).
    pub entity_id: String,

    /// Date boarded (if approved).
    ///
    /// Format: YYYYMMDD
    pub boarded_date: Option<String>,
}

// ============================================================================
// Internal Types for Payrix API Serialization
// ============================================================================

/// Internal payload structure matching Payrix's nested JSON format.
///
/// This is not exposed publicly - users work with the friendly request types
/// which are converted to this format internally.
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
struct PayrixOnboardingPayload {
    /// Business type (0=SoleProprietor, 1=Corp, 2=LLC, etc.)
    #[serde(rename = "type")]
    entity_type: MerchantType,

    /// Legal business name
    name: String,

    /// Street address line 1
    address1: String,

    /// Street address line 2 (optional)
    #[serde(skip_serializing_if = "Option::is_none")]
    address2: Option<String>,

    /// City
    city: String,

    /// State/province code
    state: String,

    /// ZIP/postal code
    zip: String,

    /// Country code
    country: String,

    /// Phone number
    phone: String,

    /// Email address
    email: String,

    /// Website URL (optional)
    #[serde(skip_serializing_if = "Option::is_none")]
    website: Option<String>,

    /// EIN (Tax ID)
    ein: String,

    /// Terms & Conditions version
    tc_version: String,

    /// Terms & Conditions acceptance timestamp
    tc_date: String,

    /// Terms & Conditions attestation (1 = accepted)
    tc_attestation: i32,

    /// Nested bank accounts
    accounts: Vec<PayrixAccountPayload>,

    /// Nested merchant configuration
    merchant: PayrixMerchantPayload,
}

/// Internal bank account payload for Payrix API.
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
struct PayrixAccountPayload {
    /// Whether this is the primary account (1 = yes, 0 = no)
    primary: i32,

    /// Account name/label
    #[serde(skip_serializing_if = "Option::is_none")]
    name: Option<String>,

    /// Transaction type (credit, debit, or all)
    #[serde(rename = "type")]
    transaction_type: AccountType,

    /// Currency code (e.g., "USD")
    #[serde(skip_serializing_if = "Option::is_none")]
    currency: Option<String>,

    /// Nested account details (for manual entry)
    #[serde(skip_serializing_if = "Option::is_none")]
    account: Option<PayrixAccountDetails>,

    /// Plaid public token for instant verification
    #[serde(skip_serializing_if = "Option::is_none")]
    public_token: Option<String>,
}

/// Internal account details for Payrix API.
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct PayrixAccountDetails {
    /// Account method/type (8 = checking)
    method: i32,

    /// Bank account number
    number: String,

    /// Bank routing number
    routing: String,

    /// Account holder type (1 = individual, 2 = business)
    holder_type: AccountHolderType,
}

/// Internal merchant payload for Payrix API.
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
struct PayrixMerchantPayload {
    /// DBA name
    dba: String,

    /// Is new business (0 = no, 1 = yes)
    new: i32,

    /// Merchant Category Code
    mcc: String,

    /// Boarding status (1 = Board Immediately)
    status: i32,

    /// Processing environment
    environment: MerchantEnvironment,

    /// Annual credit card sales in cents
    annual_cc_sales: i64,

    /// Average ticket in cents
    avg_ticket: i64,

    /// Date established (YYYYMMDD)
    established: String,

    /// Nested members (owners/principals)
    members: Vec<PayrixMemberPayload>,
}

/// Internal member payload for Payrix API.
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct PayrixMemberPayload {
    /// Member type (1=Owner, 2=ControlPerson, 3=Principal)
    #[serde(rename = "type")]
    member_type: MemberType,

    /// First name
    first: String,

    /// Last name
    last: String,

    /// Title (optional)
    #[serde(skip_serializing_if = "Option::is_none")]
    title: Option<String>,

    /// Ownership percentage
    ownership: i32,

    /// Date of birth (YYYYMMDD)
    dob: String,

    /// SSN
    ssn: String,

    /// Email
    email: String,

    /// Phone
    phone: String,

    /// Address line 1
    address1: String,

    /// Address line 2 (optional)
    #[serde(skip_serializing_if = "Option::is_none")]
    address2: Option<String>,

    /// City
    city: String,

    /// State
    state: String,

    /// ZIP
    zip: String,

    /// Country
    country: String,
}

// ============================================================================
// Custom Debug Implementations (mask sensitive data)
// ============================================================================

/// Helper to mask sensitive strings, showing only last 4 characters.
fn mask_sensitive(value: &str) -> String {
    if value.len() <= 4 {
        "*".repeat(value.len())
    } else {
        format!("{}{}", "*".repeat(value.len() - 4), &value[value.len() - 4..])
    }
}

impl std::fmt::Debug for BankAccountInfo {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("BankAccountInfo")
            .field("name", &self.name)
            .field("routing_number", &self.routing_number.as_ref().map(|s| mask_sensitive(s)))
            .field("account_number", &self.account_number.as_ref().map(|s| mask_sensitive(s)))
            .field("holder_type", &self.holder_type)
            .field("account_method", &self.account_method)
            .field("transaction_type", &self.transaction_type)
            .field("currency", &self.currency)
            .field("is_primary", &self.is_primary)
            .field("plaid_public_token", &self.plaid_public_token.as_ref().map(|_| "[REDACTED]"))
            .finish()
    }
}

impl std::fmt::Debug for MemberInfo {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("MemberInfo")
            .field("member_type", &self.member_type)
            .field("first_name", &self.first_name)
            .field("last_name", &self.last_name)
            .field("title", &self.title)
            .field("ownership_percentage", &self.ownership_percentage)
            .field("date_of_birth", &self.date_of_birth)
            .field("ssn", &mask_sensitive(&self.ssn))
            .field("email", &self.email)
            .field("phone", &self.phone)
            .field("address", &self.address)
            .finish()
    }
}

impl std::fmt::Debug for PayrixAccountDetails {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("PayrixAccountDetails")
            .field("method", &self.method)
            .field("number", &mask_sensitive(&self.number))
            .field("routing", &mask_sensitive(&self.routing))
            .field("holder_type", &self.holder_type)
            .finish()
    }
}

impl std::fmt::Debug for PayrixMemberPayload {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("PayrixMemberPayload")
            .field("member_type", &self.member_type)
            .field("first", &self.first)
            .field("last", &self.last)
            .field("title", &self.title)
            .field("ownership", &self.ownership)
            .field("dob", &self.dob)
            .field("ssn", &mask_sensitive(&self.ssn))
            .field("email", &self.email)
            .field("phone", &self.phone)
            .field("address1", &self.address1)
            .field("address2", &self.address2)
            .field("city", &self.city)
            .field("state", &self.state)
            .field("zip", &self.zip)
            .field("country", &self.country)
            .finish()
    }
}

// ============================================================================
// Type Conversions
// ============================================================================

impl From<OnboardMerchantRequest> for PayrixOnboardingPayload {
    fn from(request: OnboardMerchantRequest) -> Self {
        PayrixOnboardingPayload {
            entity_type: request.business.business_type,
            name: request.business.legal_name,
            address1: request.business.address.line1,
            address2: request.business.address.line2,
            city: request.business.address.city,
            state: request.business.address.state,
            zip: request.business.address.zip,
            country: request.business.address.country,
            phone: request.business.phone,
            email: request.business.email,
            website: request.business.website,
            ein: request.business.ein,
            tc_version: request.terms_acceptance.version,
            tc_date: request.terms_acceptance.accepted_at,
            tc_attestation: 1,
            accounts: request.accounts.into_iter().map(|a| a.into()).collect(),
            merchant: PayrixMerchantPayload {
                dba: request.merchant.dba,
                new: if request.merchant.is_new_business { 1 } else { 0 },
                mcc: request.merchant.mcc,
                status: 1, // Board Immediately
                environment: request.merchant.environment,
                annual_cc_sales: request.merchant.annual_cc_sales,
                avg_ticket: request.merchant.avg_ticket,
                established: request.merchant.established.as_str().to_string(),
                members: request.members.into_iter().map(|m| m.into()).collect(),
            },
        }
    }
}

impl From<BankAccountInfo> for PayrixAccountPayload {
    fn from(account: BankAccountInfo) -> Self {
        // Build account details if routing/account numbers are provided (manual entry)
        let account_details = match (&account.routing_number, &account.account_number) {
            (Some(routing), Some(number)) => {
                // Calculate method based on holder type and account method:
                // Individual + Checking = 8, Individual + Savings = 9
                // Business + Checking = 10, Business + Savings = 11
                let method = match (account.holder_type, account.account_method) {
                    (AccountHolderType::Individual, BankAccountMethod::Checking) => 8,
                    (AccountHolderType::Individual, BankAccountMethod::Savings) => 9,
                    (AccountHolderType::Business, BankAccountMethod::Checking) => 10,
                    (AccountHolderType::Business, BankAccountMethod::Savings) => 11,
                };
                Some(PayrixAccountDetails {
                    method,
                    number: number.clone(),
                    routing: routing.clone(),
                    holder_type: account.holder_type,
                })
            }
            _ => None,
        };

        PayrixAccountPayload {
            primary: if account.is_primary { 1 } else { 0 },
            name: account.name,
            transaction_type: account.transaction_type,
            currency: account.currency,
            account: account_details,
            public_token: account.plaid_public_token,
        }
    }
}

impl From<MemberInfo> for PayrixMemberPayload {
    fn from(member: MemberInfo) -> Self {
        PayrixMemberPayload {
            member_type: member.member_type,
            first: member.first_name,
            last: member.last_name,
            title: member.title,
            ownership: member.ownership_percentage,
            dob: member.date_of_birth,
            ssn: member.ssn,
            email: member.email,
            phone: member.phone,
            address1: member.address.line1,
            address2: member.address.line2,
            city: member.address.city,
            state: member.address.state,
            zip: member.address.zip,
            country: member.address.country,
        }
    }
}

// ============================================================================
// Response Parsing Types
// ============================================================================

/// Internal response structure for parsing Payrix's nested response.
///
/// Some fields are included for completeness when parsing the full API response,
/// even if not all are used in the current implementation.
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
#[allow(dead_code)]
struct PayrixOnboardingResponse {
    /// Entity ID
    id: String,

    /// Nested merchant in response
    #[serde(default)]
    merchant: Option<MerchantInResponse>,
    // Note: Accounts are not included here because the API returns them with
    // nested objects (expanded entity) rather than just IDs. We fetch accounts
    // separately after creation.
}

/// Internal merchant response structure.
///
/// Some fields are included for completeness when parsing the full API response,
/// even if not all are used in the current implementation.
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
#[allow(dead_code)]
struct MerchantInResponse {
    /// Merchant ID
    id: String,

    /// Merchant status
    #[serde(default)]
    status: Option<MerchantStatus>,

    /// Entity ID
    #[serde(default)]
    entity: Option<String>,

    /// Boarded date
    #[serde(default)]
    boarded: Option<String>,

    /// Members in response
    #[serde(default)]
    members: Option<Vec<Member>>,
}

// ============================================================================
// Validation
// ============================================================================

/// Validates an onboarding request before sending to the API.
///
/// This catches common errors early with clear error messages, rather than
/// waiting for cryptic API responses.
fn validate_request(request: &OnboardMerchantRequest) -> Result<()> {
    // Validate accounts
    if request.accounts.is_empty() {
        return Err(crate::error::Error::Config(
            "At least one bank account is required".into(),
        ));
    }

    if !request.accounts.iter().any(|a| a.is_primary) {
        return Err(crate::error::Error::Config(
            "One account must be marked as primary".into(),
        ));
    }

    // Validate each account has either routing/account numbers OR Plaid token
    for (i, account) in request.accounts.iter().enumerate() {
        let has_manual = account.routing_number.is_some() && account.account_number.is_some();
        let has_plaid = account.plaid_public_token.is_some();

        if !has_manual && !has_plaid {
            return Err(crate::error::Error::Config(format!(
                "Account {} requires either routing/account numbers or a Plaid token",
                i + 1
            )));
        }

        // Validate routing number format (9 digits)
        if let Some(ref routing) = account.routing_number {
            if routing.len() != 9 || !routing.chars().all(|c| c.is_ascii_digit()) {
                return Err(crate::error::Error::Config(format!(
                    "Account {} routing number must be exactly 9 digits",
                    i + 1
                )));
            }
        }
    }

    // Validate members
    if request.members.is_empty() {
        return Err(crate::error::Error::Config(
            "At least one member (owner or control person) is required".into(),
        ));
    }

    // Validate SSN format for each member (9 digits)
    for (i, member) in request.members.iter().enumerate() {
        if member.ssn.len() != 9 || !member.ssn.chars().all(|c| c.is_ascii_digit()) {
            return Err(crate::error::Error::Config(format!(
                "Member {} SSN must be exactly 9 digits (no dashes)",
                i + 1
            )));
        }

        // Validate date of birth format (YYYYMMDD, 8 digits)
        if member.date_of_birth.len() != 8
            || !member.date_of_birth.chars().all(|c| c.is_ascii_digit())
        {
            return Err(crate::error::Error::Config(format!(
                "Member {} date of birth must be in YYYYMMDD format (8 digits)",
                i + 1
            )));
        }

        // Validate ownership percentage is reasonable
        if member.ownership_percentage < 0 || member.ownership_percentage > 100 {
            return Err(crate::error::Error::Config(format!(
                "Member {} ownership percentage must be between 0 and 100",
                i + 1
            )));
        }
    }

    // Validate EIN format (9 digits)
    if request.business.ein.len() != 9
        || !request.business.ein.chars().all(|c| c.is_ascii_digit())
    {
        return Err(crate::error::Error::Config(
            "EIN must be exactly 9 digits (no dashes)".into(),
        ));
    }

    Ok(())
}

// ============================================================================
// Workflow Functions
// ============================================================================

/// Onboard a new merchant to Payrix.
///
/// This high-level workflow handles the complete merchant onboarding process:
///
/// 1. **Creates the business entity** with address and tax information
/// 2. **Creates the merchant account** with processing configuration
/// 3. **Adds bank accounts** for funding
/// 4. **Registers beneficial owners** for compliance
/// 5. **Initiates the underwriting process** by setting status to "Board Immediately"
///
/// The function internally converts the user-friendly request types to the
/// Payrix API's nested JSON structure and submits a single POST to `/entities`.
///
/// # Arguments
///
/// * `client` - The Payrix API client
/// * `request` - The complete onboarding request
///
/// # Returns
///
/// Returns an [`OnboardMerchantResult`] containing:
/// - The created entity and merchant IDs
/// - Current boarding status
/// - Full entity and merchant objects
/// - Created accounts and members
///
/// # Errors
///
/// Returns an error if:
/// - The API request fails
/// - Required fields are missing or invalid
/// - Rate limits are exceeded
/// - API response is missing required data (merchant ID)
///
/// # Cancellation Safety
///
/// **Warning:** This function is NOT cancellation-safe. If the async task is
/// cancelled mid-execution (e.g., due to a timeout), partial resources may
/// exist in Payrix:
///
/// - The entity may be created but not fully fetched
/// - The merchant may be created but the function returns before completion
/// - Accounts and members may be created but not returned to the caller
///
/// If you need to handle timeouts, consider:
/// 1. Using a generous timeout (the Payrix API can take several seconds)
/// 2. Implementing a recovery mechanism that searches for recently created
///    entities if the operation fails unexpectedly
/// 3. Using unique identifiers (like EIN) to detect duplicate submissions
///
/// # Example
///
/// See module-level documentation for a complete example.
pub async fn onboard_merchant(
    client: &PayrixClient,
    request: OnboardMerchantRequest,
) -> Result<OnboardMerchantResult> {
    // Validate the request before sending to API
    validate_request(&request)?;

    // Convert the user-friendly request to Payrix's nested format
    let payload: PayrixOnboardingPayload = request.into();

    // Submit to the entities endpoint with nested data
    // The Payrix API creates entity, merchant, accounts, and members in one call
    let response: PayrixOnboardingResponse = client.create(EntityType::Entities, &payload).await?;

    // Extract the merchant and member data from the nested response
    let merchant_response = response.merchant.ok_or_else(|| {
        crate::error::Error::Internal("API response missing merchant data".into())
    })?;

    // Validate the merchant ID is not empty
    if merchant_response.id.is_empty() {
        return Err(crate::error::Error::Internal(
            "API response contains empty merchant ID".into(),
        ));
    }

    let boarding_status = merchant_response
        .status
        .map(BoardingStatus::from)
        .unwrap_or(BoardingStatus::NotReady);

    // Fetch the full entity and merchant objects for the result
    let entity: Entity = client
        .get_one(EntityType::Entities, &response.id)
        .await?
        .ok_or_else(|| crate::error::Error::Internal("Entity not found after creation".into()))?;

    let merchant: Merchant = client
        .get_one(EntityType::Merchants, &merchant_response.id)
        .await?
        .ok_or_else(|| crate::error::Error::Internal("Merchant not found after creation".into()))?;

    // Get accounts and members
    let accounts: Vec<Account> = client
        .search(
            EntityType::Accounts,
            &format!("entity[equals]={}", response.id),
        )
        .await?;

    let members: Vec<Member> = client
        .search(
            EntityType::Members,
            &format!("merchant[equals]={}", merchant_response.id),
        )
        .await?;

    Ok(OnboardMerchantResult {
        entity_id: response.id,
        merchant_id: merchant_response.id,
        boarding_status,
        entity,
        merchant,
        accounts,
        members,
    })
}

/// Check the current boarding status of a merchant.
///
/// Use this function to poll the status of a merchant application that
/// returned `Pending` or `ManualReview` status after onboarding.
///
/// # Arguments
///
/// * `client` - The Payrix API client
/// * `merchant_id` - The merchant ID to check
///
/// # Returns
///
/// Returns a [`BoardingStatusResult`] containing:
/// - Current boarding status
/// - Merchant and entity IDs
/// - Boarded date (if approved)
///
/// # Example
///
/// ```no_run
/// use payrix::{PayrixClient, Environment};
/// use payrix::workflows::merchant_onboarding::{check_boarding_status, BoardingStatus};
///
/// # async fn example() -> payrix::Result<()> {
/// let client = PayrixClient::new("api-key", Environment::Test)?;
///
/// let status = check_boarding_status(&client, "t1_mer_12345678901234567890123").await?;
///
/// match status.status {
///     BoardingStatus::Boarded => {
///         println!("Approved on: {:?}", status.boarded_date);
///     }
///     BoardingStatus::Pending => {
///         println!("Still pending review...");
///     }
///     _ => {
///         println!("Status: {}", status.status);
///     }
/// }
/// # Ok(())
/// # }
/// ```
pub async fn check_boarding_status(
    client: &PayrixClient,
    merchant_id: &str,
) -> Result<BoardingStatusResult> {
    let merchant: Merchant = client
        .get_one(EntityType::Merchants, merchant_id)
        .await?
        .ok_or_else(|| crate::error::Error::NotFound(format!("Merchant not found: {}", merchant_id)))?;

    let status = merchant
        .status
        .map(BoardingStatus::from)
        .unwrap_or(BoardingStatus::NotReady);

    Ok(BoardingStatusResult {
        status,
        merchant_id: merchant.id.as_str().to_string(),
        entity_id: merchant
            .entity
            .map(|e| e.as_str().to_string())
            .unwrap_or_default(),
        boarded_date: merchant.boarded.map(|d| d.as_str().to_string()),
    })
}

// ============================================================================
// Tests
// ============================================================================

#[cfg(test)]
mod tests {
    use super::*;

    // ============================================================================
    // Sensitive Data Masking Tests
    // ============================================================================

    #[test]
    fn test_mask_sensitive_full_ssn() {
        let result = mask_sensitive("123456789");
        assert_eq!(result, "*****6789");
    }

    #[test]
    fn test_mask_sensitive_short_value() {
        let result = mask_sensitive("1234");
        assert_eq!(result, "****");
    }

    #[test]
    fn test_mask_sensitive_empty() {
        let result = mask_sensitive("");
        assert_eq!(result, "");
    }

    #[test]
    fn test_bank_account_debug_masks_sensitive() {
        let account = BankAccountInfo {
            name: Some("Test Account".to_string()),
            routing_number: Some("123456789".to_string()),
            account_number: Some("9876543210".to_string()),
            holder_type: AccountHolderType::Business,
            account_method: BankAccountMethod::Checking,
            transaction_type: AccountType::All,
            currency: Some("USD".to_string()),
            is_primary: true,
            plaid_public_token: None,
        };
        let debug_str = format!("{:?}", account);
        // Should NOT contain full account/routing numbers
        assert!(!debug_str.contains("123456789"));
        assert!(!debug_str.contains("9876543210"));
        // Should contain masked versions
        assert!(debug_str.contains("*****6789"));
        assert!(debug_str.contains("******3210"));
    }

    #[test]
    fn test_member_info_debug_masks_ssn() {
        let member = MemberInfo {
            member_type: MemberType::Owner,
            first_name: "John".to_string(),
            last_name: "Doe".to_string(),
            title: Some("CEO".to_string()),
            ownership_percentage: 100,
            date_of_birth: "19800115".to_string(),
            ssn: "123456789".to_string(),
            email: "john@example.com".to_string(),
            phone: "5551234567".to_string(),
            address: Address {
                line1: "123 Main St".to_string(),
                line2: None,
                city: "Chicago".to_string(),
                state: "IL".to_string(),
                zip: "60601".to_string(),
                country: "USA".to_string(),
            },
        };
        let debug_str = format!("{:?}", member);
        // Should NOT contain full SSN
        assert!(!debug_str.contains("123456789"));
        // Should contain masked version
        assert!(debug_str.contains("*****6789"));
        // Name should still be visible
        assert!(debug_str.contains("John"));
    }

    // ============================================================================
    // Validation Tests
    // ============================================================================

    /// Helper to create a valid request for validation tests
    fn valid_request() -> OnboardMerchantRequest {
        OnboardMerchantRequest {
            business: BusinessInfo {
                business_type: MerchantType::LimitedLiabilityCorporation,
                legal_name: "Test LLC".to_string(),
                address: Address {
                    line1: "123 Main St".to_string(),
                    line2: None,
                    city: "Chicago".to_string(),
                    state: "IL".to_string(),
                    zip: "60601".to_string(),
                    country: "USA".to_string(),
                },
                phone: "5551234567".to_string(),
                email: "test@example.com".to_string(),
                website: None,
                ein: "123456789".to_string(),
            },
            merchant: MerchantConfig {
                dba: "Test DBA".to_string(),
                mcc: "5999".to_string(),
                environment: MerchantEnvironment::Ecommerce,
                annual_cc_sales: 100000,
                avg_ticket: 5000,
                established: DateYmd::new("20200101").unwrap(),
                is_new_business: false,
            },
            accounts: vec![BankAccountInfo {
                name: Some("Operating".to_string()),
                routing_number: Some("123456789".to_string()),
                account_number: Some("987654321".to_string()),
                holder_type: AccountHolderType::Business,
            account_method: BankAccountMethod::Checking,
                transaction_type: AccountType::All,
                currency: Some("USD".to_string()),
                is_primary: true,
                plaid_public_token: None,
            }],
            members: vec![MemberInfo {
                member_type: MemberType::Owner,
                first_name: "John".to_string(),
                last_name: "Doe".to_string(),
                title: Some("CEO".to_string()),
                ownership_percentage: 100,
                date_of_birth: "19800115".to_string(),
                ssn: "123456789".to_string(),
                email: "john@example.com".to_string(),
                phone: "5551234567".to_string(),
                address: Address {
                    line1: "456 Oak Ave".to_string(),
                    line2: None,
                    city: "Chicago".to_string(),
                    state: "IL".to_string(),
                    zip: "60602".to_string(),
                    country: "USA".to_string(),
                },
            }],
            terms_acceptance: TermsAcceptance {
                version: "4.21".to_string(),
                accepted_at: "2024-01-15 10:30:00".to_string(),
            },
        }
    }

    #[test]
    fn test_validate_valid_request() {
        let request = valid_request();
        assert!(validate_request(&request).is_ok());
    }

    #[test]
    fn test_validate_empty_accounts() {
        let mut request = valid_request();
        request.accounts = vec![];
        let err = validate_request(&request).unwrap_err();
        assert!(err.to_string().contains("bank account"));
    }

    #[test]
    fn test_validate_no_primary_account() {
        let mut request = valid_request();
        request.accounts[0].is_primary = false;
        let err = validate_request(&request).unwrap_err();
        assert!(err.to_string().contains("primary"));
    }

    #[test]
    fn test_validate_account_missing_routing_and_plaid() {
        let mut request = valid_request();
        request.accounts[0].routing_number = None;
        request.accounts[0].account_number = None;
        let err = validate_request(&request).unwrap_err();
        assert!(err.to_string().contains("routing/account numbers or a Plaid token"));
    }

    #[test]
    fn test_validate_invalid_routing_number() {
        let mut request = valid_request();
        request.accounts[0].routing_number = Some("12345".to_string()); // Too short
        let err = validate_request(&request).unwrap_err();
        assert!(err.to_string().contains("routing number"));
    }

    #[test]
    fn test_validate_routing_number_with_dashes() {
        let mut request = valid_request();
        request.accounts[0].routing_number = Some("123-456-789".to_string());
        let err = validate_request(&request).unwrap_err();
        assert!(err.to_string().contains("routing number"));
    }

    #[test]
    fn test_validate_empty_members() {
        let mut request = valid_request();
        request.members = vec![];
        let err = validate_request(&request).unwrap_err();
        assert!(err.to_string().contains("member"));
    }

    #[test]
    fn test_validate_invalid_ssn() {
        let mut request = valid_request();
        request.members[0].ssn = "123-45-6789".to_string(); // With dashes
        let err = validate_request(&request).unwrap_err();
        assert!(err.to_string().contains("SSN"));
    }

    #[test]
    fn test_validate_ssn_too_short() {
        let mut request = valid_request();
        request.members[0].ssn = "12345".to_string();
        let err = validate_request(&request).unwrap_err();
        assert!(err.to_string().contains("SSN"));
    }

    #[test]
    fn test_validate_invalid_dob() {
        let mut request = valid_request();
        request.members[0].date_of_birth = "1980-01-15".to_string(); // With dashes
        let err = validate_request(&request).unwrap_err();
        assert!(err.to_string().contains("date of birth"));
    }

    #[test]
    fn test_validate_ownership_over_100() {
        let mut request = valid_request();
        request.members[0].ownership_percentage = 150;
        let err = validate_request(&request).unwrap_err();
        assert!(err.to_string().contains("ownership"));
    }

    #[test]
    fn test_validate_negative_ownership() {
        let mut request = valid_request();
        request.members[0].ownership_percentage = -10;
        let err = validate_request(&request).unwrap_err();
        assert!(err.to_string().contains("ownership"));
    }

    #[test]
    fn test_validate_invalid_ein() {
        let mut request = valid_request();
        request.business.ein = "12-3456789".to_string(); // With dash
        let err = validate_request(&request).unwrap_err();
        assert!(err.to_string().contains("EIN"));
    }

    #[test]
    fn test_validate_ein_too_short() {
        let mut request = valid_request();
        request.business.ein = "12345".to_string();
        let err = validate_request(&request).unwrap_err();
        assert!(err.to_string().contains("EIN"));
    }

    #[test]
    fn test_validate_plaid_token_valid() {
        let mut request = valid_request();
        // Remove manual entry, add Plaid token
        request.accounts[0].routing_number = None;
        request.accounts[0].account_number = None;
        request.accounts[0].plaid_public_token = Some("public-token-xxx".to_string());
        assert!(validate_request(&request).is_ok());
    }

    #[test]
    fn test_validate_routing_number_with_letters() {
        let mut request = valid_request();
        request.accounts[0].routing_number = Some("12345678A".to_string());
        let err = validate_request(&request).unwrap_err();
        assert!(err.to_string().contains("routing number"));
    }

    #[test]
    fn test_validate_ssn_with_letters() {
        let mut request = valid_request();
        request.members[0].ssn = "12345678A".to_string();
        let err = validate_request(&request).unwrap_err();
        assert!(err.to_string().contains("SSN"));
    }

    #[test]
    fn test_validate_dob_too_short() {
        let mut request = valid_request();
        request.members[0].date_of_birth = "1980".to_string();
        let err = validate_request(&request).unwrap_err();
        assert!(err.to_string().contains("date of birth"));
    }

    #[test]
    fn test_validate_ein_with_letters() {
        let mut request = valid_request();
        request.business.ein = "12345678A".to_string();
        let err = validate_request(&request).unwrap_err();
        assert!(err.to_string().contains("EIN"));
    }

    #[test]
    fn test_validate_ownership_zero_valid() {
        let mut request = valid_request();
        request.members[0].ownership_percentage = 0;
        assert!(validate_request(&request).is_ok());
    }

    #[test]
    fn test_validate_ownership_100_valid() {
        let mut request = valid_request();
        request.members[0].ownership_percentage = 100;
        assert!(validate_request(&request).is_ok());
    }

    #[test]
    fn test_validate_second_account_fails() {
        let mut request = valid_request();
        request.accounts.push(BankAccountInfo {
            name: Some("Second".to_string()),
            routing_number: Some("invalid".to_string()), // Invalid
            account_number: Some("123456".to_string()),
            holder_type: AccountHolderType::Business,
            account_method: BankAccountMethod::Checking,
            transaction_type: AccountType::Credit,
            currency: None,
            is_primary: false,
            plaid_public_token: None,
        });
        let err = validate_request(&request).unwrap_err();
        assert!(err.to_string().contains("Account 2"));
    }

    #[test]
    fn test_validate_second_member_fails() {
        let mut request = valid_request();
        request.members.push(MemberInfo {
            member_type: MemberType::Owner,
            first_name: "Jane".to_string(),
            last_name: "Doe".to_string(),
            title: None,
            ownership_percentage: 50,
            date_of_birth: "19850520".to_string(),
            ssn: "invalid".to_string(), // Invalid
            email: "jane@example.com".to_string(),
            phone: "5559876543".to_string(),
            address: Address {
                line1: "789 Pine St".to_string(),
                line2: None,
                city: "Chicago".to_string(),
                state: "IL".to_string(),
                zip: "60603".to_string(),
                country: "USA".to_string(),
            },
        });
        let err = validate_request(&request).unwrap_err();
        assert!(err.to_string().contains("Member 2"));
    }

    // ============================================================================
    // Boarding Status Tests
    // ============================================================================

    #[test]
    fn test_boarding_status_from_merchant_status() {
        assert_eq!(
            BoardingStatus::from(MerchantStatus::NotReady),
            BoardingStatus::NotReady
        );
        assert_eq!(
            BoardingStatus::from(MerchantStatus::Ready),
            BoardingStatus::Submitted
        );
        assert_eq!(
            BoardingStatus::from(MerchantStatus::Boarded),
            BoardingStatus::Boarded
        );
        assert_eq!(
            BoardingStatus::from(MerchantStatus::Manual),
            BoardingStatus::ManualReview
        );
        assert_eq!(
            BoardingStatus::from(MerchantStatus::Closed),
            BoardingStatus::Closed
        );
        assert_eq!(
            BoardingStatus::from(MerchantStatus::Incomplete),
            BoardingStatus::Incomplete
        );
        assert_eq!(
            BoardingStatus::from(MerchantStatus::Pending),
            BoardingStatus::Pending
        );
    }

    #[test]
    fn test_boarding_status_display() {
        assert_eq!(format!("{}", BoardingStatus::NotReady), "Not Ready");
        assert_eq!(format!("{}", BoardingStatus::Submitted), "Submitted");
        assert_eq!(format!("{}", BoardingStatus::Boarded), "Boarded");
        assert_eq!(format!("{}", BoardingStatus::ManualReview), "Manual Review");
        assert_eq!(format!("{}", BoardingStatus::Closed), "Closed");
        assert_eq!(format!("{}", BoardingStatus::Incomplete), "Incomplete");
        assert_eq!(format!("{}", BoardingStatus::Pending), "Pending");
    }

    #[test]
    fn test_onboarding_payload_serialization() {
        let request = OnboardMerchantRequest {
            business: BusinessInfo {
                business_type: MerchantType::LimitedLiabilityCorporation,
                legal_name: "Test Business LLC".to_string(),
                address: Address {
                    line1: "123 Main St".to_string(),
                    line2: Some("Suite 100".to_string()),
                    city: "Springfield".to_string(),
                    state: "IL".to_string(),
                    zip: "62701".to_string(),
                    country: "USA".to_string(),
                },
                phone: "5551234567".to_string(),
                email: "test@example.com".to_string(),
                website: Some("https://example.com".to_string()),
                ein: "123456789".to_string(),
            },
            merchant: MerchantConfig {
                dba: "Test DBA".to_string(),
                mcc: "5999".to_string(),
                environment: MerchantEnvironment::Ecommerce,
                annual_cc_sales: 50000000,
                avg_ticket: 5000,
                established: DateYmd::new("20200101").unwrap(),
                is_new_business: false,
            },
            accounts: vec![BankAccountInfo {
                name: Some("Test Account".to_string()),
                routing_number: Some("123456789".to_string()),
                account_number: Some("987654321".to_string()),
                holder_type: AccountHolderType::Business,
            account_method: BankAccountMethod::Checking,
                transaction_type: AccountType::All,
                currency: Some("USD".to_string()),
                is_primary: true,
                plaid_public_token: None,
            }],
            members: vec![MemberInfo {
                member_type: MemberType::Owner,
                first_name: "John".to_string(),
                last_name: "Doe".to_string(),
                title: Some("CEO".to_string()),
                ownership_percentage: 100,
                date_of_birth: "19800115".to_string(),
                ssn: "123456789".to_string(),
                email: "john@example.com".to_string(),
                phone: "5559876543".to_string(),
                address: Address {
                    line1: "456 Oak Ave".to_string(),
                    line2: None,
                    city: "Springfield".to_string(),
                    state: "IL".to_string(),
                    zip: "62702".to_string(),
                    country: "USA".to_string(),
                },
            }],
            terms_acceptance: TermsAcceptance {
                version: "4.21".to_string(),
                accepted_at: "2024-01-15 10:30:00".to_string(),
            },
        };

        let payload: PayrixOnboardingPayload = request.into();
        let json = serde_json::to_string_pretty(&payload).unwrap();

        // Verify key fields are present in serialized output
        // Note: to_string_pretty adds spaces, so we check for ": " format
        assert!(json.contains("\"type\": 2"), "Expected LLC type (2) in JSON: {}", json);
        assert!(json.contains("\"name\": \"Test Business LLC\""));
        assert!(json.contains("\"address1\": \"123 Main St\""));
        assert!(json.contains("\"tcVersion\": \"4.21\""));
        assert!(json.contains("\"tcAttestation\": 1"));
        assert!(json.contains("\"dba\": \"Test DBA\""));
        assert!(json.contains("\"mcc\": \"5999\""));
        assert!(json.contains("\"status\": 1")); // Board Immediately
        assert!(json.contains("\"primary\": 1"));
        assert!(json.contains("\"routing\": \"123456789\""));
        assert!(json.contains("\"first\": \"John\""));
        assert!(json.contains("\"ownership\": 100"));
    }

    #[test]
    fn test_account_payload_conversion() {
        // Test with manual entry (routing/account numbers)
        let account = BankAccountInfo {
            name: Some("Operating Account".to_string()),
            routing_number: Some("123456789".to_string()),
            account_number: Some("987654321".to_string()),
            holder_type: AccountHolderType::Business,
            account_method: BankAccountMethod::Checking,
            transaction_type: AccountType::All,
            currency: Some("USD".to_string()),
            is_primary: true,
            plaid_public_token: None,
        };

        let payload: PayrixAccountPayload = account.into();
        assert_eq!(payload.primary, 1);
        assert_eq!(payload.name, Some("Operating Account".to_string()));
        assert_eq!(payload.transaction_type, AccountType::All);
        assert_eq!(payload.currency, Some("USD".to_string()));
        assert!(payload.account.is_some());
        let account_details = payload.account.unwrap();
        assert_eq!(account_details.routing, "123456789");
        assert_eq!(account_details.number, "987654321");
        assert_eq!(account_details.method, 10); // Business + Checking = 10
        assert_eq!(account_details.holder_type, AccountHolderType::Business);
    }

    #[test]
    fn test_account_payload_with_plaid() {
        // Test with Plaid token (no routing/account numbers)
        let account = BankAccountInfo {
            name: Some("Plaid Account".to_string()),
            routing_number: None,
            account_number: None,
            holder_type: AccountHolderType::Business,
            account_method: BankAccountMethod::Checking,
            transaction_type: AccountType::Credit,  // Deposits only
            currency: Some("USD".to_string()),
            is_primary: false,
            plaid_public_token: Some("public-sandbox-xxx".to_string()),
        };

        let payload: PayrixAccountPayload = account.into();
        assert_eq!(payload.primary, 0);
        assert_eq!(payload.transaction_type, AccountType::Credit);
        assert!(payload.account.is_none());  // No manual account details
        assert_eq!(payload.public_token, Some("public-sandbox-xxx".to_string()));
    }

    #[test]
    fn test_member_payload_conversion() {
        let member = MemberInfo {
            member_type: MemberType::Owner,
            first_name: "Jane".to_string(),
            last_name: "Smith".to_string(),
            title: Some("President".to_string()),
            ownership_percentage: 50,
            date_of_birth: "19850620".to_string(),
            ssn: "987654321".to_string(),
            email: "jane@example.com".to_string(),
            phone: "5551112222".to_string(),
            address: Address {
                line1: "789 Pine Rd".to_string(),
                line2: None,
                city: "Chicago".to_string(),
                state: "IL".to_string(),
                zip: "60601".to_string(),
                country: "USA".to_string(),
            },
        };

        let payload: PayrixMemberPayload = member.into();
        assert_eq!(payload.first, "Jane");
        assert_eq!(payload.last, "Smith");
        assert_eq!(payload.title, Some("President".to_string()));
        assert_eq!(payload.ownership, 50);
        assert_eq!(payload.dob, "19850620");
        assert_eq!(payload.ssn, "987654321");
    }

    #[test]
    fn test_trust_and_operating_account_scenario() {
        // Test the common scenario of having two accounts:
        // 1. Operating account (All) - for deposits AND fee withdrawals
        // 2. Trust account (Credit only) - for deposits only, no fee withdrawals
        //
        // This is common for businesses that handle client funds (law firms,
        // escrow companies, property managers, etc.) where trust funds must
        // be kept separate from operating funds.

        let operating_account = BankAccountInfo {
            name: Some("Operating Account".to_string()),
            routing_number: Some("123456789".to_string()),
            account_number: Some("111111111".to_string()),
            holder_type: AccountHolderType::Business,
            account_method: BankAccountMethod::Checking,
            transaction_type: AccountType::All,  // Deposits AND fee withdrawals
            currency: Some("USD".to_string()),
            is_primary: true,  // Primary account for fees
            plaid_public_token: None,
        };

        let trust_account = BankAccountInfo {
            name: Some("Client Trust Account".to_string()),
            routing_number: Some("123456789".to_string()),
            account_number: Some("222222222".to_string()),
            holder_type: AccountHolderType::Business,
            account_method: BankAccountMethod::Checking,
            transaction_type: AccountType::Credit,  // Deposits ONLY - no fee withdrawals
            currency: Some("USD".to_string()),
            is_primary: false,  // Not primary - fees come from operating
            plaid_public_token: None,
        };

        // Convert to Payrix payloads
        let operating_payload: PayrixAccountPayload = operating_account.into();
        let trust_payload: PayrixAccountPayload = trust_account.into();

        // Verify operating account setup
        assert_eq!(operating_payload.primary, 1);
        assert_eq!(operating_payload.transaction_type, AccountType::All);
        assert_eq!(operating_payload.name, Some("Operating Account".to_string()));
        let operating_details = operating_payload.account.unwrap();
        assert_eq!(operating_details.number, "111111111");

        // Verify trust account setup
        assert_eq!(trust_payload.primary, 0);
        assert_eq!(trust_payload.transaction_type, AccountType::Credit);
        assert_eq!(trust_payload.name, Some("Client Trust Account".to_string()));
        let trust_details = trust_payload.account.unwrap();
        assert_eq!(trust_details.number, "222222222");

        // Verify the accounts serialize correctly for Payrix API
        let accounts = vec![
            BankAccountInfo {
                name: Some("Operating Account".to_string()),
                routing_number: Some("123456789".to_string()),
                account_number: Some("111111111".to_string()),
                holder_type: AccountHolderType::Business,
            account_method: BankAccountMethod::Checking,
                transaction_type: AccountType::All,
                currency: Some("USD".to_string()),
                is_primary: true,
                plaid_public_token: None,
            },
            BankAccountInfo {
                name: Some("Client Trust Account".to_string()),
                routing_number: Some("123456789".to_string()),
                account_number: Some("222222222".to_string()),
                holder_type: AccountHolderType::Business,
            account_method: BankAccountMethod::Checking,
                transaction_type: AccountType::Credit,
                currency: Some("USD".to_string()),
                is_primary: false,
                plaid_public_token: None,
            },
        ];

        let payloads: Vec<PayrixAccountPayload> = accounts.into_iter().map(Into::into).collect();
        let json = serde_json::to_string_pretty(&payloads).unwrap();

        // Verify both accounts appear in JSON
        assert!(json.contains("\"number\": \"111111111\""), "Operating account number should be in JSON");
        assert!(json.contains("\"number\": \"222222222\""), "Trust account number should be in JSON");
        // AccountType serializes as lowercase strings
        assert!(json.contains("\"type\": \"all\""), "Operating account should have type 'all'");
        assert!(json.contains("\"type\": \"credit\""), "Trust account should have type 'credit'");
    }

    // ============================================================================
    // Required Fields Tests
    // ============================================================================

    /// Helper to create a minimal valid OnboardMerchantRequest for testing
    fn create_test_request() -> OnboardMerchantRequest {
        OnboardMerchantRequest {
            business: BusinessInfo {
                business_type: MerchantType::LimitedLiabilityCorporation,
                legal_name: "Test Business LLC".to_string(),
                address: Address {
                    line1: "123 Main St".to_string(),
                    line2: None,
                    city: "Springfield".to_string(),
                    state: "IL".to_string(),
                    zip: "62701".to_string(),
                    country: "USA".to_string(),
                },
                phone: "5551234567".to_string(),
                email: "test@example.com".to_string(),
                website: None,
                ein: "123456789".to_string(),
            },
            merchant: MerchantConfig {
                dba: "Test DBA".to_string(),
                mcc: "5999".to_string(),
                environment: MerchantEnvironment::Ecommerce,
                annual_cc_sales: 50000000,
                avg_ticket: 5000,
                established: DateYmd::new("20200101").unwrap(),
                is_new_business: false,
            },
            accounts: vec![BankAccountInfo {
                name: None,
                routing_number: Some("123456789".to_string()),
                account_number: Some("987654321".to_string()),
                holder_type: AccountHolderType::Business,
            account_method: BankAccountMethod::Checking,
                transaction_type: AccountType::All,
                currency: None,
                is_primary: true,
                plaid_public_token: None,
            }],
            members: vec![MemberInfo {
                member_type: MemberType::Owner,
                first_name: "John".to_string(),
                last_name: "Doe".to_string(),
                title: None,
                ownership_percentage: 100,
                date_of_birth: "19800115".to_string(),
                ssn: "123456789".to_string(),
                email: "john@example.com".to_string(),
                phone: "5559876543".to_string(),
                address: Address {
                    line1: "456 Oak Ave".to_string(),
                    line2: None,
                    city: "Springfield".to_string(),
                    state: "IL".to_string(),
                    zip: "62702".to_string(),
                    country: "USA".to_string(),
                },
            }],
            terms_acceptance: TermsAcceptance {
                version: "4.21".to_string(),
                accepted_at: "2024-01-15 10:30:00".to_string(),
            },
        }
    }

    #[test]
    fn test_payload_contains_all_required_entity_fields() {
        let request = create_test_request();
        let payload: PayrixOnboardingPayload = request.into();
        let json = serde_json::to_string(&payload).unwrap();

        // Required Entity fields
        assert!(json.contains("\"type\":"), "Missing required field: type (entity_type)");
        assert!(json.contains("\"name\":"), "Missing required field: name");
        assert!(json.contains("\"address1\":"), "Missing required field: address1");
        assert!(json.contains("\"city\":"), "Missing required field: city");
        assert!(json.contains("\"state\":"), "Missing required field: state");
        assert!(json.contains("\"zip\":"), "Missing required field: zip");
        assert!(json.contains("\"country\":"), "Missing required field: country");
        assert!(json.contains("\"phone\":"), "Missing required field: phone");
        assert!(json.contains("\"email\":"), "Missing required field: email");
        assert!(json.contains("\"ein\":"), "Missing required field: ein");

        // Terms & Conditions fields
        assert!(json.contains("\"tcVersion\":"), "Missing required field: tcVersion");
        assert!(json.contains("\"tcDate\":"), "Missing required field: tcDate");
        assert!(json.contains("\"tcAttestation\":"), "Missing required field: tcAttestation");

        // Nested required fields
        assert!(json.contains("\"accounts\":"), "Missing required field: accounts");
        assert!(json.contains("\"merchant\":"), "Missing required field: merchant");
    }

    #[test]
    fn test_payload_contains_all_required_merchant_fields() {
        let request = create_test_request();
        let payload: PayrixOnboardingPayload = request.into();
        let json = serde_json::to_string(&payload).unwrap();

        // Deserialize to inspect merchant section
        let value: serde_json::Value = serde_json::from_str(&json).unwrap();
        let merchant = value.get("merchant").expect("merchant field missing");

        assert!(merchant.get("dba").is_some(), "Missing required merchant field: dba");
        assert!(merchant.get("mcc").is_some(), "Missing required merchant field: mcc");
        assert!(merchant.get("status").is_some(), "Missing required merchant field: status");
        assert!(merchant.get("environment").is_some(), "Missing required merchant field: environment");
        assert!(merchant.get("annualCcSales").is_some(), "Missing required merchant field: annualCcSales");
        assert!(merchant.get("avgTicket").is_some(), "Missing required merchant field: avgTicket");
        assert!(merchant.get("established").is_some(), "Missing required merchant field: established");
        assert!(merchant.get("new").is_some(), "Missing required merchant field: new (is_new_business)");
        assert!(merchant.get("members").is_some(), "Missing required merchant field: members");
    }

    #[test]
    fn test_payload_contains_all_required_account_fields() {
        let request = create_test_request();
        let payload: PayrixOnboardingPayload = request.into();
        let json = serde_json::to_string(&payload).unwrap();

        let value: serde_json::Value = serde_json::from_str(&json).unwrap();
        let accounts = value.get("accounts").expect("accounts field missing").as_array().unwrap();
        assert!(!accounts.is_empty(), "accounts array should not be empty");

        let account = &accounts[0];
        assert!(account.get("primary").is_some(), "Missing required account field: primary");
        assert!(account.get("type").is_some(), "Missing required account field: type");

        // For manual entry accounts, nested account details are required
        let account_details = account.get("account").expect("Missing account.account for manual entry");
        assert!(account_details.get("method").is_some(), "Missing required field: account.method");
        assert!(account_details.get("number").is_some(), "Missing required field: account.number");
        assert!(account_details.get("routing").is_some(), "Missing required field: account.routing");
        assert!(account_details.get("holderType").is_some(), "Missing required field: account.holderType");
    }

    #[test]
    fn test_payload_contains_all_required_member_fields() {
        let request = create_test_request();
        let payload: PayrixOnboardingPayload = request.into();
        let json = serde_json::to_string(&payload).unwrap();

        let value: serde_json::Value = serde_json::from_str(&json).unwrap();
        let members = value
            .get("merchant").expect("merchant missing")
            .get("members").expect("members missing")
            .as_array().unwrap();
        assert!(!members.is_empty(), "members array should not be empty");

        let member = &members[0];
        assert!(member.get("type").is_some(), "Missing required member field: type");
        assert!(member.get("first").is_some(), "Missing required member field: first");
        assert!(member.get("last").is_some(), "Missing required member field: last");
        assert!(member.get("ownership").is_some(), "Missing required member field: ownership");
        assert!(member.get("dob").is_some(), "Missing required member field: dob");
        assert!(member.get("ssn").is_some(), "Missing required member field: ssn");
        assert!(member.get("email").is_some(), "Missing required member field: email");
        assert!(member.get("phone").is_some(), "Missing required member field: phone");
        assert!(member.get("address1").is_some(), "Missing required member field: address1");
        assert!(member.get("city").is_some(), "Missing required member field: city");
        assert!(member.get("state").is_some(), "Missing required member field: state");
        assert!(member.get("zip").is_some(), "Missing required member field: zip");
        assert!(member.get("country").is_some(), "Missing required member field: country");
    }

    // ============================================================================
    // Read-Only Fields Tests
    // ============================================================================

    #[test]
    fn test_payload_excludes_entity_readonly_fields() {
        let request = create_test_request();
        let payload: PayrixOnboardingPayload = request.into();
        let json = serde_json::to_string(&payload).unwrap();

        // These fields are read-only and should NOT be in the serialized payload
        // They are returned by the Payrix API but should never be sent
        assert!(!json.contains("\"id\":"), "Read-only field 'id' should not be serialized");
        assert!(!json.contains("\"created\":"), "Read-only field 'created' should not be serialized");
        assert!(!json.contains("\"modified\":"), "Read-only field 'modified' should not be serialized");
        assert!(!json.contains("\"login\":"), "Read-only field 'login' should not be serialized");
        assert!(!json.contains("\"frozen\":"), "Read-only field 'frozen' should not be serialized");
        assert!(!json.contains("\"inactive\":"), "Read-only field 'inactive' should not be serialized");
    }

    #[test]
    fn test_payload_excludes_account_readonly_fields() {
        let account = BankAccountInfo {
            name: Some("Test Account".to_string()),
            routing_number: Some("123456789".to_string()),
            account_number: Some("987654321".to_string()),
            holder_type: AccountHolderType::Business,
            account_method: BankAccountMethod::Checking,
            transaction_type: AccountType::All,
            currency: Some("USD".to_string()),
            is_primary: true,
            plaid_public_token: None,
        };

        let payload: PayrixAccountPayload = account.into();
        let json = serde_json::to_string(&payload).unwrap();

        // Account read-only fields that should NOT be serialized
        assert!(!json.contains("\"id\":"), "Read-only field 'id' should not be in account payload");
        assert!(!json.contains("\"entity\":"), "Read-only field 'entity' should not be in account payload");
        assert!(!json.contains("\"merchant\":"), "Read-only field 'merchant' should not be in account payload");
        assert!(!json.contains("\"login\":"), "Read-only field 'login' should not be in account payload");
        assert!(!json.contains("\"last4\":"), "Read-only field 'last4' should not be in account payload");
        assert!(!json.contains("\"status\":"), "Read-only field 'status' should not be in account payload");
        assert!(!json.contains("\"verified\":"), "Read-only field 'verified' should not be in account payload");
        assert!(!json.contains("\"created\":"), "Read-only field 'created' should not be in account payload");
        assert!(!json.contains("\"modified\":"), "Read-only field 'modified' should not be in account payload");
        assert!(!json.contains("\"frozen\":"), "Read-only field 'frozen' should not be in account payload");
        assert!(!json.contains("\"inactive\":"), "Read-only field 'inactive' should not be in account payload");
    }

    #[test]
    fn test_payload_excludes_member_readonly_fields() {
        let member = MemberInfo {
            member_type: MemberType::Owner,
            first_name: "John".to_string(),
            last_name: "Doe".to_string(),
            title: None,
            ownership_percentage: 100,
            date_of_birth: "19800115".to_string(),
            ssn: "123456789".to_string(),
            email: "john@example.com".to_string(),
            phone: "5559876543".to_string(),
            address: Address {
                line1: "456 Oak Ave".to_string(),
                line2: None,
                city: "Springfield".to_string(),
                state: "IL".to_string(),
                zip: "62702".to_string(),
                country: "USA".to_string(),
            },
        };

        let payload: PayrixMemberPayload = member.into();
        let json = serde_json::to_string(&payload).unwrap();

        // Member read-only fields that should NOT be serialized
        assert!(!json.contains("\"id\":"), "Read-only field 'id' should not be in member payload");
        assert!(!json.contains("\"entity\":"), "Read-only field 'entity' should not be in member payload");
        assert!(!json.contains("\"merchant\":"), "Read-only field 'merchant' should not be in member payload");
        assert!(!json.contains("\"login\":"), "Read-only field 'login' should not be in member payload");
        assert!(!json.contains("\"created\":"), "Read-only field 'created' should not be in member payload");
        assert!(!json.contains("\"modified\":"), "Read-only field 'modified' should not be in member payload");
        assert!(!json.contains("\"frozen\":"), "Read-only field 'frozen' should not be in member payload");
        assert!(!json.contains("\"inactive\":"), "Read-only field 'inactive' should not be in member payload");
    }

    #[test]
    fn test_payload_excludes_merchant_readonly_fields() {
        let request = create_test_request();
        let payload: PayrixOnboardingPayload = request.into();
        let json = serde_json::to_string(&payload).unwrap();

        let value: serde_json::Value = serde_json::from_str(&json).unwrap();
        let merchant = value.get("merchant").expect("merchant field missing");
        let merchant_json = serde_json::to_string(merchant).unwrap();

        // Merchant read-only fields that should NOT be serialized
        // Note: The "status" field IS included because we set it to 1 (Board Immediately)
        // This is a create-time value, not a read-only response value
        assert!(!merchant_json.contains("\"id\":"), "Read-only field 'id' should not be in merchant payload");
        assert!(!merchant_json.contains("\"entity\":"), "Read-only field 'entity' should not be in merchant payload");
        assert!(!merchant_json.contains("\"login\":"), "Read-only field 'login' should not be in merchant payload");
        assert!(!merchant_json.contains("\"created\":"), "Read-only field 'created' should not be in merchant payload");
        assert!(!merchant_json.contains("\"modified\":"), "Read-only field 'modified' should not be in merchant payload");
        assert!(!merchant_json.contains("\"frozen\":"), "Read-only field 'frozen' should not be in merchant payload");
        assert!(!merchant_json.contains("\"inactive\":"), "Read-only field 'inactive' should not be in merchant payload");
        assert!(!merchant_json.contains("\"boarded\":"), "Read-only field 'boarded' should not be in merchant payload");
    }

    // ============================================================================
    // Serialization Format Tests
    // ============================================================================

    #[test]
    fn test_payload_uses_camel_case() {
        let request = create_test_request();
        let payload: PayrixOnboardingPayload = request.into();
        let json = serde_json::to_string(&payload).unwrap();

        // Verify camelCase is used (not snake_case)
        assert!(json.contains("\"tcVersion\":"), "Should use camelCase: tcVersion");
        assert!(json.contains("\"tcDate\":"), "Should use camelCase: tcDate");
        assert!(json.contains("\"tcAttestation\":"), "Should use camelCase: tcAttestation");
        assert!(json.contains("\"annualCcSales\":"), "Should use camelCase: annualCcSales");
        assert!(json.contains("\"avgTicket\":"), "Should use camelCase: avgTicket");
        assert!(json.contains("\"holderType\":"), "Should use camelCase: holderType");

        // Verify snake_case is NOT used
        assert!(!json.contains("\"tc_version\":"), "Should not use snake_case");
        assert!(!json.contains("\"tc_date\":"), "Should not use snake_case");
        assert!(!json.contains("\"annual_cc_sales\":"), "Should not use snake_case");
        assert!(!json.contains("\"avg_ticket\":"), "Should not use snake_case");
        assert!(!json.contains("\"holder_type\":"), "Should not use snake_case");
    }

    #[test]
    fn test_payload_skips_none_optional_fields() {
        let request = create_test_request();
        let payload: PayrixOnboardingPayload = request.into();
        let json = serde_json::to_string(&payload).unwrap();

        // Optional fields that are None should not appear in JSON
        // In our test request, website is None
        assert!(!json.contains("\"website\":"), "Optional None field 'website' should not be serialized");

        // address2 is also None in our test request
        assert!(!json.contains("\"address2\":"), "Optional None field 'address2' should not be serialized");
    }

    #[test]
    fn test_payload_includes_some_optional_fields() {
        let mut request = create_test_request();
        request.business.website = Some("https://example.com".to_string());
        request.business.address.line2 = Some("Suite 100".to_string());

        let payload: PayrixOnboardingPayload = request.into();
        let json = serde_json::to_string(&payload).unwrap();

        // Optional fields that are Some should appear in JSON
        assert!(json.contains("\"website\":\"https://example.com\""), "Optional Some field 'website' should be serialized");
        assert!(json.contains("\"address2\":\"Suite 100\""), "Optional Some field 'address2' should be serialized");
    }

    // ============================================================================
    // Value Correctness Tests
    // ============================================================================

    #[test]
    fn test_boarding_status_is_board_immediately() {
        let request = create_test_request();
        let payload: PayrixOnboardingPayload = request.into();
        let json = serde_json::to_string(&payload).unwrap();

        let value: serde_json::Value = serde_json::from_str(&json).unwrap();
        let merchant = value.get("merchant").expect("merchant missing");
        let status = merchant.get("status").expect("status missing").as_i64().unwrap();

        // Status should be 1 (Board Immediately) for onboarding requests
        assert_eq!(status, 1, "Merchant status should be 1 (Board Immediately)");
    }

    #[test]
    fn test_tc_attestation_is_one() {
        let request = create_test_request();
        let payload: PayrixOnboardingPayload = request.into();
        let json = serde_json::to_string(&payload).unwrap();

        let value: serde_json::Value = serde_json::from_str(&json).unwrap();
        let tc_attestation = value.get("tcAttestation").expect("tcAttestation missing").as_i64().unwrap();

        // Terms attestation should always be 1 (accepted)
        assert_eq!(tc_attestation, 1, "tcAttestation should be 1");
    }

    #[test]
    fn test_primary_account_flag_serialization() {
        // Primary account
        let primary_account = BankAccountInfo {
            name: None,
            routing_number: Some("123456789".to_string()),
            account_number: Some("111111111".to_string()),
            holder_type: AccountHolderType::Business,
            account_method: BankAccountMethod::Checking,
            transaction_type: AccountType::All,
            currency: None,
            is_primary: true,
            plaid_public_token: None,
        };
        let primary_payload: PayrixAccountPayload = primary_account.into();
        assert_eq!(primary_payload.primary, 1, "Primary account should have primary=1");

        // Non-primary account
        let secondary_account = BankAccountInfo {
            name: None,
            routing_number: Some("123456789".to_string()),
            account_number: Some("222222222".to_string()),
            holder_type: AccountHolderType::Business,
            account_method: BankAccountMethod::Checking,
            transaction_type: AccountType::Credit,
            currency: None,
            is_primary: false,
            plaid_public_token: None,
        };
        let secondary_payload: PayrixAccountPayload = secondary_account.into();
        assert_eq!(secondary_payload.primary, 0, "Non-primary account should have primary=0");
    }

    #[test]
    fn test_new_business_flag_serialization() {
        // Established business
        let mut request = create_test_request();
        request.merchant.is_new_business = false;
        let payload: PayrixOnboardingPayload = request.into();
        let json = serde_json::to_string(&payload).unwrap();
        let value: serde_json::Value = serde_json::from_str(&json).unwrap();
        let new_flag = value.get("merchant").unwrap().get("new").unwrap().as_i64().unwrap();
        assert_eq!(new_flag, 0, "Established business should have new=0");

        // New business
        let mut request = create_test_request();
        request.merchant.is_new_business = true;
        let payload: PayrixOnboardingPayload = request.into();
        let json = serde_json::to_string(&payload).unwrap();
        let value: serde_json::Value = serde_json::from_str(&json).unwrap();
        let new_flag = value.get("merchant").unwrap().get("new").unwrap().as_i64().unwrap();
        assert_eq!(new_flag, 1, "New business should have new=1");
    }

    #[test]
    fn test_account_method_business_checking() {
        let account = BankAccountInfo {
            name: None,
            routing_number: Some("123456789".to_string()),
            account_number: Some("987654321".to_string()),
            holder_type: AccountHolderType::Business,
            account_method: BankAccountMethod::Checking,
            transaction_type: AccountType::All,
            currency: None,
            is_primary: true,
            plaid_public_token: None,
        };

        let payload: PayrixAccountPayload = account.into();
        let account_details = payload.account.expect("account details missing");

        // Business + Checking = 10
        assert_eq!(account_details.method, 10, "Business checking should be method 10");
    }

    #[test]
    fn test_account_method_business_savings() {
        let account = BankAccountInfo {
            name: None,
            routing_number: Some("123456789".to_string()),
            account_number: Some("987654321".to_string()),
            holder_type: AccountHolderType::Business,
            account_method: BankAccountMethod::Savings,
            transaction_type: AccountType::All,
            currency: None,
            is_primary: true,
            plaid_public_token: None,
        };

        let payload: PayrixAccountPayload = account.into();
        let account_details = payload.account.expect("account details missing");

        // Business + Savings = 11
        assert_eq!(account_details.method, 11, "Business savings should be method 11");
    }

    #[test]
    fn test_account_method_individual_checking() {
        let account = BankAccountInfo {
            name: None,
            routing_number: Some("123456789".to_string()),
            account_number: Some("987654321".to_string()),
            holder_type: AccountHolderType::Individual,
            account_method: BankAccountMethod::Checking,
            transaction_type: AccountType::All,
            currency: None,
            is_primary: true,
            plaid_public_token: None,
        };

        let payload: PayrixAccountPayload = account.into();
        let account_details = payload.account.expect("account details missing");

        // Individual + Checking = 8
        assert_eq!(account_details.method, 8, "Individual checking should be method 8");
    }

    #[test]
    fn test_account_method_individual_savings() {
        let account = BankAccountInfo {
            name: None,
            routing_number: Some("123456789".to_string()),
            account_number: Some("987654321".to_string()),
            holder_type: AccountHolderType::Individual,
            account_method: BankAccountMethod::Savings,
            transaction_type: AccountType::All,
            currency: None,
            is_primary: true,
            plaid_public_token: None,
        };

        let payload: PayrixAccountPayload = account.into();
        let account_details = payload.account.expect("account details missing");

        // Individual + Savings = 9
        assert_eq!(account_details.method, 9, "Individual savings should be method 9");
    }

    /// Exhaustive test of ALL holder type + account method combinations.
    /// This ensures we never miss a combination when making changes.
    #[test]
    fn test_account_method_exhaustive_combinations() {
        let test_cases: &[(AccountHolderType, BankAccountMethod, i32, &str)] = &[
            (AccountHolderType::Individual, BankAccountMethod::Checking, 8, "Individual+Checking"),
            (AccountHolderType::Individual, BankAccountMethod::Savings, 9, "Individual+Savings"),
            (AccountHolderType::Business, BankAccountMethod::Checking, 10, "Business+Checking"),
            (AccountHolderType::Business, BankAccountMethod::Savings, 11, "Business+Savings"),
        ];

        for (holder_type, account_method, expected_method, description) in test_cases {
            let account = BankAccountInfo {
                name: None,
                routing_number: Some("123456789".to_string()),
                account_number: Some("987654321".to_string()),
                holder_type: *holder_type,
                account_method: *account_method,
                transaction_type: AccountType::All,
                currency: None,
                is_primary: true,
                plaid_public_token: None,
            };

            let payload: PayrixAccountPayload = account.into();
            let account_details = payload.account.expect("account details missing");

            assert_eq!(
                account_details.method, *expected_method,
                "Failed for {}: expected method {}, got {}",
                description, expected_method, account_details.method
            );
        }
    }

    // ============================================================================
    // Error Path and Edge Case Tests
    // ============================================================================

    #[test]
    fn test_response_missing_merchant_field() {
        // Simulate API response with missing merchant data
        let json = r#"{
            "id": "t1_ent_12345678901234567890123"
        }"#;

        let response: PayrixOnboardingResponse = serde_json::from_str(json).unwrap();
        assert!(response.merchant.is_none(), "merchant should be None when missing from response");
    }

    #[test]
    fn test_response_with_empty_merchant_id() {
        // Simulate API response with empty merchant ID
        let json = r#"{
            "id": "t1_ent_12345678901234567890123",
            "merchant": {
                "id": "",
                "status": 1
            }
        }"#;

        let response: PayrixOnboardingResponse = serde_json::from_str(json).unwrap();
        let merchant = response.merchant.unwrap();
        assert!(merchant.id.is_empty(), "merchant ID should be empty");
    }

    #[test]
    fn test_response_with_null_status() {
        // Simulate API response with null/missing status
        let json = r#"{
            "id": "t1_ent_12345678901234567890123",
            "merchant": {
                "id": "t1_mer_12345678901234567890123"
            }
        }"#;

        let response: PayrixOnboardingResponse = serde_json::from_str(json).unwrap();
        let merchant = response.merchant.unwrap();
        assert!(merchant.status.is_none(), "status should be None when missing");
    }

    #[test]
    fn test_boarding_status_defaults_to_not_ready_when_missing() {
        // When status is None, BoardingStatus should default to NotReady
        let status: Option<MerchantStatus> = None;
        let boarding_status = status
            .map(BoardingStatus::from)
            .unwrap_or(BoardingStatus::NotReady);
        assert_eq!(boarding_status, BoardingStatus::NotReady);
    }

    #[test]
    fn test_bank_account_method_default() {
        // Verify the default is Checking
        assert_eq!(BankAccountMethod::default(), BankAccountMethod::Checking);
    }

    #[test]
    fn test_validation_catches_empty_routing_with_account_number() {
        // Edge case: account number provided but no routing number
        let mut request = valid_request();
        request.accounts[0].routing_number = None;
        request.accounts[0].account_number = Some("123456789".to_string());
        request.accounts[0].plaid_public_token = None;

        let err = validate_request(&request).unwrap_err();
        assert!(err.to_string().contains("routing/account numbers or a Plaid token"));
    }

    #[test]
    fn test_validation_catches_routing_without_account_number() {
        // Edge case: routing number provided but no account number
        let mut request = valid_request();
        request.accounts[0].routing_number = Some("123456789".to_string());
        request.accounts[0].account_number = None;
        request.accounts[0].plaid_public_token = None;

        let err = validate_request(&request).unwrap_err();
        assert!(err.to_string().contains("routing/account numbers or a Plaid token"));
    }

    // ============================================================================
    // Type Enum Serialization Tests
    // ============================================================================

    #[test]
    fn test_entity_type_serialization() {
        // Test that MerchantType (entity type) serializes to correct integer
        let mut request = create_test_request();
        request.business.business_type = MerchantType::LimitedLiabilityCorporation;
        let payload: PayrixOnboardingPayload = request.into();
        let json = serde_json::to_string(&payload).unwrap();

        // LLC should serialize to 2
        assert!(json.contains("\"type\":2"), "LLC should serialize to type=2, got: {}", json);
    }

    #[test]
    fn test_member_type_serialization() {
        // Owner type
        let mut member = MemberInfo {
            member_type: MemberType::Owner,
            first_name: "John".to_string(),
            last_name: "Doe".to_string(),
            title: None,
            ownership_percentage: 100,
            date_of_birth: "19800115".to_string(),
            ssn: "123456789".to_string(),
            email: "john@example.com".to_string(),
            phone: "5559876543".to_string(),
            address: Address {
                line1: "456 Oak Ave".to_string(),
                line2: None,
                city: "Springfield".to_string(),
                state: "IL".to_string(),
                zip: "62702".to_string(),
                country: "USA".to_string(),
            },
        };
        let payload: PayrixMemberPayload = member.clone().into();
        let json = serde_json::to_string(&payload).unwrap();
        assert!(json.contains("\"type\":1"), "Owner should serialize to type=1");

        // ControlPerson type
        member.member_type = MemberType::ControlPerson;
        let payload: PayrixMemberPayload = member.clone().into();
        let json = serde_json::to_string(&payload).unwrap();
        assert!(json.contains("\"type\":2"), "ControlPerson should serialize to type=2");

        // Principal type
        member.member_type = MemberType::Principal;
        let payload: PayrixMemberPayload = member.into();
        let json = serde_json::to_string(&payload).unwrap();
        assert!(json.contains("\"type\":3"), "Principal should serialize to type=3");
    }

    #[test]
    fn test_account_type_serialization() {
        // All type
        let mut account = BankAccountInfo {
            name: None,
            routing_number: Some("123456789".to_string()),
            account_number: Some("987654321".to_string()),
            holder_type: AccountHolderType::Business,
            account_method: BankAccountMethod::Checking,
            transaction_type: AccountType::All,
            currency: None,
            is_primary: true,
            plaid_public_token: None,
        };
        let payload: PayrixAccountPayload = account.clone().into();
        let json = serde_json::to_string(&payload).unwrap();
        assert!(json.contains("\"type\":\"all\""), "AccountType::All should serialize to 'all'");

        // Credit type
        account.transaction_type = AccountType::Credit;
        let payload: PayrixAccountPayload = account.clone().into();
        let json = serde_json::to_string(&payload).unwrap();
        assert!(json.contains("\"type\":\"credit\""), "AccountType::Credit should serialize to 'credit'");

        // Debit type
        account.transaction_type = AccountType::Debit;
        let payload: PayrixAccountPayload = account.into();
        let json = serde_json::to_string(&payload).unwrap();
        assert!(json.contains("\"type\":\"debit\""), "AccountType::Debit should serialize to 'debit'");
    }

    #[test]
    fn test_account_holder_type_serialization() {
        // Business holder type
        let mut account = BankAccountInfo {
            name: None,
            routing_number: Some("123456789".to_string()),
            account_number: Some("987654321".to_string()),
            holder_type: AccountHolderType::Business,
            account_method: BankAccountMethod::Checking,
            transaction_type: AccountType::All,
            currency: None,
            is_primary: true,
            plaid_public_token: None,
        };
        let payload: PayrixAccountPayload = account.clone().into();
        let json = serde_json::to_string(&payload).unwrap();
        // Business should serialize to 2
        assert!(json.contains("\"holderType\":2"), "AccountHolderType::Business should serialize to 2, got: {}", json);

        // Individual holder type
        account.holder_type = AccountHolderType::Individual;
        let payload: PayrixAccountPayload = account.into();
        let json = serde_json::to_string(&payload).unwrap();
        // Individual should serialize to 1
        assert!(json.contains("\"holderType\":1"), "AccountHolderType::Individual should serialize to 1, got: {}", json);
    }

    #[test]
    fn test_environment_serialization() {
        let mut request = create_test_request();

        // Ecommerce environment
        request.merchant.environment = MerchantEnvironment::Ecommerce;
        let payload: PayrixOnboardingPayload = request.clone().into();
        let json = serde_json::to_string(&payload).unwrap();
        let value: serde_json::Value = serde_json::from_str(&json).unwrap();
        let env = value.get("merchant").unwrap().get("environment").unwrap().as_str().unwrap();
        assert_eq!(env, "ecommerce", "Ecommerce should serialize to 'ecommerce'");

        // CardPresent (retail) environment
        request.merchant.environment = MerchantEnvironment::CardPresent;
        let payload: PayrixOnboardingPayload = request.clone().into();
        let json = serde_json::to_string(&payload).unwrap();
        let value: serde_json::Value = serde_json::from_str(&json).unwrap();
        let env = value.get("merchant").unwrap().get("environment").unwrap().as_str().unwrap();
        assert_eq!(env, "cardPresent", "CardPresent should serialize to 'cardPresent'");

        // Restaurant environment
        request.merchant.environment = MerchantEnvironment::Restaurant;
        let payload: PayrixOnboardingPayload = request.clone().into();
        let json = serde_json::to_string(&payload).unwrap();
        let value: serde_json::Value = serde_json::from_str(&json).unwrap();
        let env = value.get("merchant").unwrap().get("environment").unwrap().as_str().unwrap();
        assert_eq!(env, "restaurant", "Restaurant should serialize to 'restaurant'");

        // MailOrTelephoneOrder (MOTO) environment
        request.merchant.environment = MerchantEnvironment::MailOrTelephoneOrder;
        let payload: PayrixOnboardingPayload = request.into();
        let json = serde_json::to_string(&payload).unwrap();
        let value: serde_json::Value = serde_json::from_str(&json).unwrap();
        let env = value.get("merchant").unwrap().get("environment").unwrap().as_str().unwrap();
        assert_eq!(env, "moto", "MailOrTelephoneOrder should serialize to 'moto'");
    }

    // ============================================================================
    // Edge Case Tests
    // ============================================================================

    #[test]
    fn test_plaid_account_omits_manual_details() {
        let account = BankAccountInfo {
            name: Some("Plaid Verified Account".to_string()),
            routing_number: None,  // No manual entry
            account_number: None,  // No manual entry
            holder_type: AccountHolderType::Business,
            account_method: BankAccountMethod::Checking,
            transaction_type: AccountType::All,
            currency: Some("USD".to_string()),
            is_primary: true,
            plaid_public_token: Some("public-sandbox-token".to_string()),
        };

        let payload: PayrixAccountPayload = account.into();
        let json = serde_json::to_string(&payload).unwrap();

        // Should have public_token but not nested account details
        assert!(json.contains("\"publicToken\":\"public-sandbox-token\""), "Should include publicToken");
        assert!(!json.contains("\"account\":"), "Should not include nested account when using Plaid, got: {}", json);
        assert!(!json.contains("\"routing\":"), "Should not include routing when using Plaid");
        assert!(!json.contains("\"number\":"), "Should not include number when using Plaid");
    }

    #[test]
    fn test_multiple_members_serialization() {
        let mut request = create_test_request();

        // Add a second member (control person)
        request.members.push(MemberInfo {
            member_type: MemberType::ControlPerson,
            first_name: "Jane".to_string(),
            last_name: "Smith".to_string(),
            title: Some("CFO".to_string()),
            ownership_percentage: 0,  // Control persons may not have ownership
            date_of_birth: "19850620".to_string(),
            ssn: "987654321".to_string(),
            email: "jane@example.com".to_string(),
            phone: "5551112222".to_string(),
            address: Address {
                line1: "789 Pine Rd".to_string(),
                line2: None,
                city: "Chicago".to_string(),
                state: "IL".to_string(),
                zip: "60601".to_string(),
                country: "USA".to_string(),
            },
        });

        let payload: PayrixOnboardingPayload = request.into();
        let json = serde_json::to_string(&payload).unwrap();

        let value: serde_json::Value = serde_json::from_str(&json).unwrap();
        let members = value.get("merchant").unwrap().get("members").unwrap().as_array().unwrap();

        assert_eq!(members.len(), 2, "Should have 2 members");

        // Verify first member (Owner)
        assert_eq!(members[0].get("first").unwrap().as_str().unwrap(), "John");
        assert_eq!(members[0].get("type").unwrap().as_i64().unwrap(), 1); // Owner

        // Verify second member (ControlPerson)
        assert_eq!(members[1].get("first").unwrap().as_str().unwrap(), "Jane");
        assert_eq!(members[1].get("type").unwrap().as_i64().unwrap(), 2); // ControlPerson
        assert_eq!(members[1].get("title").unwrap().as_str().unwrap(), "CFO");
    }

    #[test]
    fn test_multiple_accounts_serialization() {
        let mut request = create_test_request();

        // Add trust account
        request.accounts.push(BankAccountInfo {
            name: Some("Trust Account".to_string()),
            routing_number: Some("123456789".to_string()),
            account_number: Some("222222222".to_string()),
            holder_type: AccountHolderType::Business,
            account_method: BankAccountMethod::Checking,
            transaction_type: AccountType::Credit,  // Deposits only
            currency: Some("USD".to_string()),
            is_primary: false,
            plaid_public_token: None,
        });

        let payload: PayrixOnboardingPayload = request.into();
        let json = serde_json::to_string(&payload).unwrap();

        let value: serde_json::Value = serde_json::from_str(&json).unwrap();
        let accounts = value.get("accounts").unwrap().as_array().unwrap();

        assert_eq!(accounts.len(), 2, "Should have 2 accounts");

        // First account is primary (All type)
        assert_eq!(accounts[0].get("primary").unwrap().as_i64().unwrap(), 1);
        assert_eq!(accounts[0].get("type").unwrap().as_str().unwrap(), "all");

        // Second account is trust (Credit only)
        assert_eq!(accounts[1].get("primary").unwrap().as_i64().unwrap(), 0);
        assert_eq!(accounts[1].get("type").unwrap().as_str().unwrap(), "credit");
        assert_eq!(accounts[1].get("name").unwrap().as_str().unwrap(), "Trust Account");
    }

    // ============================================================================
    // Response Parsing Tests
    // ============================================================================

    #[test]
    fn test_payrix_onboarding_response_deserialize() {
        // Test parsing of the nested response structure from Payrix
        // Note: accounts are not included in this response struct because the API
        // returns them with expanded nested objects. We fetch them separately.
        let json = r#"{
            "id": "t1_ent_12345678901234567890123",
            "merchant": {
                "id": "t1_mer_23456789012345678901234",
                "status": 2,
                "entity": "t1_ent_12345678901234567890123",
                "boarded": "20240115"
            }
        }"#;

        let response: PayrixOnboardingResponse = serde_json::from_str(json).unwrap();
        assert_eq!(response.id, "t1_ent_12345678901234567890123");

        let merchant = response.merchant.unwrap();
        assert_eq!(merchant.id, "t1_mer_23456789012345678901234");
        assert_eq!(merchant.status, Some(MerchantStatus::Boarded));
        assert_eq!(merchant.boarded, Some("20240115".to_string()));
    }

    #[test]
    fn test_payrix_onboarding_response_minimal() {
        // Test parsing with minimal response (only id)
        let json = r#"{
            "id": "t1_ent_12345678901234567890123"
        }"#;

        let response: PayrixOnboardingResponse = serde_json::from_str(json).unwrap();
        assert_eq!(response.id, "t1_ent_12345678901234567890123");
        assert!(response.merchant.is_none());
    }

    #[test]
    fn test_merchant_in_response_deserialize() {
        let json = r#"{
            "id": "t1_mer_12345678901234567890123",
            "status": 6,
            "entity": "t1_ent_23456789012345678901234"
        }"#;

        let merchant: MerchantInResponse = serde_json::from_str(json).unwrap();
        assert_eq!(merchant.id, "t1_mer_12345678901234567890123");
        assert_eq!(merchant.status, Some(MerchantStatus::Pending));
        assert_eq!(merchant.entity, Some("t1_ent_23456789012345678901234".to_string()));
        assert!(merchant.boarded.is_none());
        assert!(merchant.members.is_none());
    }

    #[test]
    fn test_merchant_in_response_with_members() {
        let json = r#"{
            "id": "t1_mer_12345678901234567890123",
            "status": 2,
            "members": [
                {
                    "id": "t1_mem_34567890123456789012345",
                    "first": "John",
                    "last": "Doe"
                }
            ]
        }"#;

        let merchant: MerchantInResponse = serde_json::from_str(json).unwrap();
        assert_eq!(merchant.id, "t1_mer_12345678901234567890123");
        let members = merchant.members.unwrap();
        assert_eq!(members.len(), 1);
        assert_eq!(members[0].first, Some("John".to_string()));
        assert_eq!(members[0].last, Some("Doe".to_string()));
    }

    // ============================================================================
    // BoardingStatus Tests
    // ============================================================================

    #[test]
    fn test_boarding_status_all_variants() {
        // Verify all MerchantStatus values map correctly to BoardingStatus
        let test_cases = vec![
            (MerchantStatus::NotReady, BoardingStatus::NotReady),
            (MerchantStatus::Ready, BoardingStatus::Submitted),
            (MerchantStatus::Boarded, BoardingStatus::Boarded),
            (MerchantStatus::Manual, BoardingStatus::ManualReview),
            (MerchantStatus::Closed, BoardingStatus::Closed),
            (MerchantStatus::Incomplete, BoardingStatus::Incomplete),
            (MerchantStatus::Pending, BoardingStatus::Pending),
        ];

        for (merchant_status, expected) in test_cases {
            let actual = BoardingStatus::from(merchant_status);
            assert_eq!(actual, expected, "MerchantStatus::{:?} should map to BoardingStatus::{:?}", merchant_status, expected);
        }
    }

    #[test]
    fn test_boarding_status_equality() {
        assert_eq!(BoardingStatus::Boarded, BoardingStatus::Boarded);
        assert_ne!(BoardingStatus::Boarded, BoardingStatus::Pending);
    }

    #[test]
    fn test_boarding_status_clone() {
        let status = BoardingStatus::ManualReview;
        let cloned = status; // BoardingStatus implements Copy
        assert_eq!(status, cloned);
    }

    #[test]
    fn test_boarding_status_copy() {
        let status = BoardingStatus::Boarded;
        let copied = status; // Copy trait
        assert_eq!(status, copied);
    }

    // ============================================================================
    // OnboardMerchantResult Tests
    // ============================================================================

    #[test]
    fn test_onboard_merchant_result_fields() {
        // Test that OnboardMerchantResult has the expected fields
        // In real usage, this would be populated by the API call

        // Simulate parsing a response JSON to create Entity and Merchant
        let entity_json = r#"{"id": "t1_ent_12345678901234567890123"}"#;
        let merchant_json = r#"{"id": "t1_mer_23456789012345678901234"}"#;

        let entity: Entity = serde_json::from_str(entity_json).unwrap();
        let merchant: Merchant = serde_json::from_str(merchant_json).unwrap();

        let result = OnboardMerchantResult {
            entity_id: entity.id.as_str().to_string(),
            merchant_id: merchant.id.as_str().to_string(),
            boarding_status: BoardingStatus::Boarded,
            entity,
            merchant,
            accounts: vec![],
            members: vec![],
        };

        assert_eq!(result.entity_id, "t1_ent_12345678901234567890123");
        assert_eq!(result.merchant_id, "t1_mer_23456789012345678901234");
        assert_eq!(result.boarding_status, BoardingStatus::Boarded);
        assert!(result.accounts.is_empty());
        assert!(result.members.is_empty());
    }

    // ============================================================================
    // BoardingStatusResult Tests
    // ============================================================================

    #[test]
    fn test_boarding_status_result_structure() {
        let result = BoardingStatusResult {
            status: BoardingStatus::Pending,
            merchant_id: "t1_mer_12345678901234567890123".to_string(),
            entity_id: "t1_ent_23456789012345678901234".to_string(),
            boarded_date: None,
        };

        assert_eq!(result.status, BoardingStatus::Pending);
        assert_eq!(result.merchant_id, "t1_mer_12345678901234567890123");
        assert!(result.boarded_date.is_none());
    }

    #[test]
    fn test_boarding_status_result_with_boarded_date() {
        let result = BoardingStatusResult {
            status: BoardingStatus::Boarded,
            merchant_id: "t1_mer_12345678901234567890123".to_string(),
            entity_id: "t1_ent_23456789012345678901234".to_string(),
            boarded_date: Some("20240115".to_string()),
        };

        assert_eq!(result.status, BoardingStatus::Boarded);
        assert_eq!(result.boarded_date, Some("20240115".to_string()));
    }

    // ============================================================================
    // Validation Edge Case Tests
    // ============================================================================

    #[test]
    fn test_empty_accounts_serialization() {
        let mut request = create_test_request();
        request.accounts = vec![];  // Empty accounts

        let payload: PayrixOnboardingPayload = request.into();
        let json = serde_json::to_string(&payload).unwrap();

        // Should still serialize with empty array
        assert!(json.contains("\"accounts\":[]"), "Empty accounts should serialize to empty array");
    }

    #[test]
    fn test_empty_members_serialization() {
        let mut request = create_test_request();
        request.members = vec![];  // Empty members

        let payload: PayrixOnboardingPayload = request.into();
        let json = serde_json::to_string(&payload).unwrap();

        let value: serde_json::Value = serde_json::from_str(&json).unwrap();
        let merchant = value.get("merchant").unwrap();
        let members = merchant.get("members").unwrap().as_array().unwrap();

        // Should still serialize with empty array
        assert!(members.is_empty(), "Empty members should serialize to empty array");
    }

    #[test]
    fn test_special_characters_in_strings() {
        let mut request = create_test_request();
        request.business.legal_name = "O'Reilly & Sons, LLC \"Test\"".to_string();
        request.business.address.line1 = "123 Main St. #456".to_string();

        let payload: PayrixOnboardingPayload = request.into();
        let json = serde_json::to_string(&payload).unwrap();

        // Should properly escape special characters
        assert!(json.contains("O'Reilly"), "Single quote should be preserved");
        assert!(json.contains("& Sons"), "Ampersand should be preserved");
        assert!(json.contains("#456"), "Hash should be preserved");

        // Verify JSON is valid by parsing it back
        let _: serde_json::Value = serde_json::from_str(&json)
            .expect("JSON with special characters should be valid");
    }

    #[test]
    fn test_unicode_in_strings() {
        let mut request = create_test_request();
        request.business.legal_name = "Café München LLC".to_string();
        request.members[0].first_name = "José".to_string();

        let payload: PayrixOnboardingPayload = request.into();
        let json = serde_json::to_string(&payload).unwrap();

        // Should preserve Unicode characters
        assert!(json.contains("Café"), "Unicode é should be preserved");
        assert!(json.contains("München"), "Unicode ü should be preserved");
        assert!(json.contains("José"), "Unicode é in name should be preserved");
    }

    #[test]
    fn test_max_ownership_percentage() {
        let mut request = create_test_request();
        request.members[0].ownership_percentage = 100;

        let payload: PayrixOnboardingPayload = request.into();
        let json = serde_json::to_string(&payload).unwrap();

        let value: serde_json::Value = serde_json::from_str(&json).unwrap();
        let members = value.get("merchant").unwrap().get("members").unwrap().as_array().unwrap();
        let ownership = members[0].get("ownership").unwrap().as_i64().unwrap();

        assert_eq!(ownership, 100);
    }

    #[test]
    fn test_zero_ownership_percentage() {
        let mut request = create_test_request();
        request.members[0].member_type = MemberType::ControlPerson;
        request.members[0].ownership_percentage = 0;  // Control persons may have 0% ownership

        let payload: PayrixOnboardingPayload = request.into();
        let json = serde_json::to_string(&payload).unwrap();

        let value: serde_json::Value = serde_json::from_str(&json).unwrap();
        let members = value.get("merchant").unwrap().get("members").unwrap().as_array().unwrap();
        let ownership = members[0].get("ownership").unwrap().as_i64().unwrap();

        assert_eq!(ownership, 0);
    }

    #[test]
    fn test_large_annual_sales() {
        let mut request = create_test_request();
        request.merchant.annual_cc_sales = 10_000_000_000; // $100 million in cents

        let payload: PayrixOnboardingPayload = request.into();
        let json = serde_json::to_string(&payload).unwrap();

        let value: serde_json::Value = serde_json::from_str(&json).unwrap();
        let annual_cc_sales = value.get("merchant").unwrap().get("annualCcSales").unwrap().as_i64().unwrap();

        assert_eq!(annual_cc_sales, 10_000_000_000);
    }

    #[test]
    fn test_address_line2_with_apartment() {
        let mut request = create_test_request();
        request.business.address.line2 = Some("Apt 4B, Floor 12".to_string());
        request.members[0].address.line2 = Some("Unit #789".to_string());

        let payload: PayrixOnboardingPayload = request.into();
        let json = serde_json::to_string(&payload).unwrap();

        assert!(json.contains("\"address2\":\"Apt 4B, Floor 12\""), "Business address2 should be present");

        let value: serde_json::Value = serde_json::from_str(&json).unwrap();
        let members = value.get("merchant").unwrap().get("members").unwrap().as_array().unwrap();
        let member_address2 = members[0].get("address2").unwrap().as_str().unwrap();

        assert_eq!(member_address2, "Unit #789");
    }
}