delopay 0.20.0

Official Rust SDK for the DeloPay payments API
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
//! The `connectors` resource: merchant connector accounts, the per-shop
//! bindings between a merchant account and an upstream payment processor.

use std::sync::Arc;

use serde::Serialize;
use serde_json::Value;

use crate::core::encoding::{encode_segment, to_json_vec};
use crate::core::error::{DelopayError, Result};
use crate::core::models::connector::{
    AirwallexApplePayDomainsRegisterResponse, ConnectorBuyerMailResponse,
    ConnectorConsolidationResponse, ConnectorCurrencyConversionSetting,
    ConnectorCurrencyPolicyResponse, ConnectorHealthResponse, ConnectorResponse,
    ConnectorShopsResponse, ConnectorWebhookListResponse, ConnectorWebhookRegisterResponse,
    ConnectorWebhookSyncResponse, ProviderWebhookCreateResponse, ProviderWebhookDeleteResult,
    ProviderWebhookEndpoint, ProviderWebhookListResponse, ProviderWebhookReplacePreviewResponse,
    ProviderWebhookReplaceResponse, StripePaymentMethodDomainsRegisterResponse,
    VaultOutagesResponse, VaultRoutesApplyResponse, VaultRoutesPreviewResponse,
    VaultVerificationResponse, WebhookAddressFormat, WebhookAddressPreviewResponse,
    WebhookAddressResponse, WhopApplePayDomainsRegisterResponse,
};
use crate::core::panes::PanesCatalogResponse;
use crate::http::client::Inner;
use crate::http::transport::HttpMethod;
use crate::resources::ValidateRequest;

/// The `connectors` resource, obtained via [`crate::Delopay::connectors`].
#[derive(Debug, Clone)]
pub struct Connectors {
    inner: Arc<Inner>,
}

impl Connectors {
    pub(crate) fn new(inner: Arc<Inner>) -> Self {
        Self { inner }
    }

    /// Create a connector under a merchant account.
    /// `POST /account/{account_id}/connectors`
    pub async fn create(
        &self,
        account_id: &str,
        params: &ConnectorCreateRequest,
    ) -> Result<ConnectorResponse> {
        params.validate()?;
        let path = format!("/account/{}/connectors", encode_segment(account_id));
        let body = to_json_vec(params)?;
        self.inner
            .request(HttpMethod::Post, &path, Some(&body), &[], None)
            .await
    }

    /// Every connector's pane capabilities, as the router itself knows them —
    /// which rails a connector supports, and which methods it can publish as a
    /// pane, with the confirm routing keys each one carries.
    ///
    /// Capability facts only: no label, sublabel or category comes back. Render
    /// a method's copy from your own locale files, keyed by
    /// [`crate::panes::PaneCapability::key`], and take the routing keys from here verbatim
    /// rather than deriving them.
    ///
    /// This is what the helpers in [`crate::panes`] should be driven from —
    /// [`crate::panes::default_pane`] and [`crate::panes::validate_panes`] both
    /// take a [`crate::panes::PanesConnectorCatalog`] out of this response, so a connector
    /// the router starts publishing panes for needs no SDK release.
    ///
    /// `GET /account/{account_id}/connectors/native-panes/catalog`
    ///
    /// The path keeps the `native-panes` spelling deliberately: the router's
    /// route was never renamed, and pointing at a new name would 404.
    ///
    /// A router predating the endpoint answers 404. That is the case
    /// [`crate::panes::STRIPE_FALLBACK_PANE_CATALOG`] exists for — degrade to
    /// it rather than offering a caller nothing.
    pub async fn panes_catalog(&self, account_id: &str) -> Result<PanesCatalogResponse> {
        let path = format!(
            "/account/{}/connectors/native-panes/catalog",
            encode_segment(account_id)
        );
        self.inner
            .request(HttpMethod::Get, &path, None, &[], None)
            .await
    }

    /// Retrieve one connector.
    /// `GET /account/{account_id}/connectors/{connector_id}`
    ///
    /// The credential-bearing fields come back `null` here whatever is stored:
    /// `connector_webhook_details`, `connector_wallets_details`,
    /// `pm_auth_config` and `additional_merchant_data`. They are dropped
    /// rather than masked, because an editor that prefills from this response
    /// and writes the field back would otherwise save a mask over a live
    /// signing secret. Send one only when an operator typed a new value; an
    /// omitted field leaves the stored one alone.
    ///
    /// This is the retrieve path alone — [`Self::create`] and [`Self::update`]
    /// echo back what the caller sent.
    pub async fn retrieve(
        &self,
        account_id: &str,
        connector_id: &str,
    ) -> Result<ConnectorResponse> {
        let path = format!(
            "/account/{}/connectors/{}",
            encode_segment(account_id),
            encode_segment(connector_id)
        );
        self.inner
            .request(HttpMethod::Get, &path, None, &[], None)
            .await
    }

    /// List a merchant account's connectors.
    /// `GET /account/{account_id}/connectors`
    ///
    /// Never wider than the caller: an API key pinned to one shop lists that
    /// shop's connectors only, not every sibling shop's.
    pub async fn list(&self, account_id: &str) -> Result<Vec<ConnectorResponse>> {
        let path = format!("/account/{}/connectors", encode_segment(account_id));
        self.inner
            .request(HttpMethod::Get, &path, None, &[], None)
            .await
    }

    /// Update a connector.
    /// `POST /account/{account_id}/connectors/{connector_id}`
    pub async fn update(
        &self,
        account_id: &str,
        connector_id: &str,
        params: &ConnectorUpdateRequest,
    ) -> Result<ConnectorResponse> {
        params.validate()?;
        let path = format!(
            "/account/{}/connectors/{}",
            encode_segment(account_id),
            encode_segment(connector_id)
        );
        let body = to_json_vec(params)?;
        self.inner
            .request(HttpMethod::Post, &path, Some(&body), &[], None)
            .await
    }

    /// Delete a connector.
    /// `DELETE /account/{account_id}/connectors/{connector_id}`
    ///
    /// A shop-scoped role may remove a connector of its own shop — the shop is
    /// re-checked server-side — so creating processors and removing them are
    /// one rung of access rather than two.
    pub async fn delete(&self, account_id: &str, connector_id: &str) -> Result<ConnectorResponse> {
        let path = format!(
            "/account/{}/connectors/{}",
            encode_segment(account_id),
            encode_segment(connector_id)
        );
        self.inner
            .request(HttpMethod::Delete, &path, None, &[], None)
            .await
    }

    /// Register a webhook for a connector.
    /// `POST /account/{merchant_id}/connectors/webhooks/{connector_id}`
    ///
    /// Pass `None` to send no body, which the server treats as
    /// `{ "event_type": "all_events" }`; pass
    /// [`ConnectorWebhookRegisterRequest::specific_event`] to scope the
    /// registration to a single event.
    pub async fn register_webhook(
        &self,
        merchant_id: &str,
        connector_id: &str,
        params: Option<&ConnectorWebhookRegisterRequest>,
    ) -> Result<ConnectorWebhookRegisterResponse> {
        let path = format!(
            "/account/{}/connectors/webhooks/{}",
            encode_segment(merchant_id),
            encode_segment(connector_id)
        );
        match params {
            // The TypeScript SDK omits the body entirely when no params are
            // given; the server's default only applies to a bodyless call.
            None => {
                self.inner
                    .request(HttpMethod::Post, &path, None, &[], None)
                    .await
            }
            Some(p) => {
                let body = to_json_vec(p)?;
                self.inner
                    .request(HttpMethod::Post, &path, Some(&body), &[], None)
                    .await
            }
        }
    }

    /// Get the webhooks registered for a connector.
    /// `GET /account/{merchant_id}/connectors/webhooks/{connector_id}`
    pub async fn webhook(
        &self,
        merchant_id: &str,
        connector_id: &str,
    ) -> Result<ConnectorWebhookListResponse> {
        let path = format!(
            "/account/{}/connectors/webhooks/{}",
            encode_segment(merchant_id),
            encode_segment(connector_id)
        );
        self.inner
            .request(HttpMethod::Get, &path, None, &[], None)
            .await
    }

    /// Bring an already-registered webhook's event subscription up to date
    /// with the events Delopay handles.
    /// `POST /account/{merchant_id}/connectors/webhooks/{connector_id}/sync-events`
    ///
    /// A PSP freezes an endpoint's event list at registration time, so an
    /// endpoint created before an event type was added never receives it —
    /// silently, with no error anywhere. [`webhook`](Self::webhook) reports the
    /// gap as
    /// [`missing_events`](crate::core::models::connector::ConnectorWebhookEntry::missing_events);
    /// this repairs it.
    ///
    /// Unlike re-registering, the endpoints are updated **in place**: the
    /// endpoint id and its signing secret are preserved, so signature
    /// verification keeps working across the change. Stripe connectors only;
    /// idempotent, so it is safe on a schedule or after every deploy.
    ///
    /// ```no_run
    /// # use delopay::Delopay;
    /// # async fn run(client: Delopay) -> delopay::Result<()> {
    /// let sync = client
    ///     .connectors()
    ///     .sync_webhook_events("mer_abc", "mca_xyz")
    ///     .await?;
    /// for endpoint in &sync.endpoints {
    ///     match &endpoint.error_message {
    ///         Some(err) => eprintln!("{}: {err}", endpoint.connector_webhook_id),
    ///         None if endpoint.updated => println!("subscribed {:?}", endpoint.added_events),
    ///         None => {}
    ///     }
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub async fn sync_webhook_events(
        &self,
        merchant_id: &str,
        connector_id: &str,
    ) -> Result<ConnectorWebhookSyncResponse> {
        let path = format!(
            "/account/{}/connectors/webhooks/{}/sync-events",
            encode_segment(merchant_id),
            encode_segment(connector_id)
        );
        self.inner
            .request(HttpMethod::Post, &path, None, &[], None)
            .await
    }

    /// What the *processor* says about a connector account: whether it will
    /// accept charges, its capability map, anything it is still waiting on, and
    /// which processor account was asked.
    ///
    /// `GET /account/{account_id}/connectors/{connector_id}/health`
    ///
    /// **This is not a credential check.** That asks whether the stored
    /// credentials work, by running a test-card authorization. A
    /// processor can revoke an account's ability to take payments while the
    /// credentials stay perfectly valid — the key keeps working for the whole
    /// outage while every checkout silently stalls, and a credential check
    /// reports healthy throughout. Only the account's own status carries the
    /// answer.
    ///
    /// A plain read: it costs the merchant nothing, leaves nothing behind, and
    /// is safe to call twice. Pass [`ConnectorHealthParams`] to choose the
    /// credential set or to force a fresh probe instead of a stored one.
    ///
    /// ```no_run
    /// # use delopay::{ConnectorHealthParams, Delopay};
    /// # async fn run(client: Delopay) -> delopay::Result<()> {
    /// let health = client
    ///     .connectors()
    ///     .health("mer_abc", "mca_xyz", Some(&ConnectorHealthParams::new().refresh(true)))
    ///     .await?;
    /// if health.state == "unknown" {
    ///     // Neither good nor bad news — say so, and branch on `unknown_reason`.
    ///     eprintln!("not established: {:?}", health.unknown_reason);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub async fn health(
        &self,
        account_id: &str,
        connector_id: &str,
        params: Option<&ConnectorHealthParams>,
    ) -> Result<ConnectorHealthResponse> {
        let path = format!(
            "/account/{}/connectors/{}/health",
            encode_segment(account_id),
            encode_segment(connector_id)
        );
        let query = params
            .map(ConnectorHealthParams::to_query)
            .unwrap_or_default();
        self.inner
            .request(HttpMethod::Get, &path, None, &query, None)
            .await
    }

    /// Register checkout/shop domains as Apple Pay domains on an Airwallex
    /// account.
    /// `POST /account/{merchant_id}/connectors/{connector_id}/airwallex/apple-pay-domains`
    ///
    /// Apple Pay renders only on a page whose domain the processor has
    /// registered with Apple, and until then the button is hidden with no error
    /// and no console warning. Airwallex connectors only. Idempotent: a host
    /// already on the account is reported without a write.
    ///
    /// One call registers against a single credential set
    /// ([`environment`](AirwallexApplePayDomainsRegisterRequest::environment),
    /// default `"live"`) — call it twice to cover live and sandbox. Per-URL
    /// outcomes come back in
    /// [`results`](AirwallexApplePayDomainsRegisterResponse::results); a result
    /// of `"failed"` usually means the domain is not yet serving the
    /// association file.
    ///
    /// The Airwallex sibling of
    /// [`register_stripe_payment_method_domains`](Self::register_stripe_payment_method_domains).
    pub async fn register_airwallex_apple_pay_domains(
        &self,
        merchant_id: &str,
        connector_id: &str,
        params: &AirwallexApplePayDomainsRegisterRequest,
    ) -> Result<AirwallexApplePayDomainsRegisterResponse> {
        let path = format!(
            "/account/{}/connectors/{}/airwallex/apple-pay-domains",
            encode_segment(merchant_id),
            encode_segment(connector_id)
        );
        let body = to_json_vec(params)?;
        self.inner
            .request(HttpMethod::Post, &path, Some(&body), &[], None)
            .await
    }

    /// Register checkout/shop domains as Stripe *payment method domains*, so
    /// Apple Pay renders on those pages.
    /// `POST /account/{merchant_id}/connectors/{connector_id}/stripe/payment-method-domains`
    ///
    /// Stripe hides the Apple Pay button silently on an unregistered domain, so
    /// a missing registration looks like "Apple Pay is unavailable" rather than
    /// an error. Stripe connectors only. One call registers against a single
    /// credential set
    /// ([`environment`](StripePaymentMethodDomainsRegisterRequest::environment),
    /// default `"live"`) — call it twice to cover live and sandbox. Per-URL
    /// outcomes come back in
    /// [`results`](StripePaymentMethodDomainsRegisterResponse::results); a
    /// missing sandbox credential set is a request-level 400.
    pub async fn register_stripe_payment_method_domains(
        &self,
        merchant_id: &str,
        connector_id: &str,
        params: &StripePaymentMethodDomainsRegisterRequest,
    ) -> Result<StripePaymentMethodDomainsRegisterResponse> {
        let path = format!(
            "/account/{}/connectors/{}/stripe/payment-method-domains",
            encode_segment(merchant_id),
            encode_segment(connector_id)
        );
        let body = to_json_vec(params)?;
        self.inner
            .request(HttpMethod::Post, &path, Some(&body), &[], None)
            .await
    }

    /// List the payment methods the platform supports.
    /// `GET /account/payment-methods`
    pub async fn list_payment_methods(&self) -> Result<Vec<Value>> {
        self.inner
            .request(HttpMethod::Get, "/account/payment-methods", None, &[], None)
            .await
    }

    /// List the connectors of the caller's own shop.
    /// `GET /account/{account_id}/profile/connectors`
    ///
    /// The shop-scoped counterpart of [`list`](Self::list): the merchant-wide
    /// list answers 403 to a shop user's dashboard token, while this one is
    /// scoped server-side to the caller's shop.
    pub async fn list_by_profile(&self, account_id: &str) -> Result<Vec<ConnectorResponse>> {
        let path = format!("/account/{}/profile/connectors", encode_segment(account_id));
        self.inner
            .request(HttpMethod::Get, &path, None, &[], None)
            .await
    }

    /// Read the connected provider account's optional buyer-email preference.
    /// `GET /account/{merchant_id}/connectors/{connector_id}/buyer-email-preference?test_mode=`
    ///
    /// Currently supported for Whop, and only with a merchant dashboard token
    /// holding connector edit authority. `test_mode` selects the credential
    /// set explicitly: `true` for sandbox, `false` for live. The preference
    /// applies to every shop sharing the provider account; it does not switch
    /// off mandatory provider messages or invoice delivery.
    pub async fn retrieve_buyer_email_preference(
        &self,
        merchant_id: &str,
        connector_id: &str,
        test_mode: bool,
    ) -> Result<ConnectorBuyerMailResponse> {
        let path = connector_path(merchant_id, connector_id, "/buyer-email-preference");
        let query = [("test_mode", test_mode.to_string())];
        self.inner
            .request(HttpMethod::Get, &path, None, &query, None)
            .await
    }

    /// Change the buyer-email preference for the whole provider account.
    /// `PUT /account/{merchant_id}/connectors/{connector_id}/buyer-email-preference`
    ///
    /// Send the account, credential set and value read before asking for
    /// confirmation: a changed account or preference is refused before
    /// anything changes. Inspect
    /// [`outcome`](ConnectorBuyerMailResponse::outcome): only `"verified"`
    /// confirms the new value, and a 200 can also report a conflict, refusal
    /// or unknown outcome. After an uncertain outcome, or a transport error,
    /// read the preference again before retrying.
    pub async fn update_buyer_email_preference(
        &self,
        merchant_id: &str,
        connector_id: &str,
        params: &ConnectorBuyerMailUpdateRequest,
    ) -> Result<ConnectorBuyerMailResponse> {
        let path = connector_path(merchant_id, connector_id, "/buyer-email-preference");
        let body = to_json_vec(params)?;
        self.inner
            .request_body_keyed_with_query(HttpMethod::Put, &path, Some(&body), &[], None)
            .await
    }

    /// Share a connector with more shops of the same merchant.
    /// `POST /account/{account_id}/connectors/{connector_id}/shops`
    ///
    /// Nothing is copied: every shop sends payments to the same account, on
    /// the same credentials and webhook, and the account's limits count them
    /// all.
    pub async fn add_shops(
        &self,
        account_id: &str,
        connector_id: &str,
        params: &ConnectorShopsAddRequest,
    ) -> Result<ConnectorShopsResponse> {
        let path = connector_path(account_id, connector_id, "/shops");
        let body = to_json_vec(params)?;
        self.inner
            .request_body_keyed_with_query(HttpMethod::Post, &path, Some(&body), &[], None)
            .await
    }

    /// Fold copies of the same provider account into this connector.
    /// `POST /account/{account_id}/connectors/{connector_id}/consolidate`
    ///
    /// The copies' shops move to the connector with their on/off state,
    /// routing, checkout layout, currencies, saved credentials, mandates and
    /// subscriptions. A copy keeps answering for the payments made on it and
    /// serves no shop. Send `dry_run(true)` first, then confirm with the
    /// preview's `preview_token` and a choice for every conflict.
    pub async fn consolidate(
        &self,
        account_id: &str,
        connector_id: &str,
        params: &ConnectorConsolidationRequest,
    ) -> Result<ConnectorConsolidationResponse> {
        params.validate()?;
        let path = connector_path(account_id, connector_id, "/consolidate");
        let body = to_json_vec(params)?;
        self.inner
            .request_body_keyed_with_query(HttpMethod::Post, &path, Some(&body), &[], None)
            .await
    }

    /// Switch a connector off, or back on, in one shop it serves.
    /// `POST /account/{account_id}/connectors/{connector_id}/shops/{profile_id}`
    pub async fn set_shop_disabled(
        &self,
        account_id: &str,
        connector_id: &str,
        profile_id: &str,
        params: &ConnectorShopUpdateRequest,
    ) -> Result<ConnectorShopsResponse> {
        params.validate()?;
        let path = connector_shop_path(account_id, connector_id, profile_id, "");
        let body = to_json_vec(params)?;
        self.inner
            .request_body_keyed_with_query(HttpMethod::Post, &path, Some(&body), &[], None)
            .await
    }

    /// Stop a connector serving one shop.
    /// `DELETE /account/{account_id}/connectors/{connector_id}/shops/{profile_id}`
    ///
    /// Any shop may leave, the one the connector was created in included,
    /// while another one stays. The last shop is refused: delete the
    /// connector instead. The account, its limits and every other shop on it
    /// are unaffected.
    pub async fn remove_shop(
        &self,
        account_id: &str,
        connector_id: &str,
        profile_id: &str,
    ) -> Result<ConnectorShopsResponse> {
        let path = connector_shop_path(account_id, connector_id, profile_id, "");
        self.inner
            .request_body_keyed_with_query(HttpMethod::Delete, &path, None, &[], None)
            .await
    }

    /// Read the transaction currencies a connector may process: its own list,
    /// what the provider is known to accept, and the effective currencies in
    /// each shop it serves.
    /// `GET /account/{account_id}/connectors/{connector_id}/currencies`
    pub async fn currencies(
        &self,
        account_id: &str,
        connector_id: &str,
    ) -> Result<ConnectorCurrencyPolicyResponse> {
        let path = connector_path(account_id, connector_id, "/currencies");
        self.inner
            .request(HttpMethod::Get, &path, None, &[], None)
            .await
    }

    /// Set the transaction currencies a connector may process in every shop
    /// it serves, and what it does with a payment in a currency it does not
    /// take.
    /// `PUT /account/{account_id}/connectors/{connector_id}/currencies`
    ///
    /// A field left unset stays as it is. With `dry_run(true)` nothing is
    /// saved and [`impact`](ConnectorCurrencyPolicyResponse::impact) reports
    /// the effect.
    pub async fn set_currencies(
        &self,
        account_id: &str,
        connector_id: &str,
        params: &ConnectorCurrencyPolicyUpdateRequest,
    ) -> Result<ConnectorCurrencyPolicyResponse> {
        params.validate()?;
        let path = connector_path(account_id, connector_id, "/currencies");
        let body = to_json_vec(params)?;
        self.inner
            .request_body_keyed_with_query(HttpMethod::Put, &path, Some(&body), &[], None)
            .await
    }

    /// Narrow a connector's currencies in one shop it serves, within the
    /// connector's own list, or set the shop's own conversion.
    /// `PUT /account/{account_id}/connectors/{connector_id}/shops/{profile_id}/currencies`
    ///
    /// Sending `null` (see
    /// [`follow_account_currencies`](ConnectorCurrencyPolicyUpdateRequest::follow_account_currencies)
    /// and
    /// [`follow_account_conversion`](ConnectorCurrencyPolicyUpdateRequest::follow_account_conversion))
    /// returns the shop to the connector's setting; a field left unset stays
    /// as it is.
    pub async fn set_shop_currencies(
        &self,
        account_id: &str,
        connector_id: &str,
        profile_id: &str,
        params: &ConnectorCurrencyPolicyUpdateRequest,
    ) -> Result<ConnectorCurrencyPolicyResponse> {
        params.validate()?;
        let path = connector_shop_path(account_id, connector_id, profile_id, "/currencies");
        let body = to_json_vec(params)?;
        self.inner
            .request_body_keyed_with_query(HttpMethod::Put, &path, Some(&body), &[], None)
            .await
    }

    /// Run the configuration checks of a vault connector account: credential
    /// validity, write-only collect scope, reachability, environment
    /// coherence and route coverage.
    /// `POST /account/{account_id}/connectors/{connector_id}/vault/verify`
    ///
    /// Writes nothing, but is not cheap: it calls the vault provider.
    pub async fn verify_vault(
        &self,
        account_id: &str,
        connector_id: &str,
        params: &VaultVerifyRequest,
    ) -> Result<VaultVerificationResponse> {
        let path = connector_path(account_id, connector_id, "/vault/verify");
        let body = to_json_vec(params)?;
        self.inner
            .request_body_keyed_with_query(HttpMethod::Post, &path, Some(&body), &[], None)
            .await
    }

    /// The shops whose card vault is switched on and whose vault account has
    /// stopped working, each with the cause.
    /// `GET /account/{account_id}/vault/outages`
    ///
    /// While a shop is listed, its card form cannot be shown and its card
    /// payments fail. An outage is listed once the vault has refused the
    /// account several times in a row over at least a minute, and is removed
    /// when the vault serves the account again. Nothing switches a vault off
    /// by itself.
    pub async fn vault_outages(&self, account_id: &str) -> Result<VaultOutagesResponse> {
        let path = format!("/account/{}/vault/outages", encode_segment(account_id));
        self.inner
            .request(HttpMethod::Get, &path, None, &[], None)
            .await
    }

    /// Compute the route document a vault connector should have and diff it
    /// against what exists, without writing anything.
    /// `POST /account/{account_id}/connectors/{connector_id}/vault/routes/preview`
    ///
    /// Echo both returned fingerprints byte for byte to
    /// [`apply_vault_routes`](Self::apply_vault_routes). A 404 means the API
    /// cannot configure routes, not that there is nothing to change.
    pub async fn preview_vault_routes(
        &self,
        account_id: &str,
        connector_id: &str,
        params: &VaultRoutesPreviewRequest,
    ) -> Result<VaultRoutesPreviewResponse> {
        params.validate()?;
        let path = connector_path(account_id, connector_id, "/vault/routes/preview");
        let body = to_json_vec(params)?;
        self.inner
            .request_body_keyed_with_query(HttpMethod::Post, &path, Some(&body), &[], None)
            .await
    }

    /// Write the routes just previewed.
    /// `POST /account/{account_id}/connectors/{connector_id}/vault/routes/apply`
    ///
    /// A 409 (`DE_04`) means the vault changed since the preview and nothing
    /// was written: preview again.
    pub async fn apply_vault_routes(
        &self,
        account_id: &str,
        connector_id: &str,
        params: &VaultRoutesApplyRequest,
    ) -> Result<VaultRoutesApplyResponse> {
        params.validate()?;
        let path = connector_path(account_id, connector_id, "/vault/routes/apply");
        let body = to_json_vec(params)?;
        self.inner
            .request_body_keyed_with_query(HttpMethod::Post, &path, Some(&body), &[], None)
            .await
    }

    /// Register and verify checkout/shop domains as Whop Apple Pay payment
    /// method domains, so Apple Pay renders in Whop's embedded card form.
    /// `POST /account/{merchant_id}/connectors/{connector_id}/whop/apple-pay-domains`
    ///
    /// Whop connectors only. One call registers against a single credential
    /// set (default `"live"`): call it twice to cover live and sandbox. A host
    /// already verified comes back `"already_verified"` without a write; a
    /// `"pending"` one is verified again.
    pub async fn register_whop_apple_pay_domains(
        &self,
        merchant_id: &str,
        connector_id: &str,
        params: &WhopApplePayDomainsRegisterRequest,
    ) -> Result<WhopApplePayDomainsRegisterResponse> {
        let path = connector_path(merchant_id, connector_id, "/whop/apple-pay-domains");
        let body = to_json_vec(params)?;
        self.inner
            .request_body_keyed_with_query(HttpMethod::Post, &path, Some(&body), &[], None)
            .await
    }

    /// Read the callback addresses of a connector's payment provider.
    /// `GET /account/{merchant_id}/connectors/webhooks/{connector_id}/address`
    ///
    /// One entry per environment. Providers whose webhooks are neither managed
    /// nor hand-configured are refused with a 400.
    pub async fn webhook_address(
        &self,
        merchant_id: &str,
        connector_id: &str,
    ) -> Result<WebhookAddressResponse> {
        let path = webhook_path(merchant_id, connector_id, "/address");
        self.inner
            .request(HttpMethod::Get, &path, None, &[], None)
            .await
    }

    /// Validate a proposed callback address without saving it.
    /// `POST /account/{merchant_id}/connectors/webhooks/{connector_id}/address/preview`
    ///
    /// Needs the same permission as saving.
    pub async fn preview_webhook_address(
        &self,
        merchant_id: &str,
        connector_id: &str,
        params: &WebhookAddressRequest,
    ) -> Result<WebhookAddressPreviewResponse> {
        params.validate()?;
        let path = webhook_path(merchant_id, connector_id, "/address/preview");
        let body = to_json_vec(params)?;
        self.inner
            .request_body_keyed_with_query(HttpMethod::Post, &path, Some(&body), &[], None)
            .await
    }

    /// Save the callback address of a connector's payment provider for one
    /// environment.
    /// `PUT /account/{merchant_id}/connectors/webhooks/{connector_id}/address`
    ///
    /// The address applies to every connector account of that provider and
    /// environment, so `confirm_shared(true)` is required when other accounts
    /// are affected. A refused proposal answers 422 `IR_06`; a save that lost
    /// to a concurrent change answers 422 `HE_00` and can be repeated; a
    /// caller who may not edit every affected account gets 403.
    pub async fn update_webhook_address(
        &self,
        merchant_id: &str,
        connector_id: &str,
        params: &WebhookAddressRequest,
    ) -> Result<WebhookAddressResponse> {
        params.validate()?;
        let path = webhook_path(merchant_id, connector_id, "/address");
        let body = to_json_vec(params)?;
        self.inner
            .request_body_keyed_with_query(HttpMethod::Put, &path, Some(&body), &[], None)
            .await
    }

    /// Every webhook the connector's payment provider lists for its
    /// credentials in one environment (`"live"` or `"sandbox"`).
    /// `GET /account/{merchant_id}/connectors/webhooks/{connector_id}/provider?environment=`
    ///
    /// Destinations are masked.
    pub async fn list_provider_webhooks(
        &self,
        merchant_id: &str,
        connector_id: &str,
        environment: &str,
    ) -> Result<ProviderWebhookListResponse> {
        let path = webhook_path(merchant_id, connector_id, "/provider");
        let query = [("environment", environment.to_string())];
        self.inner
            .request(HttpMethod::Get, &path, None, &query, None)
            .await
    }

    /// Create a webhook at the provider for the merchant's own systems.
    /// `POST /account/{merchant_id}/connectors/webhooks/{connector_id}/provider`
    ///
    /// The URL must be `https` and point outside the platform. A returned
    /// [`signing_secret`](ProviderWebhookCreateResponse::signing_secret) is
    /// not kept and cannot be read again.
    pub async fn create_provider_webhook(
        &self,
        merchant_id: &str,
        connector_id: &str,
        params: &ProviderWebhookCreateRequest,
    ) -> Result<ProviderWebhookCreateResponse> {
        let path = webhook_path(merchant_id, connector_id, "/provider");
        let body = to_json_vec(params)?;
        self.inner
            .request_body_keyed_with_query(HttpMethod::Post, &path, Some(&body), &[], None)
            .await
    }

    /// Change one webhook at the provider.
    /// `PATCH /account/{merchant_id}/connectors/webhooks/{connector_id}/provider/{webhook_id}`
    ///
    /// Refused once the webhook changed since `fingerprint`, and for the
    /// platform's own webhooks.
    pub async fn update_provider_webhook(
        &self,
        merchant_id: &str,
        connector_id: &str,
        webhook_id: &str,
        params: &ProviderWebhookUpdateRequest,
    ) -> Result<ProviderWebhookEndpoint> {
        let suffix = format!("/provider/{}", encode_segment(webhook_id));
        let path = webhook_path(merchant_id, connector_id, &suffix);
        let body = to_json_vec(params)?;
        self.inner
            .request_body_keyed_with_query(HttpMethod::Patch, &path, Some(&body), &[], None)
            .await
    }

    /// Delete one webhook at the provider.
    /// `POST /account/{merchant_id}/connectors/webhooks/{connector_id}/provider/{webhook_id}/delete`
    ///
    /// Refused once the webhook changed since `fingerprint`. Deleting the
    /// platform's own webhook needs `confirm_managed`; another connector
    /// account's is never deleted from here.
    pub async fn delete_provider_webhook(
        &self,
        merchant_id: &str,
        connector_id: &str,
        webhook_id: &str,
        params: &ProviderWebhookDeleteRequest,
    ) -> Result<ProviderWebhookDeleteResult> {
        let suffix = format!("/provider/{}/delete", encode_segment(webhook_id));
        let path = webhook_path(merchant_id, connector_id, &suffix);
        let body = to_json_vec(params)?;
        self.inner
            .request_body_keyed_with_query(HttpMethod::Post, &path, Some(&body), &[], None)
            .await
    }

    /// What replacing every webhook with the platform's own would delete and
    /// keep, in one environment (`"live"` or `"sandbox"`). Nothing is
    /// changed.
    /// `GET /account/{merchant_id}/connectors/webhooks/{connector_id}/provider/replace?environment=`
    pub async fn preview_provider_webhook_replace(
        &self,
        merchant_id: &str,
        connector_id: &str,
        environment: &str,
    ) -> Result<ProviderWebhookReplacePreviewResponse> {
        let path = webhook_path(merchant_id, connector_id, "/provider/replace");
        let query = [("environment", environment.to_string())];
        self.inner
            .request(HttpMethod::Get, &path, None, &query, None)
            .await
    }

    /// Keep only the platform's webhook: delete exactly the confirmed
    /// webhooks of the preview, after registering the platform's own unless
    /// the preview's `sequence` is `delete_first`.
    /// `POST /account/{merchant_id}/connectors/webhooks/{connector_id}/provider/replace`
    ///
    /// A list that changed since the preview answers `scope_changed` and
    /// deletes nothing. A second replacement while one runs is refused as
    /// busy (`HE_00`).
    pub async fn replace_provider_webhooks(
        &self,
        merchant_id: &str,
        connector_id: &str,
        params: &ProviderWebhookReplaceRequest,
    ) -> Result<ProviderWebhookReplaceResponse> {
        let path = webhook_path(merchant_id, connector_id, "/provider/replace");
        let body = to_json_vec(params)?;
        self.inner
            .request_body_keyed_with_query(HttpMethod::Post, &path, Some(&body), &[], None)
            .await
    }
}

/// `/account/{account_id}/connectors/{connector_id}{suffix}`, percent-encoded.
fn connector_path(account_id: &str, connector_id: &str, suffix: &str) -> String {
    format!(
        "/account/{}/connectors/{}{suffix}",
        encode_segment(account_id),
        encode_segment(connector_id)
    )
}

/// `/account/{account_id}/connectors/{connector_id}/shops/{profile_id}{suffix}`.
fn connector_shop_path(
    account_id: &str,
    connector_id: &str,
    profile_id: &str,
    suffix: &str,
) -> String {
    format!(
        "{}/{}{suffix}",
        connector_path(account_id, connector_id, "/shops"),
        encode_segment(profile_id)
    )
}

/// `/account/{merchant_id}/connectors/webhooks/{connector_id}{suffix}`.
fn webhook_path(merchant_id: &str, connector_id: &str, suffix: &str) -> String {
    format!(
        "/account/{}/connectors/webhooks/{}{suffix}",
        encode_segment(merchant_id),
        encode_segment(connector_id)
    )
}

/// Reject an `extra` key that collides with one of `named`.
fn reject_extra_collisions(
    extra: &serde_json::Map<String, Value>,
    named: &[&str],
    type_name: &str,
) -> Result<()> {
    for key in extra.keys() {
        if named.contains(&key.as_str()) {
            return Err(DelopayError::InvalidRequest(format!(
                "`extra` key `{key}` collides with a named field on {type_name}"
            )));
        }
    }
    Ok(())
}

/// Parameters for [`Connectors::update_buyer_email_preference`].
///
/// Every field is required: the change is refused unless it names the exact
/// account and value read before confirmation.
#[derive(Debug, Clone, Serialize)]
pub struct ConnectorBuyerMailUpdateRequest {
    /// The credential set read: `true` for sandbox, `false` for live.
    pub test_mode: bool,
    /// The exact provider account read before asking for confirmation.
    pub expected_provider_account_id: String,
    /// The requested preference.
    pub send_customer_emails: bool,
    /// The value the provider reported before, not the requested one.
    pub expected_send_customer_emails: bool,
    /// Must be `true`: authorizes the change for every shop sharing the
    /// account.
    pub confirmed_account_wide: bool,
}

impl ConnectorBuyerMailUpdateRequest {
    /// A change from `expected_send_customer_emails` to
    /// `send_customer_emails` on the provider account read, confirmed for
    /// every shop sharing it.
    pub fn new(
        test_mode: bool,
        expected_provider_account_id: impl Into<String>,
        expected_send_customer_emails: bool,
        send_customer_emails: bool,
    ) -> Self {
        Self {
            test_mode,
            expected_provider_account_id: expected_provider_account_id.into(),
            send_customer_emails,
            expected_send_customer_emails,
            confirmed_account_wide: true,
        }
    }
}

/// Parameters for [`Connectors::add_shops`].
#[derive(Debug, Clone, Default, Serialize)]
pub struct ConnectorShopsAddRequest {
    /// The shops to add. Each must belong to the connector's merchant and not
    /// be served by the connector yet.
    pub profile_ids: Vec<String>,
}

impl ConnectorShopsAddRequest {
    /// Add the given shops.
    pub fn new<I, S>(profile_ids: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        Self {
            profile_ids: profile_ids.into_iter().map(Into::into).collect(),
        }
    }
}

/// Parameters for [`Connectors::consolidate`].
#[derive(Debug, Clone, Default, Serialize)]
pub struct ConnectorConsolidationRequest {
    /// The copies to fold into the connector.
    pub merchant_connector_ids: Vec<String>,
    /// Describe the consolidation and write nothing.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub dry_run: Option<bool>,
    /// The `preview_token` of the preview being confirmed. Required to
    /// confirm.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub preview_token: Option<String>,
    /// For each conflicting setting, the account whose value is kept.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub choices: Option<std::collections::BTreeMap<String, String>>,
    /// Any additional fields, merged verbatim.
    #[serde(flatten, skip_serializing_if = "serde_json::Map::is_empty")]
    pub extra: serde_json::Map<String, Value>,
}

impl ConnectorConsolidationRequest {
    /// Fold the given copies into the connector.
    pub fn new<I, S>(merchant_connector_ids: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        Self {
            merchant_connector_ids: merchant_connector_ids.into_iter().map(Into::into).collect(),
            ..Default::default()
        }
    }

    /// Preview only (`true`) or apply (`false`).
    #[must_use]
    pub fn dry_run(mut self, dry_run: bool) -> Self {
        self.dry_run = Some(dry_run);
        self
    }

    /// Confirm the preview that returned this token.
    #[must_use]
    pub fn preview_token(mut self, preview_token: impl Into<String>) -> Self {
        self.preview_token = Some(preview_token.into());
        self
    }

    /// Keep `merchant_connector_id`'s value of `setting` (e.g. `"label"`).
    #[must_use]
    pub fn choice(
        mut self,
        setting: impl Into<String>,
        merchant_connector_id: impl Into<String>,
    ) -> Self {
        self.choices
            .get_or_insert_with(Default::default)
            .insert(setting.into(), merchant_connector_id.into());
        self
    }
}

/// Names of `ConnectorConsolidationRequest`'s fields as they appear on the
/// wire (`extra` excluded).
const CONNECTOR_CONSOLIDATION_REQUEST_NAMED: &[&str] = &[
    "merchant_connector_ids",
    "dry_run",
    "preview_token",
    "choices",
];

impl ValidateRequest for ConnectorConsolidationRequest {
    fn validate(&self) -> Result<()> {
        reject_extra_collisions(
            &self.extra,
            CONNECTOR_CONSOLIDATION_REQUEST_NAMED,
            "ConnectorConsolidationRequest",
        )
    }
}

/// Parameters for [`Connectors::set_shop_disabled`].
#[derive(Debug, Clone, Default, Serialize)]
pub struct ConnectorShopUpdateRequest {
    /// `true` switches the connector off in the shop, `false` back on.
    pub disabled: bool,
    /// Why, for the audit log.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub reason: Option<String>,
    /// Any additional fields, merged verbatim.
    #[serde(flatten, skip_serializing_if = "serde_json::Map::is_empty")]
    pub extra: serde_json::Map<String, Value>,
}

impl ConnectorShopUpdateRequest {
    /// Switch the connector off (`true`) or back on (`false`) in the shop.
    pub fn new(disabled: bool) -> Self {
        Self {
            disabled,
            ..Default::default()
        }
    }

    /// Record why.
    #[must_use]
    pub fn reason(mut self, reason: impl Into<String>) -> Self {
        self.reason = Some(reason.into());
        self
    }
}

/// Names of `ConnectorShopUpdateRequest`'s fields as they appear on the wire
/// (`extra` excluded).
const CONNECTOR_SHOP_UPDATE_REQUEST_NAMED: &[&str] = &["disabled", "reason"];

impl ValidateRequest for ConnectorShopUpdateRequest {
    fn validate(&self) -> Result<()> {
        reject_extra_collisions(
            &self.extra,
            CONNECTOR_SHOP_UPDATE_REQUEST_NAMED,
            "ConnectorShopUpdateRequest",
        )
    }
}

/// Parameters for [`Connectors::set_currencies`] and
/// [`Connectors::set_shop_currencies`]. A field left unset is not sent and
/// stays as it is.
///
/// Both fields are three-state: unset (not sent), `null`, or a value. `null`
/// is not "none": on the connector it allows every currency the provider
/// supports (or refuses untaken currencies, for `conversion`); on a shop it
/// returns the shop to the connector's setting.
#[derive(Debug, Clone, Default, Serialize)]
pub struct ConnectorCurrencyPolicyUpdateRequest {
    /// At least one ISO 4217 currency, or `null`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub allowed_currencies: Option<Option<Vec<String>>>,
    /// What the connector does with a payment in a currency it does not
    /// take, or `null`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub conversion: Option<Option<ConnectorCurrencyConversionSetting>>,
    /// Validate and report the impact without saving.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub dry_run: Option<bool>,
    /// Any additional fields, merged verbatim.
    #[serde(flatten, skip_serializing_if = "serde_json::Map::is_empty")]
    pub extra: serde_json::Map<String, Value>,
}

impl ConnectorCurrencyPolicyUpdateRequest {
    /// An empty update; set the fields you want changed.
    pub fn new() -> Self {
        Self::default()
    }

    /// Allow exactly these currencies (at least one).
    #[must_use]
    pub fn allowed_currencies<I, S>(mut self, currencies: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.allowed_currencies = Some(Some(currencies.into_iter().map(Into::into).collect()));
        self
    }

    /// Send `allowed_currencies: null`. On the connector this allows every
    /// currency the provider supports.
    #[must_use]
    pub fn allow_every_currency(mut self) -> Self {
        self.allowed_currencies = Some(None);
        self
    }

    /// Send `allowed_currencies: null` on the shop route: the shop follows
    /// the connector's list again.
    #[must_use]
    pub fn follow_account_currencies(self) -> Self {
        self.allow_every_currency()
    }

    /// Set the conversion setting.
    #[must_use]
    pub fn conversion(mut self, conversion: ConnectorCurrencyConversionSetting) -> Self {
        self.conversion = Some(Some(conversion));
        self
    }

    /// Send `conversion: null`. On the connector this refuses payments in an
    /// untaken currency; on a shop it follows the connector's setting again.
    #[must_use]
    pub fn follow_account_conversion(mut self) -> Self {
        self.conversion = Some(None);
        self
    }

    /// Validate and report the impact without saving.
    #[must_use]
    pub fn dry_run(mut self, dry_run: bool) -> Self {
        self.dry_run = Some(dry_run);
        self
    }
}

/// Names of `ConnectorCurrencyPolicyUpdateRequest`'s fields as they appear on
/// the wire (`extra` excluded).
const CONNECTOR_CURRENCY_POLICY_UPDATE_REQUEST_NAMED: &[&str] =
    &["allowed_currencies", "conversion", "dry_run"];

impl ValidateRequest for ConnectorCurrencyPolicyUpdateRequest {
    fn validate(&self) -> Result<()> {
        reject_extra_collisions(
            &self.extra,
            CONNECTOR_CURRENCY_POLICY_UPDATE_REQUEST_NAMED,
            "ConnectorCurrencyPolicyUpdateRequest",
        )
    }
}

/// Parameters for [`Connectors::verify_vault`].
#[derive(Debug, Clone, Default, Serialize)]
pub struct VaultVerifyRequest {
    /// The shop whose vault is checked.
    pub profile_id: String,
}

impl VaultVerifyRequest {
    /// Check the vault of this shop.
    pub fn new(profile_id: impl Into<String>) -> Self {
        Self {
            profile_id: profile_id.into(),
        }
    }
}

/// Parameters for [`Connectors::preview_vault_routes`].
#[derive(Debug, Clone, Default, Serialize)]
pub struct VaultRoutesPreviewRequest {
    /// The shop whose vault routes are previewed.
    pub profile_id: String,
    /// `"sandbox"` or `"live"`; unset derives it from the credentials.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub environment: Option<String>,
    /// Any additional fields, merged verbatim.
    #[serde(flatten, skip_serializing_if = "serde_json::Map::is_empty")]
    pub extra: serde_json::Map<String, Value>,
}

impl VaultRoutesPreviewRequest {
    /// Preview the routes of this shop's vault.
    pub fn new(profile_id: impl Into<String>) -> Self {
        Self {
            profile_id: profile_id.into(),
            ..Default::default()
        }
    }

    /// Preview the `"sandbox"` or `"live"` vault.
    #[must_use]
    pub fn environment(mut self, environment: impl Into<String>) -> Self {
        self.environment = Some(environment.into());
        self
    }
}

/// Names of `VaultRoutesPreviewRequest`'s fields as they appear on the wire
/// (`extra` excluded).
const VAULT_ROUTES_PREVIEW_REQUEST_NAMED: &[&str] = &["profile_id", "environment"];

impl ValidateRequest for VaultRoutesPreviewRequest {
    fn validate(&self) -> Result<()> {
        reject_extra_collisions(
            &self.extra,
            VAULT_ROUTES_PREVIEW_REQUEST_NAMED,
            "VaultRoutesPreviewRequest",
        )
    }
}

/// Parameters for [`Connectors::apply_vault_routes`].
///
/// `expected_current_fingerprint` is always sent: `null` means "the preview
/// found no routes" and is a value; an absent key is refused.
#[derive(Debug, Clone, Default, Serialize)]
pub struct VaultRoutesApplyRequest {
    /// The shop whose vault routes are written.
    pub profile_id: String,
    /// `"sandbox"` or `"live"`; unset derives it from the credentials.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub environment: Option<String>,
    /// The preview's `current_fingerprint`, byte for byte.
    pub expected_current_fingerprint: Option<String>,
    /// The preview's `desired_fingerprint`, byte for byte.
    pub expected_desired_fingerprint: String,
    /// Any additional fields, merged verbatim.
    #[serde(flatten, skip_serializing_if = "serde_json::Map::is_empty")]
    pub extra: serde_json::Map<String, Value>,
}

impl VaultRoutesApplyRequest {
    /// Apply the preview whose fingerprints are given.
    pub fn new(
        profile_id: impl Into<String>,
        expected_current_fingerprint: Option<String>,
        expected_desired_fingerprint: impl Into<String>,
    ) -> Self {
        Self {
            profile_id: profile_id.into(),
            environment: None,
            expected_current_fingerprint,
            expected_desired_fingerprint: expected_desired_fingerprint.into(),
            extra: serde_json::Map::new(),
        }
    }

    /// Write the `"sandbox"` or `"live"` vault's routes.
    #[must_use]
    pub fn environment(mut self, environment: impl Into<String>) -> Self {
        self.environment = Some(environment.into());
        self
    }
}

/// Names of `VaultRoutesApplyRequest`'s fields as they appear on the wire
/// (`extra` excluded).
const VAULT_ROUTES_APPLY_REQUEST_NAMED: &[&str] = &[
    "profile_id",
    "environment",
    "expected_current_fingerprint",
    "expected_desired_fingerprint",
];

impl ValidateRequest for VaultRoutesApplyRequest {
    fn validate(&self) -> Result<()> {
        reject_extra_collisions(
            &self.extra,
            VAULT_ROUTES_APPLY_REQUEST_NAMED,
            "VaultRoutesApplyRequest",
        )
    }
}

/// Parameters for [`Connectors::register_whop_apple_pay_domains`].
///
/// `urls` is serialized even when empty: an empty list is a caller mistake the
/// server should reject explicitly.
#[derive(Debug, Clone, Default, Serialize)]
pub struct WhopApplePayDomainsRegisterRequest {
    /// Absolute URLs (or bare hostnames) whose hosts are registered — the
    /// hosted-checkout origin first, plus any of the merchant's own shop URLs.
    /// At most 10 per request.
    pub urls: Vec<String>,
    /// Credential set to register with: `"live"` or `"sandbox"`. Defaults to
    /// `"live"` server-side.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub environment: Option<String>,
}

impl WhopApplePayDomainsRegisterRequest {
    /// Register the given URLs against the connector's live credential set.
    pub fn new<I, S>(urls: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        Self {
            urls: urls.into_iter().map(Into::into).collect(),
            environment: None,
        }
    }

    /// Register against the `"live"` or `"sandbox"` credential set.
    #[must_use]
    pub fn environment(mut self, environment: impl Into<String>) -> Self {
        self.environment = Some(environment.into());
        self
    }
}

/// A proposed callback address for one provider and environment. Parameters
/// for [`Connectors::preview_webhook_address`] and
/// [`Connectors::update_webhook_address`].
#[derive(Debug, Clone, Default, Serialize)]
pub struct WebhookAddressRequest {
    /// `"live"` or `"sandbox"`. Required, except for a provider whose address
    /// is shared across environments: leave it unset there.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub environment: Option<String>,
    /// `"standard"`, `"custom"` or `"anonymous"`.
    pub mode: String,
    /// The alias for `custom` mode: 6 to 48 ASCII letters, digits, `-` or
    /// `_`, starting and ending with a letter or digit.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub alias: Option<String>,
    /// The identifier format for `anonymous` mode.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub format: Option<WebhookAddressFormat>,
    /// `anonymous` mode only: replace the generated identifier even when the
    /// format is unchanged.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub regenerate: Option<bool>,
    /// Required as `true` to save an address that also applies to other
    /// connector accounts. Ignored by the preview.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub confirm_shared: Option<bool>,
    /// Any additional fields, merged verbatim.
    #[serde(flatten, skip_serializing_if = "serde_json::Map::is_empty")]
    pub extra: serde_json::Map<String, Value>,
}

impl WebhookAddressRequest {
    /// An address in `mode` (`"standard"`, `"custom"` or `"anonymous"`).
    pub fn new(mode: impl Into<String>) -> Self {
        Self {
            mode: mode.into(),
            ..Default::default()
        }
    }

    /// The environment whose address is set: `"live"` or `"sandbox"`.
    #[must_use]
    pub fn environment(mut self, environment: impl Into<String>) -> Self {
        self.environment = Some(environment.into());
        self
    }

    /// The alias, for `custom` mode.
    #[must_use]
    pub fn alias(mut self, alias: impl Into<String>) -> Self {
        self.alias = Some(alias.into());
        self
    }

    /// The identifier format, for `anonymous` mode.
    #[must_use]
    pub fn format(mut self, format: WebhookAddressFormat) -> Self {
        self.format = Some(format);
        self
    }

    /// Replace the generated identifier even when the format is unchanged.
    #[must_use]
    pub fn regenerate(mut self, regenerate: bool) -> Self {
        self.regenerate = Some(regenerate);
        self
    }

    /// Confirm a change that also applies to other connector accounts.
    #[must_use]
    pub fn confirm_shared(mut self, confirm_shared: bool) -> Self {
        self.confirm_shared = Some(confirm_shared);
        self
    }
}

/// Names of `WebhookAddressRequest`'s fields as they appear on the wire
/// (`extra` excluded).
const WEBHOOK_ADDRESS_REQUEST_NAMED: &[&str] = &[
    "environment",
    "mode",
    "alias",
    "format",
    "regenerate",
    "confirm_shared",
];

impl ValidateRequest for WebhookAddressRequest {
    fn validate(&self) -> Result<()> {
        reject_extra_collisions(
            &self.extra,
            WEBHOOK_ADDRESS_REQUEST_NAMED,
            "WebhookAddressRequest",
        )
    }
}

/// Parameters for [`Connectors::create_provider_webhook`].
///
/// `Debug` is hand-written: a destination URL can carry a token in its path
/// or query, so `url` prints as `"[redacted]"`.
#[derive(Clone, Serialize)]
pub struct ProviderWebhookCreateRequest {
    /// `"live"` or `"sandbox"`.
    pub environment: String,
    /// An `https` URL outside the platform.
    pub url: String,
    /// The provider's event names. At least one.
    pub events: Vec<String>,
}

impl ProviderWebhookCreateRequest {
    /// A webhook to `url` for `events`, on the `environment` credential set.
    pub fn new<I, S>(environment: impl Into<String>, url: impl Into<String>, events: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        Self {
            environment: environment.into(),
            url: url.into(),
            events: events.into_iter().map(Into::into).collect(),
        }
    }
}

impl std::fmt::Debug for ProviderWebhookCreateRequest {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ProviderWebhookCreateRequest")
            .field("environment", &self.environment)
            .field("url", &REDACTED)
            .field("events", &self.events)
            .finish()
    }
}

/// Parameters for [`Connectors::update_provider_webhook`]. Only the fields you
/// set change.
///
/// The API refuses unknown fields here, so there is no `extra` map. `Debug` is
/// hand-written: `url` prints as `"[redacted]"`, like the create's.
#[derive(Clone, Serialize)]
pub struct ProviderWebhookUpdateRequest {
    /// `"live"` or `"sandbox"`.
    pub environment: String,
    /// The `fingerprint` the change was decided on.
    pub fingerprint: String,
    /// The new destination.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub url: Option<String>,
    /// The new event names.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub events: Option<Vec<String>>,
    /// Switch the webhook on or off.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub enabled: Option<bool>,
}

impl ProviderWebhookUpdateRequest {
    /// A change on the `environment` credential set, decided on
    /// `fingerprint`.
    pub fn new(environment: impl Into<String>, fingerprint: impl Into<String>) -> Self {
        Self {
            environment: environment.into(),
            fingerprint: fingerprint.into(),
            url: None,
            events: None,
            enabled: None,
        }
    }

    /// Send to a new destination.
    #[must_use]
    pub fn url(mut self, url: impl Into<String>) -> Self {
        self.url = Some(url.into());
        self
    }

    /// Subscribe to these events instead.
    #[must_use]
    pub fn events<I, S>(mut self, events: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.events = Some(events.into_iter().map(Into::into).collect());
        self
    }

    /// Switch the webhook on (`true`) or off (`false`).
    #[must_use]
    pub fn enabled(mut self, enabled: bool) -> Self {
        self.enabled = Some(enabled);
        self
    }
}

impl std::fmt::Debug for ProviderWebhookUpdateRequest {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ProviderWebhookUpdateRequest")
            .field("environment", &self.environment)
            .field("fingerprint", &self.fingerprint)
            .field("url", &self.url.as_ref().map(|_| REDACTED))
            .field("events", &self.events)
            .field("enabled", &self.enabled)
            .finish()
    }
}

/// Parameters for [`Connectors::delete_provider_webhook`]. The API refuses
/// unknown fields here, so there is no `extra` map.
#[derive(Debug, Clone, Serialize)]
pub struct ProviderWebhookDeleteRequest {
    /// `"live"` or `"sandbox"`.
    pub environment: String,
    /// The `fingerprint` the deletion was decided on.
    pub fingerprint: String,
    /// Required as `true` to delete the platform's own webhook.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub confirm_managed: Option<bool>,
}

impl ProviderWebhookDeleteRequest {
    /// A deletion on the `environment` credential set, decided on
    /// `fingerprint`.
    pub fn new(environment: impl Into<String>, fingerprint: impl Into<String>) -> Self {
        Self {
            environment: environment.into(),
            fingerprint: fingerprint.into(),
            confirm_managed: None,
        }
    }

    /// Confirm deleting the platform's own webhook.
    #[must_use]
    pub fn confirm_managed(mut self, confirm: bool) -> Self {
        self.confirm_managed = Some(confirm);
        self
    }
}

/// Parameters for [`Connectors::replace_provider_webhooks`]. The API refuses
/// unknown fields here, so there is no `extra` map.
#[derive(Debug, Clone, Serialize)]
pub struct ProviderWebhookReplaceRequest {
    /// `"live"` or `"sandbox"`.
    pub environment: String,
    /// Exactly the webhooks of the preview's `delete` list the caller agreed
    /// to.
    pub confirmed: Vec<ProviderWebhookConfirmation>,
    /// Required as `true` when the preview's `sequence` is `delete_first`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub accept_delete_first: Option<bool>,
}

impl ProviderWebhookReplaceRequest {
    /// Replace on the `environment` credential set, deleting `confirmed`.
    pub fn new(
        environment: impl Into<String>,
        confirmed: Vec<ProviderWebhookConfirmation>,
    ) -> Self {
        Self {
            environment: environment.into(),
            confirmed,
            accept_delete_first: None,
        }
    }

    /// Accept that the confirmed webhooks are deleted before the platform's
    /// own is registered.
    #[must_use]
    pub fn accept_delete_first(mut self, accept: bool) -> Self {
        self.accept_delete_first = Some(accept);
        self
    }
}

/// One webhook confirmed for deletion in a [`ProviderWebhookReplaceRequest`].
#[derive(Debug, Clone, Serialize)]
pub struct ProviderWebhookConfirmation {
    /// The provider's id of the webhook.
    pub id: String,
    /// The `fingerprint` the preview listed it with.
    pub fingerprint: String,
}

impl ProviderWebhookConfirmation {
    /// Confirm webhook `id` in the state `fingerprint`.
    pub fn new(id: impl Into<String>, fingerprint: impl Into<String>) -> Self {
        Self {
            id: id.into(),
            fingerprint: fingerprint.into(),
        }
    }
}

/// Parameters for [`Connectors::create`].
///
/// `Debug` is hand-written: `connector_account_details`,
/// `connector_webhook_details` and `additional_merchant_data` carry live
/// gateway credentials (API keys, signing secrets, acquirer merchant data), so
/// a derived `Debug` would leak them into logs. They print as
/// `Some("[redacted]")`.
#[derive(Clone, Default, Serialize)]
pub struct ConnectorCreateRequest {
    /// Connector category, e.g. `"payment_processor"` or `"payout_processor"`.
    pub connector_type: String,
    /// Snake-case connector identifier, e.g. `"stripe"`, `"adyen"`.
    pub connector_name: String,
    /// Human-readable label, unique within the merchant account.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub connector_label: Option<String>,
    /// Shop (business profile) the connector belongs to.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub profile_id: Option<String>,
    /// Gateway credentials (open shape — see the API reference). **Secret.**
    #[serde(skip_serializing_if = "Option::is_none")]
    pub connector_account_details: Option<Value>,
    /// Payment methods to enable on this connector (open shapes).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub payment_methods_enabled: Option<Vec<Value>>,
    /// Arbitrary key-value metadata.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub metadata: Option<Value>,
    /// Whether the connector runs against the gateway's test environment.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub test_mode: Option<bool>,
    /// Whether the connector is disabled on creation.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub disabled: Option<bool>,
    /// Incoming-webhook verification details. **Secret** (holds the shared
    /// verification secret).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub connector_webhook_details: Option<Value>,
    /// Additional merchant data required by some connectors. **Secret.**
    #[serde(skip_serializing_if = "Option::is_none")]
    pub additional_merchant_data: Option<Value>,
    /// Connector status, e.g. `"active"` or `"inactive"`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub status: Option<String>,
    /// The payment methods to enable for sandbox payments. `None` makes
    /// sandbox follow `payment_methods_enabled`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub payment_methods_enabled_sandbox: Option<Vec<Value>>,
    /// How the callback URL the provider delivers webhooks to is addressed.
    /// Refused once the merchant already has an account at that provider.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub webhook_address: Option<ConnectorCreateWebhookAddress>,
    /// Any additional fields, merged verbatim.
    #[serde(flatten, skip_serializing_if = "serde_json::Map::is_empty")]
    pub extra: serde_json::Map<String, Value>,
}

/// Placeholder printed in place of a credential-bearing field.
const REDACTED: &str = "[redacted]";

/// `Some("[redacted]")` when the credential field is set, `None` when it is
/// not — enough to debug "did I set this?" without printing the secret.
fn redact(v: Option<&Value>) -> Option<&'static str> {
    v.map(|_| REDACTED)
}

impl std::fmt::Debug for ConnectorCreateRequest {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ConnectorCreateRequest")
            .field("connector_type", &self.connector_type)
            .field("connector_name", &self.connector_name)
            .field("connector_label", &self.connector_label)
            .field("profile_id", &self.profile_id)
            .field(
                "connector_account_details",
                &redact(self.connector_account_details.as_ref()),
            )
            .field("payment_methods_enabled", &self.payment_methods_enabled)
            .field("metadata", &self.metadata)
            .field("test_mode", &self.test_mode)
            .field("disabled", &self.disabled)
            .field(
                "connector_webhook_details",
                &redact(self.connector_webhook_details.as_ref()),
            )
            .field(
                "additional_merchant_data",
                &redact(self.additional_merchant_data.as_ref()),
            )
            .field("status", &self.status)
            .field(
                "payment_methods_enabled_sandbox",
                &self.payment_methods_enabled_sandbox,
            )
            .field("webhook_address", &self.webhook_address)
            .field("extra", &self.extra)
            .finish()
    }
}

/// How the callback URL of a new connector account is addressed, in
/// [`ConnectorCreateRequest::webhook_address`].
#[derive(Debug, Clone, Default, Serialize)]
pub struct ConnectorCreateWebhookAddress {
    /// `"standard"`, `"custom"` or `"anonymous"`.
    pub mode: String,
    /// The alias, for `"custom"` mode.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub alias: Option<String>,
    /// The format of a generated address.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub format: Option<WebhookAddressFormat>,
}

impl ConnectorCreateWebhookAddress {
    /// An address in `mode`.
    pub fn new(mode: impl Into<String>) -> Self {
        Self {
            mode: mode.into(),
            ..Default::default()
        }
    }

    /// The alias, for `"custom"` mode.
    #[must_use]
    pub fn alias(mut self, alias: impl Into<String>) -> Self {
        self.alias = Some(alias.into());
        self
    }

    /// The format of a generated address.
    #[must_use]
    pub fn format(mut self, format: WebhookAddressFormat) -> Self {
        self.format = Some(format);
        self
    }
}

/// Names of `ConnectorCreateRequest`'s fields, as they appear on the wire
/// (`extra` excluded).
const CONNECTOR_CREATE_REQUEST_NAMED: &[&str] = &[
    "connector_type",
    "connector_name",
    "connector_label",
    "profile_id",
    "connector_account_details",
    "payment_methods_enabled",
    "metadata",
    "test_mode",
    "disabled",
    "connector_webhook_details",
    "additional_merchant_data",
    "status",
    "payment_methods_enabled_sandbox",
    "webhook_address",
];

impl ValidateRequest for ConnectorCreateRequest {
    fn validate(&self) -> Result<()> {
        for key in self.extra.keys() {
            if CONNECTOR_CREATE_REQUEST_NAMED.contains(&key.as_str()) {
                return Err(DelopayError::InvalidRequest(format!(
                    "`extra` key `{key}` collides with a named field on ConnectorCreateRequest"
                )));
            }
        }
        Ok(())
    }
}

impl ConnectorCreateRequest {
    /// A request creating a connector of the given category and name, e.g.
    /// `ConnectorCreateRequest::new("payment_processor", "stripe")`.
    pub fn new(connector_type: impl Into<String>, connector_name: impl Into<String>) -> Self {
        Self {
            connector_type: connector_type.into(),
            connector_name: connector_name.into(),
            ..Default::default()
        }
    }

    /// Set the shop (business profile) the connector belongs to.
    #[must_use]
    pub fn profile_id(mut self, profile_id: impl Into<String>) -> Self {
        self.profile_id = Some(profile_id.into());
        self
    }

    /// Set the connector's label.
    #[must_use]
    pub fn connector_label(mut self, label: impl Into<String>) -> Self {
        self.connector_label = Some(label.into());
        self
    }

    /// Set the gateway credentials.
    #[must_use]
    pub fn connector_account_details(mut self, details: Value) -> Self {
        self.connector_account_details = Some(details);
        self
    }

    /// Set whether the connector runs in the gateway's test environment.
    #[must_use]
    pub fn test_mode(mut self, test_mode: bool) -> Self {
        self.test_mode = Some(test_mode);
        self
    }
}

/// Parameters for [`Connectors::update`].
///
/// `Debug` is hand-written for the same reason as
/// [`ConnectorCreateRequest`]: the credential-bearing fields are redacted.
#[derive(Clone, Default, Serialize)]
pub struct ConnectorUpdateRequest {
    /// Connector category, e.g. `"payment_processor"`. Required by the API.
    pub connector_type: String,
    /// Connector status, e.g. `"active"` or `"inactive"`. Required by the API.
    pub status: String,
    /// Human-readable label, unique within the merchant account.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub connector_label: Option<String>,
    /// Gateway credentials (open shape — see the API reference). **Secret.**
    #[serde(skip_serializing_if = "Option::is_none")]
    pub connector_account_details: Option<Value>,
    /// Payment methods enabled on this connector (open shapes).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub payment_methods_enabled: Option<Vec<Value>>,
    /// Arbitrary key-value metadata.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub metadata: Option<Value>,
    /// Whether the connector runs against the gateway's test environment.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub test_mode: Option<bool>,
    /// Whether the connector is disabled.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub disabled: Option<bool>,
    /// Incoming-webhook verification details. **Secret**, and **merged key by
    /// key** — unlike every other field on this request.
    ///
    /// Send only the keys an operator actually typed. See
    /// [`ConnectorWebhookDetailsUpdate`] for what an omitted key, a value and
    /// an empty string each do; padding the environment you are not editing
    /// with empty strings clears its live signing secret.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub connector_webhook_details: Option<ConnectorWebhookDetailsUpdate>,
    /// Additional merchant data required by some connectors. **Secret.**
    #[serde(skip_serializing_if = "Option::is_none")]
    pub additional_merchant_data: Option<Value>,
    /// The payment methods to enable for sandbox payments.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub payment_methods_enabled_sandbox: Option<Vec<Value>>,
    /// `true` makes sandbox follow `payment_methods_enabled` again.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub payment_methods_enabled_sandbox_follows_live: Option<bool>,
    /// Any additional fields, merged verbatim.
    #[serde(flatten, skip_serializing_if = "serde_json::Map::is_empty")]
    pub extra: serde_json::Map<String, Value>,
}

/// The incoming-webhook signing secrets of one connector account, as an
/// **update**.
///
/// The server merges this key by key, which the sibling secret fields on
/// [`ConnectorUpdateRequest`] do not do:
///
/// | What you send | What happens |
/// |---|---|
/// | the key omitted (`None`) | the stored secret is kept |
/// | a value | it is written |
/// | an empty string | the stored secret is **cleared** |
///
/// So send only the keys an operator actually typed. A caller that fills in
/// the whole block and pads the environment it is not editing with `""`
/// clears that environment's live signing secret, and inbound webhooks stop
/// verifying with nothing on screen to say why.
///
/// Typing the four keys catches a misspelling (`merchant_secrets`) and a
/// non-string value, both of which an open JSON value accepted in silence. It
/// cannot catch the destructive case — clearing a secret with `""` is the
/// intended way to clear one, so the call that means it and the call that
/// pads are the same call. That guard is the calling convention above.
///
/// `Debug` is hand-written: every field here is a live signing secret.
#[derive(Clone, Default, Serialize)]
pub struct ConnectorWebhookDetailsUpdate {
    /// Live signing secret.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub merchant_secret: Option<String>,
    /// Second live secret, for connectors that sign with a pair.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub additional_secret: Option<String>,
    /// Sandbox signing secret.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub sandbox_merchant_secret: Option<String>,
    /// Second sandbox secret.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub sandbox_additional_secret: Option<String>,
}

impl std::fmt::Debug for ConnectorWebhookDetailsUpdate {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let mask = |v: &Option<String>| v.as_ref().map(|_| REDACTED);
        f.debug_struct("ConnectorWebhookDetailsUpdate")
            .field("merchant_secret", &mask(&self.merchant_secret))
            .field("additional_secret", &mask(&self.additional_secret))
            .field(
                "sandbox_merchant_secret",
                &mask(&self.sandbox_merchant_secret),
            )
            .field(
                "sandbox_additional_secret",
                &mask(&self.sandbox_additional_secret),
            )
            .finish()
    }
}

impl std::fmt::Debug for ConnectorUpdateRequest {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ConnectorUpdateRequest")
            .field("connector_type", &self.connector_type)
            .field("status", &self.status)
            .field("connector_label", &self.connector_label)
            .field(
                "connector_account_details",
                &redact(self.connector_account_details.as_ref()),
            )
            .field("payment_methods_enabled", &self.payment_methods_enabled)
            .field("metadata", &self.metadata)
            .field("test_mode", &self.test_mode)
            .field("disabled", &self.disabled)
            .field("connector_webhook_details", &self.connector_webhook_details)
            .field(
                "additional_merchant_data",
                &redact(self.additional_merchant_data.as_ref()),
            )
            .field(
                "payment_methods_enabled_sandbox",
                &self.payment_methods_enabled_sandbox,
            )
            .field(
                "payment_methods_enabled_sandbox_follows_live",
                &self.payment_methods_enabled_sandbox_follows_live,
            )
            .field("extra", &self.extra)
            .finish()
    }
}

/// Names of `ConnectorUpdateRequest`'s fields, as they appear on the wire
/// (`extra` excluded).
const CONNECTOR_UPDATE_REQUEST_NAMED: &[&str] = &[
    "connector_type",
    "status",
    "connector_label",
    "connector_account_details",
    "payment_methods_enabled",
    "metadata",
    "test_mode",
    "disabled",
    "connector_webhook_details",
    "additional_merchant_data",
    "payment_methods_enabled_sandbox",
    "payment_methods_enabled_sandbox_follows_live",
];

impl ValidateRequest for ConnectorUpdateRequest {
    fn validate(&self) -> Result<()> {
        for key in self.extra.keys() {
            if CONNECTOR_UPDATE_REQUEST_NAMED.contains(&key.as_str()) {
                return Err(DelopayError::InvalidRequest(format!(
                    "`extra` key `{key}` collides with a named field on ConnectorUpdateRequest"
                )));
            }
        }
        Ok(())
    }
}

impl ConnectorUpdateRequest {
    /// A request setting the connector's category and status, e.g.
    /// `ConnectorUpdateRequest::new("payment_processor", "active")`.
    pub fn new(connector_type: impl Into<String>, status: impl Into<String>) -> Self {
        Self {
            connector_type: connector_type.into(),
            status: status.into(),
            ..Default::default()
        }
    }

    /// Set the gateway credentials.
    #[must_use]
    pub fn connector_account_details(mut self, details: Value) -> Self {
        self.connector_account_details = Some(details);
        self
    }

    /// Set whether the connector is disabled.
    #[must_use]
    pub fn disabled(mut self, disabled: bool) -> Self {
        self.disabled = Some(disabled);
        self
    }
}

/// Parameters for [`Connectors::register_webhook`].
#[derive(Debug, Clone, Default, Serialize)]
pub struct ConnectorWebhookRegisterRequest {
    /// Event scope: the string `"all_events"`, or
    /// `{"specific_event": "…"}`. Omit to let the server default to all
    /// events.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub event_type: Option<Value>,
    /// Credential set to register with: `"live"` or `"sandbox"`. Defaults to
    /// `"live"` server-side.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub environment: Option<String>,
    /// Endpoint URL to register (plain `/webhooks/…` or obfuscated
    /// `/webhooks_base/…` form). When omitted the server derives the canonical
    /// plain form. Must route back to the connector account — the path has to
    /// end with the `mca_…` id.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub webhook_url: Option<String>,
}

impl ConnectorWebhookRegisterRequest {
    /// Register for every event the connector emits.
    pub fn all_events() -> Self {
        Self {
            event_type: Some(Value::String("all_events".to_string())),
            ..Default::default()
        }
    }

    /// Register for one named event only.
    pub fn specific_event(event: impl Into<String>) -> Self {
        Self {
            event_type: Some(serde_json::json!({ "specific_event": event.into() })),
            ..Default::default()
        }
    }

    /// Register against the `"live"` or `"sandbox"` credential set.
    #[must_use]
    pub fn environment(mut self, environment: impl Into<String>) -> Self {
        self.environment = Some(environment.into());
        self
    }

    /// Register a specific endpoint URL instead of the server-derived one.
    #[must_use]
    pub fn webhook_url(mut self, url: impl Into<String>) -> Self {
        self.webhook_url = Some(url.into());
        self
    }
}

/// Parameters for [`Connectors::register_stripe_payment_method_domains`].
///
/// `urls` is serialized even when empty: an empty list is a caller mistake the
/// server should reject explicitly, not a field the SDK quietly drops into a
/// different request.
#[derive(Debug, Clone, Default, Serialize)]
pub struct StripePaymentMethodDomainsRegisterRequest {
    /// Absolute URLs (or bare hostnames) whose hosts are registered — the
    /// hosted-checkout origin first, plus any of the merchant's own shop URLs.
    /// At most 10 per request; duplicates by resolved host are collapsed
    /// server-side but still receive their own result row.
    pub urls: Vec<String>,
    /// Credential set to register with: `"live"` or `"sandbox"`. Defaults to
    /// `"live"` server-side.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub environment: Option<String>,
}

impl StripePaymentMethodDomainsRegisterRequest {
    /// Register the given URLs against the connector's live credential set.
    pub fn new<I, S>(urls: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        Self {
            urls: urls.into_iter().map(Into::into).collect(),
            environment: None,
        }
    }

    /// Register against the `"live"` or `"sandbox"` credential set instead of
    /// the server default (`"live"`).
    #[must_use]
    pub fn environment(mut self, environment: impl Into<String>) -> Self {
        self.environment = Some(environment.into());
        self
    }
}

/// Query parameters for [`Connectors::health`].
#[derive(Debug, Clone, Default)]
pub struct ConnectorHealthParams {
    /// Which credential set to probe: `true` for sandbox, `false` for live.
    /// Omitted means the connector's own default environment.
    pub test_mode: Option<bool>,
    /// Force a fresh probe instead of the stored one. A probe calls the
    /// processor, so leave it off for a page that polls.
    pub refresh: Option<bool>,
}

impl ConnectorHealthParams {
    /// Empty parameters: the connector's default environment, stored probe.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Probe the sandbox (`true`) or live (`false`) credential set.
    #[must_use]
    pub fn test_mode(mut self, test_mode: bool) -> Self {
        self.test_mode = Some(test_mode);
        self
    }

    /// Force a fresh probe rather than answering from the stored one.
    #[must_use]
    pub fn refresh(mut self, refresh: bool) -> Self {
        self.refresh = Some(refresh);
        self
    }

    fn to_query(&self) -> Vec<(&'static str, String)> {
        let mut q = Vec::new();
        if let Some(v) = self.test_mode {
            q.push(("test_mode", v.to_string()));
        }
        if let Some(v) = self.refresh {
            q.push(("refresh", v.to_string()));
        }
        q
    }
}

/// Parameters for [`Connectors::register_airwallex_apple_pay_domains`].
///
/// `urls` is serialized even when empty: an empty list is a caller mistake the
/// server should reject explicitly, not a field the SDK quietly drops.
#[derive(Debug, Clone, Default, Serialize)]
pub struct AirwallexApplePayDomainsRegisterRequest {
    /// Absolute URLs (or bare hostnames) whose hosts are registered — the
    /// hosted-checkout origin first, plus any of the merchant's own shop URLs.
    pub urls: Vec<String>,
    /// Credential set to register with: `"live"` or `"sandbox"`. Defaults to
    /// `"live"` server-side.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub environment: Option<String>,
}

impl AirwallexApplePayDomainsRegisterRequest {
    /// Register the given URLs against the connector's live credential set.
    pub fn new<I, S>(urls: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        Self {
            urls: urls.into_iter().map(Into::into).collect(),
            environment: None,
        }
    }

    /// Register against the `"live"` or `"sandbox"` credential set instead of
    /// the server default (`"live"`).
    #[must_use]
    pub fn environment(mut self, environment: impl Into<String>) -> Self {
        self.environment = Some(environment.into());
        self
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::http::mock::{Step, client_with};
    use serde_json::json;

    const CONNECTOR_JSON: &str = r#"{
        "merchant_connector_id": "mca_1",
        "connector_type": "payment_processor",
        "connector_name": "stripe",
        "profile_id": "pro_1",
        "status": "active"
    }"#;

    fn full_create_request() -> ConnectorCreateRequest {
        ConnectorCreateRequest {
            connector_type: "payment_processor".to_string(),
            connector_name: "stripe".to_string(),
            connector_label: Some("stripe_uk".to_string()),
            profile_id: Some("pro_1".to_string()),
            connector_account_details: Some(json!({"api_key": "sk_live_supersecret"})),
            payment_methods_enabled: Some(vec![json!({"payment_method": "card"})]),
            metadata: Some(json!({"team": "payments"})),
            test_mode: Some(false),
            disabled: Some(false),
            connector_webhook_details: Some(json!({"merchant_secret": "whsec_topsecret"})),
            additional_merchant_data: Some(json!({"acquirer": "acq_1"})),
            status: Some("active".to_string()),
            payment_methods_enabled_sandbox: Some(vec![json!({"payment_method": "card"})]),
            webhook_address: Some(
                ConnectorCreateWebhookAddress::new("custom")
                    .alias("shop-a")
                    .format(WebhookAddressFormat::new("wh", "alphanumeric", 16)),
            ),
            extra: serde_json::Map::new(),
        }
    }

    fn full_update_request() -> ConnectorUpdateRequest {
        ConnectorUpdateRequest {
            connector_type: "payment_processor".to_string(),
            status: "active".to_string(),
            connector_label: Some("stripe_uk".to_string()),
            connector_account_details: Some(json!({"api_key": "sk_live_supersecret"})),
            payment_methods_enabled: Some(vec![json!({"payment_method": "card"})]),
            metadata: Some(json!({"team": "payments"})),
            test_mode: Some(false),
            disabled: Some(false),
            connector_webhook_details: Some(ConnectorWebhookDetailsUpdate {
                merchant_secret: Some("whsec_topsecret".to_string()),
                additional_secret: None,
                sandbox_merchant_secret: None,
                sandbox_additional_secret: None,
            }),
            additional_merchant_data: Some(json!({"acquirer": "acq_1"})),
            payment_methods_enabled_sandbox: Some(Vec::new()),
            payment_methods_enabled_sandbox_follows_live: Some(false),
            extra: serde_json::Map::new(),
        }
    }

    /// The catalogue route keeps the router's own spelling of the path.
    ///
    /// Mutation: rename the segment to `panes` — which is what the SDK's own
    /// identifiers were renamed to — and this fails, as it would 404 in
    /// production.
    #[tokio::test]
    async fn panes_catalog_gets_the_routers_own_path_and_decodes() {
        let (client, mock) = client_with(vec![Step::ok(
            r#"{
                "connectors": [{
                    "connector": "stripe",
                    "allowed_rails": ["wallet", "redirect"],
                    "methods": [{
                        "key": "klarna",
                        "rail": "redirect",
                        "payment_method": "pay_later",
                        "payment_method_type": "klarna",
                        "requires_billing_country": true
                    }]
                }]
            }"#,
        )]);
        let catalog = client.connectors().panes_catalog("acct/1").await.unwrap();

        assert_eq!(catalog.connectors[0].connector, "stripe");
        let method = &catalog.connectors[0].methods[0];
        assert_eq!(method.payment_method, "pay_later");
        assert!(method.requires_billing_country);

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "GET");
        assert_eq!(
            seen[0].url,
            "https://api.test/account/acct%2F1/connectors/native-panes/catalog"
        );
    }

    /// Drift guard: catches a new field added to `ConnectorCreateRequest`
    /// without a matching update to `CONNECTOR_CREATE_REQUEST_NAMED`.
    #[test]
    fn connector_create_request_named_fields_are_complete() {
        let value = serde_json::to_value(full_create_request()).unwrap();
        assert_eq!(
            value["webhook_address"],
            json!({"mode": "custom", "alias": "shop-a",
                   "format": {"prefix": "wh", "style": "alphanumeric", "length": 16}})
        );
        for key in value.as_object().expect("serializes to an object").keys() {
            assert!(
                CONNECTOR_CREATE_REQUEST_NAMED.contains(&key.as_str()),
                "CONNECTOR_CREATE_REQUEST_NAMED is missing wire key `{key}`"
            );
        }
    }

    /// Only the keys a caller set reach the wire.
    ///
    /// The server merges this block key by key, so an omitted key keeps the
    /// stored secret and an explicit empty string clears it. Serializing the
    /// unset keys — as `null`, or as `""` — would turn "I am changing the live
    /// secret" into "I am also clearing both sandbox secrets", and inbound
    /// webhooks would stop verifying with nothing on screen to say why.
    ///
    /// Mutation: drop the `skip_serializing_if` on any field of
    /// `ConnectorWebhookDetailsUpdate` and this fails.
    #[test]
    fn a_webhook_secret_update_sends_only_the_keys_it_sets() {
        let request = ConnectorUpdateRequest {
            connector_webhook_details: Some(ConnectorWebhookDetailsUpdate {
                sandbox_merchant_secret: Some("whsec_sandbox".to_string()),
                ..ConnectorWebhookDetailsUpdate::default()
            }),
            ..ConnectorUpdateRequest::new("payment_processor", "active")
        };
        let value = serde_json::to_value(&request).unwrap();
        let details = value
            .get("connector_webhook_details")
            .and_then(Value::as_object)
            .expect("the block serializes");
        assert_eq!(
            details.keys().collect::<Vec<_>>(),
            ["sandbox_merchant_secret"]
        );
    }

    /// An empty string is a deliberate clear and does reach the wire — the
    /// only way to remove a stored secret. The type cannot tell that call from
    /// a caller padding the block, which is why the calling convention is
    /// "send only what an operator typed".
    #[test]
    fn an_explicit_empty_secret_is_sent_because_it_means_clear_it() {
        let request = ConnectorUpdateRequest {
            connector_webhook_details: Some(ConnectorWebhookDetailsUpdate {
                merchant_secret: Some(String::new()),
                ..ConnectorWebhookDetailsUpdate::default()
            }),
            ..ConnectorUpdateRequest::new("payment_processor", "active")
        };
        let value = serde_json::to_value(&request).unwrap();
        assert_eq!(value["connector_webhook_details"]["merchant_secret"], "");
    }

    /// Every secret in the block prints redacted.
    ///
    /// Mutation: derive `Debug` on `ConnectorWebhookDetailsUpdate` and this
    /// fails — a request struct is exactly what lands in a debug log when a
    /// save goes wrong.
    #[test]
    fn a_webhook_secret_update_debug_redacts_every_secret() {
        let printed = format!(
            "{:?}",
            ConnectorWebhookDetailsUpdate {
                merchant_secret: Some("whsec_live".to_string()),
                additional_secret: Some("whsec_extra".to_string()),
                sandbox_merchant_secret: Some("whsec_sandbox".to_string()),
                sandbox_additional_secret: Some("whsec_sandbox_extra".to_string()),
            }
        );
        assert!(!printed.contains("whsec_"), "printed: {printed}");
        assert_eq!(printed.matches(REDACTED).count(), 4);
    }

    /// Drift guard for `CONNECTOR_UPDATE_REQUEST_NAMED`.
    #[test]
    fn connector_update_request_named_fields_are_complete() {
        let value = serde_json::to_value(full_update_request()).unwrap();
        for key in value.as_object().expect("serializes to an object").keys() {
            assert!(
                CONNECTOR_UPDATE_REQUEST_NAMED.contains(&key.as_str()),
                "CONNECTOR_UPDATE_REQUEST_NAMED is missing wire key `{key}`"
            );
        }
    }

    #[test]
    fn create_validate_rejects_colliding_extra_key() {
        let mut req = ConnectorCreateRequest::new("payment_processor", "stripe");
        req.extra.insert("profile_id".to_string(), json!("pro_2"));
        match req.validate().unwrap_err() {
            DelopayError::InvalidRequest(msg) => assert!(msg.contains("profile_id")),
            other => panic!("expected InvalidRequest, got {other:?}"),
        }
    }

    #[test]
    fn update_validate_rejects_colliding_extra_key() {
        let mut req = ConnectorUpdateRequest::new("payment_processor", "active");
        req.extra.insert("status".to_string(), json!("inactive"));
        assert!(matches!(
            req.validate().unwrap_err(),
            DelopayError::InvalidRequest(_)
        ));
    }

    /// The credential fields must never reach a log line. A mutation replacing
    /// `redact(...)` with the field itself makes this red.
    #[test]
    fn debug_redacts_connector_credentials() {
        let rendered = format!("{:?}", full_create_request());
        assert!(!rendered.contains("sk_live_supersecret"), "{rendered}");
        assert!(!rendered.contains("whsec_topsecret"), "{rendered}");
        assert!(!rendered.contains("acq_1"), "{rendered}");
        assert!(rendered.contains("connector_account_details: Some(\"[redacted]\")"));
        // Non-secret fields still print, or the impl would be useless.
        assert!(rendered.contains("stripe"), "{rendered}");

        let rendered = format!("{:?}", full_update_request());
        assert!(!rendered.contains("sk_live_supersecret"), "{rendered}");
        assert!(!rendered.contains("whsec_topsecret"), "{rendered}");
        assert!(!rendered.contains("acq_1"), "{rendered}");
        assert!(rendered.contains("connector_account_details: Some(\"[redacted]\")"));
    }

    /// An unset credential field must be distinguishable from a set one.
    #[test]
    fn debug_shows_none_for_unset_credentials() {
        let rendered = format!(
            "{:?}",
            ConnectorCreateRequest::new("payment_processor", "stripe")
        );
        assert!(
            rendered.contains("connector_account_details: None"),
            "{rendered}"
        );
    }

    #[tokio::test]
    async fn create_posts_to_the_account_connectors_path() {
        let (client, mock) = client_with(vec![Step::ok(CONNECTOR_JSON)]);
        let req = ConnectorCreateRequest::new("payment_processor", "stripe")
            .profile_id("pro_1")
            .connector_account_details(json!({"api_key": "sk_test"}));
        let created = client.connectors().create("mer/1", &req).await.unwrap();
        assert_eq!(created.merchant_connector_id, "mca_1");
        assert_eq!(created.connector_name.as_deref(), Some("stripe"));

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(seen[0].url, "https://api.test/account/mer%2F1/connectors");
        let body = seen[0].body_json();
        assert_eq!(body["connector_name"], "stripe");
        assert_eq!(body["connector_account_details"]["api_key"], "sk_test");
    }

    #[tokio::test]
    async fn retrieve_list_and_delete_hit_their_paths() {
        let (client, mock) = client_with(vec![
            Step::ok(CONNECTOR_JSON),
            Step::ok("[]"),
            Step::ok(CONNECTOR_JSON),
        ]);
        let connectors = client.connectors();
        let retrieved = connectors.retrieve("mer_1", "mca/1").await.unwrap();
        assert_eq!(retrieved.status.as_deref(), Some("active"));
        assert!(connectors.list("mer_1").await.unwrap().is_empty());
        connectors.delete("mer_1", "mca_1").await.unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(
            (seen[0].method, seen[0].url.as_str()),
            ("GET", "https://api.test/account/mer_1/connectors/mca%2F1")
        );
        assert_eq!(
            (seen[1].method, seen[1].url.as_str()),
            ("GET", "https://api.test/account/mer_1/connectors")
        );
        assert_eq!(
            (seen[2].method, seen[2].url.as_str()),
            ("DELETE", "https://api.test/account/mer_1/connectors/mca_1")
        );
    }

    #[tokio::test]
    async fn update_posts_the_status_to_the_connector_path() {
        let (client, mock) = client_with(vec![Step::ok(CONNECTOR_JSON)]);
        let req = ConnectorUpdateRequest::new("payment_processor", "inactive").disabled(true);
        client
            .connectors()
            .update("mer_1", "mca_1", &req)
            .await
            .unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(
            seen[0].url,
            "https://api.test/account/mer_1/connectors/mca_1"
        );
        let body = seen[0].body_json();
        assert_eq!(body["status"], "inactive");
        assert_eq!(body["disabled"], true);
    }

    #[tokio::test]
    async fn register_webhook_omits_the_body_when_no_params() {
        // The server only applies its `all_events` default to a bodyless call,
        // so a mutation sending `{}` here must fail.
        let (client, mock) = client_with(vec![Step::ok(
            r#"{"webhook_registration_status":"success"}"#,
        )]);
        let registered = client
            .connectors()
            .register_webhook("mer_1", "mca_1", None)
            .await
            .unwrap();
        assert_eq!(registered.webhook_registration_status, "success");

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(
            seen[0].url,
            "https://api.test/account/mer_1/connectors/webhooks/mca_1"
        );
        assert!(seen[0].body.is_none(), "expected no request body");
    }

    #[tokio::test]
    async fn register_webhook_sends_a_specific_event_scope() {
        let (client, mock) = client_with(vec![Step::ok(
            r#"{"webhook_registration_status":"success"}"#,
        )]);
        let req = ConnectorWebhookRegisterRequest::specific_event("payment_intent.succeeded")
            .environment("sandbox");
        client
            .connectors()
            .register_webhook("mer_1", "mca_1", Some(&req))
            .await
            .unwrap();

        let seen = mock.seen.lock().unwrap();
        let body = seen[0].body_json();
        assert_eq!(
            body["event_type"]["specific_event"],
            "payment_intent.succeeded"
        );
        assert_eq!(body["environment"], "sandbox");
    }

    #[tokio::test]
    async fn webhook_and_payment_methods_get_their_paths() {
        let (client, mock) = client_with(vec![
            Step::ok(r#"{"connector":"stripe","webhooks":[{"connector_webhook_id":"we_1"}]}"#),
            Step::ok("[]"),
        ]);
        let connectors = client.connectors();
        let listed = connectors.webhook("mer_1", "mca_1").await.unwrap();
        assert_eq!(listed.connector, "stripe");
        assert_eq!(listed.webhooks.len(), 1);
        assert_eq!(listed.webhooks[0].connector_webhook_id, "we_1");
        connectors.list_payment_methods().await.unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(
            (seen[0].method, seen[0].url.as_str()),
            (
                "GET",
                "https://api.test/account/mer_1/connectors/webhooks/mca_1"
            )
        );
        assert_eq!(
            (seen[1].method, seen[1].url.as_str()),
            ("GET", "https://api.test/account/payment-methods")
        );
    }

    /// Sync is a bodyless POST on its own path — a mutation dropping the
    /// `/sync-events` suffix would silently re-register the endpoint instead,
    /// minting a new signing secret.
    #[tokio::test]
    async fn sync_webhook_events_posts_to_the_sync_path() {
        let (client, mock) = client_with(vec![Step::ok(
            r#"{
                "connector": "stripe",
                "expected_events": ["refund.succeeded"],
                "endpoints": [
                    {"connector_webhook_id":"we_1","updated":true,"added_events":["refund.succeeded"]}
                ]
            }"#,
        )]);
        let synced = client
            .connectors()
            .sync_webhook_events("mer_1", "mca_1")
            .await
            .unwrap();
        assert_eq!(synced.endpoints[0].added_events, ["refund.succeeded"]);
        assert!(synced.endpoints[0].updated);

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(
            seen[0].url,
            "https://api.test/account/mer_1/connectors/webhooks/mca_1/sync-events"
        );
        assert!(seen[0].body.is_none(), "expected no request body");
    }

    #[tokio::test]
    async fn register_stripe_payment_method_domains_sends_urls_and_environment() {
        let (client, mock) = client_with(vec![Step::ok(
            r#"{"environment":"sandbox","results":[{"url":"https://shop.example","status":"registered"}]}"#,
        )]);
        let req = StripePaymentMethodDomainsRegisterRequest::new(["https://shop.example"])
            .environment("sandbox");
        let registered = client
            .connectors()
            .register_stripe_payment_method_domains("mer_1", "mca_1", &req)
            .await
            .unwrap();
        assert_eq!(registered.results[0].status.as_deref(), Some("registered"));

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(
            seen[0].url,
            "https://api.test/account/mer_1/connectors/mca_1/stripe/payment-method-domains"
        );
        let body = seen[0].body_json();
        assert_eq!(body["urls"][0], "https://shop.example");
        assert_eq!(body["environment"], "sandbox");
    }

    /// The default request must not pin an environment — omitting it is what
    /// lets the server apply its own `"live"` default.
    #[tokio::test]
    async fn register_stripe_payment_method_domains_omits_an_unset_environment() {
        let (client, mock) = client_with(vec![Step::ok(r#"{"environment":"live","results":[]}"#)]);
        let req = StripePaymentMethodDomainsRegisterRequest::new(["shop.example"]);
        client
            .connectors()
            .register_stripe_payment_method_domains("mer_1", "mca_1", &req)
            .await
            .unwrap();

        let seen = mock.seen.lock().unwrap();
        let body = seen[0].body_json();
        assert!(body.get("environment").is_none(), "{body}");
    }
    /// The health probe is a plain GET that carries the environment and the
    /// refresh flag as query parameters. Mutation: drop `refresh` from
    /// `to_query` — the URL assertion fails.
    #[tokio::test]
    async fn health_gets_the_connector_health_path_with_its_options() {
        let (client, mock) = client_with(vec![Step::ok(
            r#"{"merchant_connector_id":"mca_1","connector":"stripe","test_mode":false,"state":"unknown","unknown_reason":"processor_unreachable","probed_at":"2026-09-12T00:00:00Z"}"#,
        )]);
        let out = client
            .connectors()
            .health(
                "mer_1",
                "mca_1",
                Some(&ConnectorHealthParams::new().test_mode(false).refresh(true)),
            )
            .await
            .unwrap();

        // `unknown` is a third state: it must not be read as either healthy or
        // restricted, and it carries the reason instead of a chargeability.
        assert_eq!(out.state, "unknown");
        assert_eq!(out.can_accept_charges, None);
        assert_eq!(out.unknown_reason.as_deref(), Some("processor_unreachable"));

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "GET");
        assert_eq!(
            seen[0].url,
            "https://api.test/account/mer_1/connectors/mca_1/health?test_mode=false&refresh=true"
        );
    }

    /// Apple Pay domains register per credential set, and the URLs go out as
    /// sent. Mutation: send `environment` unconditionally — the
    /// "no environment key" assertion fails for the default request.
    #[tokio::test]
    async fn register_airwallex_apple_pay_domains_posts_the_urls() {
        let (client, mock) = client_with(vec![Step::ok(
            r#"{"environment":"live","results":[{"url":"https://shop.test","domain":"shop.test","status":"already_registered"}]}"#,
        )]);
        let out = client
            .connectors()
            .register_airwallex_apple_pay_domains(
                "mer_1",
                "mca_1",
                &AirwallexApplePayDomainsRegisterRequest::new(["https://shop.test"]),
            )
            .await
            .unwrap();

        assert_eq!(out.results[0].status.as_deref(), Some("already_registered"));

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(
            seen[0].url,
            "https://api.test/account/mer_1/connectors/mca_1/airwallex/apple-pay-domains"
        );
        assert_eq!(seen[0].body_json()["urls"][0], "https://shop.test");
        assert!(seen[0].body_json().get("environment").is_none());
    }

    const SHOPS_JSON: &str = r#"{
        "merchant_connector_id": "mca_1",
        "profile_id": "pro_1",
        "shared_profile_ids": ["pro_2"],
        "disabled_profile_ids": [],
        "assigned_profile_ids": ["pro_1", "pro_2"],
        "surprise_field": 1
    }"#;

    const CURRENCY_POLICY_JSON: &str = r#"{
        "merchant_connector_id": "mca_1",
        "connector_name": "stripe",
        "profile_id": "pro_1",
        "allowed_currencies": ["EUR", "USD"],
        "unreadable": false,
        "conversion": {"convert_to": "EUR", "unreadable": false},
        "provider_capability": {"currencies": null, "payment_method_types": []},
        "shops": [{
            "profile_id": "pro_1",
            "disabled": false,
            "allowed_currencies": null,
            "effective_currencies": ["EUR", "USD"],
            "ignored_currencies": [],
            "conversion": null
        }],
        "impact": [{
            "profile_id": "pro_1",
            "before": null,
            "after": ["EUR", "USD"],
            "removed": [],
            "removed_unbounded": true,
            "uncovered": []
        }],
        "applied": false,
        "surprise_field": 1
    }"#;

    const WEBHOOK_ADDRESS_JSON: &str = r#"{
        "connector": "stripe",
        "merchant_connector_id": "mca_1",
        "management": "managed",
        "constraints": {
            "alias_min_length": 6, "alias_max_length": 48, "prefix_max_length": 8,
            "body_min_length": 12, "numeric_body_min_length": 16, "body_max_length": 32,
            "max_changes": 3, "change_window_days": 30
        },
        "environments": [{
            "environment": "live",
            "shared_across_environments": false,
            "mode": "anonymous",
            "identifier": "wh-abc123",
            "format": {"prefix": "wh-", "style": "alphanumeric", "length": 16},
            "rate_limit": {"remaining_changes": 2},
            "editable": true,
            "groups": [],
            "hidden_group_count": 0
        }],
        "surprise_field": 1
    }"#;

    const PROVIDER_ENDPOINT_JSON: &str = r#"{
        "id": "we_1",
        "url": "https://merchant.test/hooks/••••",
        "host": "merchant.test",
        "owner": "other",
        "events": ["charge.succeeded"],
        "enabled": true,
        "created_at": 1700000000,
        "fingerprint": "fp_1"
    }"#;

    /// Mutation: drop `encode_segment` from `connector_path` — the `%2F` in
    /// the expected URL is lost. Mutation: drop the `test_mode` query — the
    /// URL assertion fails.
    #[tokio::test]
    async fn retrieve_buyer_email_preference_sends_the_credential_set() {
        let (client, mock) = client_with(vec![Step::ok(
            r#"{"merchant_connector_id":"mca_1","connector":"whop","provider_account_id":"biz_1",
                "test_mode":true,"scope":"provider_account","send_customer_emails":null,
                "outcome":"current","observed_at":"2026-01-01T00:00:00Z","surprise_field":1}"#,
        )]);
        let out = client
            .connectors()
            .retrieve_buyer_email_preference("mer_1", "mca/1", true)
            .await
            .unwrap();
        assert_eq!(out.outcome, "current");
        assert_eq!(out.send_customer_emails, None);
        assert_eq!(out.extra["surprise_field"], 1);

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "GET");
        assert_eq!(
            seen[0].url,
            "https://api.test/account/mer_1/connectors/mca%2F1/buyer-email-preference?test_mode=true"
        );
    }

    /// Mutation: swap `send_customer_emails` and
    /// `expected_send_customer_emails` in `new` — the body assertions fail.
    #[tokio::test]
    async fn update_buyer_email_preference_puts_the_confirmed_change() {
        let (client, mock) = client_with(vec![Step::ok(
            r#"{"merchant_connector_id":"mca_1","connector":"whop","provider_account_id":"biz_1",
                "test_mode":false,"scope":"provider_account","send_customer_emails":false,
                "outcome":"verified","observed_at":"2026-01-01T00:00:00Z","surprise_field":1}"#,
        )]);
        let params = ConnectorBuyerMailUpdateRequest::new(false, "biz_1", true, false);
        let out = client
            .connectors()
            .update_buyer_email_preference("mer_1", "mca_1", &params)
            .await
            .unwrap();
        assert_eq!(out.outcome, "verified");
        assert_eq!(out.extra["surprise_field"], 1);

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "PUT");
        assert_eq!(
            seen[0].url,
            "https://api.test/account/mer_1/connectors/mca_1/buyer-email-preference"
        );
        assert_eq!(
            seen[0].body_json(),
            json!({
                "test_mode": false,
                "expected_provider_account_id": "biz_1",
                "send_customer_emails": false,
                "expected_send_customer_emails": true,
                "confirmed_account_wide": true
            })
        );
    }

    #[tokio::test]
    async fn list_by_profile_gets_the_profile_scoped_path() {
        let (client, mock) = client_with(vec![Step::ok(&format!("[{CONNECTOR_JSON}]"))]);
        let out = client.connectors().list_by_profile("mer/1").await.unwrap();
        assert_eq!(out[0].merchant_connector_id, "mca_1");

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "GET");
        assert_eq!(
            seen[0].url,
            "https://api.test/account/mer%2F1/profile/connectors"
        );
    }

    #[tokio::test]
    async fn add_shops_posts_the_profile_ids() {
        let (client, mock) = client_with(vec![Step::ok(SHOPS_JSON)]);
        let out = client
            .connectors()
            .add_shops("mer_1", "mca_1", &ConnectorShopsAddRequest::new(["pro_2"]))
            .await
            .unwrap();
        assert_eq!(out.assigned_profile_ids, ["pro_1", "pro_2"]);
        assert_eq!(out.extra["surprise_field"], 1);

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(
            seen[0].url,
            "https://api.test/account/mer_1/connectors/mca_1/shops"
        );
        assert_eq!(seen[0].body_json(), json!({"profile_ids": ["pro_2"]}));
    }

    /// Mutation: drop `params.validate()?` from `consolidate` — the colliding
    /// request reaches the mock and the `call_count` assertion fails.
    #[tokio::test]
    async fn consolidate_posts_the_preview_confirmation() {
        let (client, mock) = client_with(vec![Step::ok(
            r#"{
                "merchant_connector_id": "mca_1",
                "connector_name": "stripe",
                "dry_run": false,
                "consolidated": true,
                "preview_token": "tok_1",
                "accounts": [{"merchant_connector_id":"mca_1","kept":true,"eligibility":"kept","profile_ids":["pro_1"]}],
                "shops": [{"profile_id":"pro_1","served_by":["mca_1"],"enabled_before":true,"enabled_after":true,"currencies_after":null}],
                "conflicts": [{"setting":"label","values":[{"merchant_connector_ids":["mca_2"],"summary":{"label":"b"}}],"choosable":["mca_1","mca_2"]}],
                "blockers": [],
                "changes": {"routing_configs":1,"fallback_lists":0,"checkout_layouts":0,"surcharge_rules":0,
                    "hidden_accounts":0,"subscription_shop_configs":0,"product_references":0,
                    "shop_billing_settings":0,"role_grants":0,"saved_payment_methods":2,"customers":3,
                    "mandates":0,"subscriptions":0,"subscription_terms":0},
                "surprise_field": 1
            }"#,
        )]);
        let params = ConnectorConsolidationRequest::new(["mca_2"])
            .dry_run(false)
            .preview_token("tok_1")
            .choice("label", "mca_1");
        let out = client
            .connectors()
            .consolidate("mer_1", "mca_1", &params)
            .await
            .unwrap();
        assert!(out.consolidated);
        assert_eq!(out.accounts[0].eligibility, "kept");
        assert_eq!(out.conflicts[0].values[0].summary["label"], "b");
        assert_eq!(out.changes.as_ref().unwrap().saved_payment_methods, 2);
        assert_eq!(out.extra["surprise_field"], 1);

        {
            let seen = mock.seen.lock().unwrap();
            assert_eq!(seen[0].method, "POST");
            assert_eq!(
                seen[0].url,
                "https://api.test/account/mer_1/connectors/mca_1/consolidate"
            );
            assert_eq!(
                seen[0].body_json(),
                json!({
                    "merchant_connector_ids": ["mca_2"],
                    "dry_run": false,
                    "preview_token": "tok_1",
                    "choices": {"label": "mca_1"}
                })
            );
        }

        let mut bad = ConnectorConsolidationRequest::new(["mca_2"]);
        bad.extra.insert("dry_run".to_string(), json!(true));
        assert!(
            client
                .connectors()
                .consolidate("mer_1", "mca_1", &bad)
                .await
                .is_err()
        );
        assert_eq!(mock.call_count(), 1);
    }

    /// The consolidation is a POST without an idempotency key, so a 5xx must
    /// not replay it. Mutation: pass a key to `request` — the second step is
    /// consumed and `call_count` becomes 2.
    #[tokio::test]
    async fn consolidate_is_not_retried_on_a_server_error() {
        let (client, mock) = crate::http::mock::client_with_retries(
            vec![Step::status(503, "{}"), Step::ok("{}")],
            2,
        );
        let params = ConnectorConsolidationRequest::new(["mca_2"]);
        assert!(
            client
                .connectors()
                .consolidate("mer_1", "mca_1", &params)
                .await
                .is_err()
        );
        assert_eq!(mock.call_count(), 1);
    }

    #[tokio::test]
    async fn set_shop_disabled_posts_to_the_shop_path() {
        let (client, mock) = client_with(vec![Step::ok(SHOPS_JSON)]);
        let params = ConnectorShopUpdateRequest::new(true).reason("paused");
        client
            .connectors()
            .set_shop_disabled("mer_1", "mca_1", "pro/2", &params)
            .await
            .unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(
            seen[0].url,
            "https://api.test/account/mer_1/connectors/mca_1/shops/pro%2F2"
        );
        assert_eq!(
            seen[0].body_json(),
            json!({"disabled": true, "reason": "paused"})
        );
    }

    #[tokio::test]
    async fn remove_shop_deletes_the_shop_path() {
        let (client, mock) = client_with(vec![Step::ok(SHOPS_JSON)]);
        let out = client
            .connectors()
            .remove_shop("mer_1", "mca_1", "pro_2")
            .await
            .unwrap();
        assert_eq!(out.profile_id, "pro_1");
        assert_eq!(out.extra["surprise_field"], 1);

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "DELETE");
        assert_eq!(
            seen[0].url,
            "https://api.test/account/mer_1/connectors/mca_1/shops/pro_2"
        );
        assert!(seen[0].body.is_none());
    }

    #[tokio::test]
    async fn currencies_gets_and_decodes_the_policy() {
        let (client, mock) = client_with(vec![Step::ok(CURRENCY_POLICY_JSON)]);
        let out = client
            .connectors()
            .currencies("mer_1", "mca_1")
            .await
            .unwrap();
        assert_eq!(
            out.allowed_currencies.as_deref(),
            Some(&["EUR".to_string(), "USD".to_string()][..])
        );
        assert_eq!(out.conversion.convert_to.as_deref(), Some("EUR"));
        assert!(out.shops[0].conversion.is_none());
        assert!(out.impact.as_ref().unwrap()[0].removed_unbounded);
        assert_eq!(out.extra["surprise_field"], 1);

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "GET");
        assert_eq!(
            seen[0].url,
            "https://api.test/account/mer_1/connectors/mca_1/currencies"
        );
    }

    /// `null` is a value here. Mutation: serialize `allowed_currencies` as a
    /// plain `Option` — `allow_every_currency` stops sending the key and the
    /// body assertion fails.
    #[tokio::test]
    async fn set_currencies_sends_null_to_allow_every_currency() {
        let (client, mock) = client_with(vec![Step::ok(CURRENCY_POLICY_JSON)]);
        let params = ConnectorCurrencyPolicyUpdateRequest::new()
            .allow_every_currency()
            .conversion(ConnectorCurrencyConversionSetting::refuse())
            .dry_run(true);
        client
            .connectors()
            .set_currencies("mer_1", "mca_1", &params)
            .await
            .unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "PUT");
        assert_eq!(
            seen[0].url,
            "https://api.test/account/mer_1/connectors/mca_1/currencies"
        );
        assert_eq!(
            seen[0].body_json(),
            json!({"allowed_currencies": null, "conversion": {"convert_to": null}, "dry_run": true})
        );
    }

    /// An unset field is not sent, so it stays as it is. Mutation: drop
    /// `skip_serializing_if` on `conversion` — a `conversion` key appears.
    #[tokio::test]
    async fn set_shop_currencies_puts_only_the_fields_set() {
        let (client, mock) = client_with(vec![Step::ok(CURRENCY_POLICY_JSON)]);
        let params = ConnectorCurrencyPolicyUpdateRequest::new().allowed_currencies(["EUR"]);
        client
            .connectors()
            .set_shop_currencies("mer_1", "mca_1", "pro_1", &params)
            .await
            .unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "PUT");
        assert_eq!(
            seen[0].url,
            "https://api.test/account/mer_1/connectors/mca_1/shops/pro_1/currencies"
        );
        assert_eq!(seen[0].body_json(), json!({"allowed_currencies": ["EUR"]}));
    }

    #[tokio::test]
    async fn set_shop_currencies_sends_null_conversion_to_follow_the_account() {
        let (client, mock) = client_with(vec![Step::ok(CURRENCY_POLICY_JSON)]);
        let params = ConnectorCurrencyPolicyUpdateRequest::new()
            .follow_account_currencies()
            .follow_account_conversion();
        client
            .connectors()
            .set_shop_currencies("mer_1", "mca_1", "pro_1", &params)
            .await
            .unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(
            seen[0].body_json(),
            json!({"allowed_currencies": null, "conversion": null})
        );
    }

    #[tokio::test]
    async fn verify_vault_posts_the_profile() {
        let (client, mock) = client_with(vec![Step::ok(
            r#"{"passed":false,"checks":[{"id":"credentials","status":"fail","detail":"401"}],
                "processors":[{"merchant_connector_id":"mca_2","connector_name":"stripe","status":"hidable"}],
                "egress_ips_to_allowlist":["192.0.2.1"],"surprise_field":1}"#,
        )]);
        let out = client
            .connectors()
            .verify_vault("mer_1", "mca_1", &VaultVerifyRequest::new("pro_1"))
            .await
            .unwrap();
        assert!(!out.passed);
        assert_eq!(out.checks[0].detail.as_deref(), Some("401"));
        assert_eq!(out.processors[0].status, "hidable");
        assert_eq!(out.extra["surprise_field"], 1);

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(
            seen[0].url,
            "https://api.test/account/mer_1/connectors/mca_1/vault/verify"
        );
        assert_eq!(seen[0].body_json(), json!({"profile_id": "pro_1"}));
    }

    #[tokio::test]
    async fn vault_outages_gets_the_account_path() {
        let (client, mock) = client_with(vec![Step::ok(
            r#"{"outages":[{"profile_id":"pro_1","profile_name":"Shop","vault_connector_id":"mca_v",
                "vault_connector_name":"vgs","cause":"limit_reached","since":"2026-01-01T00:00:00Z"}],
                "surprise_field":1}"#,
        )]);
        let out = client.connectors().vault_outages("mer/1").await.unwrap();
        assert_eq!(out.outages[0].cause, "limit_reached");
        assert_eq!(out.extra["surprise_field"], 1);

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "GET");
        assert_eq!(
            seen[0].url,
            "https://api.test/account/mer%2F1/vault/outages"
        );
    }

    #[tokio::test]
    async fn preview_vault_routes_posts_the_profile_and_environment() {
        let (client, mock) = client_with(vec![Step::ok(
            r#"{"vault_id":"tnt_1","environment":"sandbox","desired_fingerprint":"d1",
                "desired_upstream_hosts":["api.stripe.com"],"current_fingerprint":null,
                "changes":[{"route_id":"r1","purpose":"collect","change":"create","field_changes":[]}],
                "warnings":[{"code":"no_processor","detail":"none"}],"surprise_field":1}"#,
        )]);
        let params = VaultRoutesPreviewRequest::new("pro_1").environment("sandbox");
        let out = client
            .connectors()
            .preview_vault_routes("mer_1", "mca_1", &params)
            .await
            .unwrap();
        assert_eq!(out.desired_fingerprint, "d1");
        assert!(out.current_fingerprint.is_none());
        assert_eq!(out.changes[0].change, "create");
        assert_eq!(out.warnings[0].code, "no_processor");
        assert_eq!(out.extra["surprise_field"], 1);

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(
            seen[0].url,
            "https://api.test/account/mer_1/connectors/mca_1/vault/routes/preview"
        );
        assert_eq!(
            seen[0].body_json(),
            json!({"profile_id": "pro_1", "environment": "sandbox"})
        );
    }

    /// The router refuses an absent `expected_current_fingerprint`. Mutation:
    /// add `skip_serializing_if = "Option::is_none"` to it — the `null` key
    /// disappears and the body assertion fails.
    #[tokio::test]
    async fn apply_vault_routes_sends_a_null_current_fingerprint() {
        let (client, mock) = client_with(vec![Step::ok(
            r#"{"applied":true,"route_ids":{"collect":"r1","reveal":"r2"},
                "collect_route_id_stored":true,"warnings":[],
                "verification":{"established":["routes"],"not_established":[]},"surprise_field":1}"#,
        )]);
        let params = VaultRoutesApplyRequest::new("pro_1", None, "d1");
        let out = client
            .connectors()
            .apply_vault_routes("mer_1", "mca_1", &params)
            .await
            .unwrap();
        assert!(out.applied);
        assert_eq!(out.route_ids.reveal, "r2");
        assert_eq!(out.verification.unwrap().established, ["routes"]);
        assert_eq!(out.extra["surprise_field"], 1);

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(
            seen[0].url,
            "https://api.test/account/mer_1/connectors/mca_1/vault/routes/apply"
        );
        assert_eq!(
            seen[0].body_json(),
            json!({
                "profile_id": "pro_1",
                "expected_current_fingerprint": null,
                "expected_desired_fingerprint": "d1"
            })
        );
    }

    #[tokio::test]
    async fn register_whop_apple_pay_domains_posts_the_urls() {
        let (client, mock) = client_with(vec![Step::ok(
            r#"{"environment":"sandbox","results":[{"url":"https://shop.test","domain":"shop.test",
                "status":"verified","whop_domain_id":"dom_1"}],"surprise_field":1}"#,
        )]);
        let params =
            WhopApplePayDomainsRegisterRequest::new(["https://shop.test"]).environment("sandbox");
        let out = client
            .connectors()
            .register_whop_apple_pay_domains("mer_1", "mca_1", &params)
            .await
            .unwrap();
        assert_eq!(out.results[0].status, "verified");
        assert_eq!(out.results[0].whop_domain_id.as_deref(), Some("dom_1"));
        assert_eq!(out.extra["surprise_field"], 1);

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(
            seen[0].url,
            "https://api.test/account/mer_1/connectors/mca_1/whop/apple-pay-domains"
        );
        assert_eq!(
            seen[0].body_json(),
            json!({"urls": ["https://shop.test"], "environment": "sandbox"})
        );
    }

    /// Mutation: build the path with `connector_path` instead of
    /// `webhook_path` — the `/webhooks/` segment moves and the URL fails.
    #[tokio::test]
    async fn webhook_address_gets_the_address_path() {
        let (client, mock) = client_with(vec![Step::ok(WEBHOOK_ADDRESS_JSON)]);
        let out = client
            .connectors()
            .webhook_address("mer_1", "mca/1")
            .await
            .unwrap();
        assert_eq!(out.management, "managed");
        assert_eq!(out.constraints.max_changes, 3);
        assert_eq!(out.environments[0].format.as_ref().unwrap().length, 16);
        assert_eq!(out.environments[0].rate_limit.remaining_changes, 2);
        assert_eq!(out.extra["surprise_field"], 1);

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "GET");
        assert_eq!(
            seen[0].url,
            "https://api.test/account/mer_1/connectors/webhooks/mca%2F1/address"
        );
    }

    #[tokio::test]
    async fn preview_webhook_address_posts_the_proposal() {
        let (client, mock) = client_with(vec![Step::ok(
            r#"{"valid":false,"errors":[{"field":"alias","code":"too_short"}],
                "identifier_final":false,"changes_address":true,
                "rate_limit":{"remaining_changes":0,"next_change_allowed_at":"2026-02-01T00:00:00Z"},
                "editable":true,"requires_shared_confirmation":true,
                "groups":[{"credentials_sha256":"abc","contains_this_connector":true,
                    "current_url":"https://api.test/webhooks/x","accounts":[],"hidden_account_count":0}],
                "hidden_group_count":1,"surprise_field":1}"#,
        )]);
        let params = WebhookAddressRequest::new("anonymous")
            .environment("live")
            .format(WebhookAddressFormat::new("wh-", "alphanumeric", 16));
        let out = client
            .connectors()
            .preview_webhook_address("mer_1", "mca_1", &params)
            .await
            .unwrap();
        assert!(!out.valid);
        assert_eq!(out.errors[0].code, "too_short");
        assert!(out.groups[0].contains_this_connector);
        assert_eq!(out.hidden_group_count, 1);
        assert_eq!(out.extra["surprise_field"], 1);

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(
            seen[0].url,
            "https://api.test/account/mer_1/connectors/webhooks/mca_1/address/preview"
        );
        assert_eq!(
            seen[0].body_json(),
            json!({
                "environment": "live",
                "mode": "anonymous",
                "format": {"prefix": "wh-", "style": "alphanumeric", "length": 16}
            })
        );
    }

    #[tokio::test]
    async fn update_webhook_address_puts_the_confirmed_address() {
        let (client, mock) = client_with(vec![Step::ok(WEBHOOK_ADDRESS_JSON)]);
        let params = WebhookAddressRequest::new("custom")
            .environment("live")
            .alias("my-shop")
            .confirm_shared(true);
        client
            .connectors()
            .update_webhook_address("mer_1", "mca_1", &params)
            .await
            .unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "PUT");
        assert_eq!(
            seen[0].url,
            "https://api.test/account/mer_1/connectors/webhooks/mca_1/address"
        );
        assert_eq!(
            seen[0].body_json(),
            json!({"environment": "live", "mode": "custom", "alias": "my-shop", "confirm_shared": true})
        );
    }

    #[tokio::test]
    async fn list_provider_webhooks_sends_the_environment() {
        let (client, mock) = client_with(vec![Step::ok(&format!(
            r#"{{"connector":"stripe","environment":"sandbox","coverage":"account",
                "capabilities":{{"create":true,"update_url":true,"update_events":true,
                    "update_enabled":true,"delete":true,"replace_all":false}},
                "endpoint_limit":16,"required_events":["charge.succeeded"],
                "managed":{{"status":"registered","missing_events":[]}},
                "endpoints":[{PROVIDER_ENDPOINT_JSON}],"editable":true,
                "read_at":"2026-01-01T00:00:00Z","surprise_field":1}}"#
        ))]);
        let out = client
            .connectors()
            .list_provider_webhooks("mer_1", "mca_1", "sandbox")
            .await
            .unwrap();
        assert_eq!(out.endpoint_limit, Some(16));
        assert!(!out.capabilities.replace_all);
        assert_eq!(out.managed.status, "registered");
        assert_eq!(out.endpoints[0].created_at, Some(1_700_000_000));
        assert_eq!(out.extra["surprise_field"], 1);

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "GET");
        assert_eq!(
            seen[0].url,
            "https://api.test/account/mer_1/connectors/webhooks/mca_1/provider?environment=sandbox"
        );
    }

    #[tokio::test]
    async fn create_provider_webhook_posts_and_keeps_the_secret_out_of_debug() {
        let (client, mock) = client_with(vec![Step::ok(&format!(
            r#"{{"endpoint":{PROVIDER_ENDPOINT_JSON},"signing_secret":"whsec_topsecret","surprise_field":1}}"#
        ))]);
        let params = ProviderWebhookCreateRequest::new(
            "live",
            "https://merchant.test/hooks/tok_secret",
            ["charge.succeeded"],
        );
        let out = client
            .connectors()
            .create_provider_webhook("mer_1", "mca_1", &params)
            .await
            .unwrap();
        assert_eq!(out.signing_secret.as_deref(), Some("whsec_topsecret"));
        assert_eq!(out.endpoint.fingerprint, "fp_1");
        assert_eq!(out.extra["surprise_field"], 1);
        // Mutation: derive `Debug` on either type — these go red.
        assert!(!format!("{out:?}").contains("whsec_topsecret"));
        assert!(!format!("{params:?}").contains("tok_secret"));

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(
            seen[0].url,
            "https://api.test/account/mer_1/connectors/webhooks/mca_1/provider"
        );
        assert_eq!(
            seen[0].body_json(),
            json!({
                "environment": "live",
                "url": "https://merchant.test/hooks/tok_secret",
                "events": ["charge.succeeded"]
            })
        );
    }

    #[tokio::test]
    async fn update_provider_webhook_patches_the_encoded_webhook_path() {
        let (client, mock) = client_with(vec![Step::ok(&format!(
            r#"{{"surprise_field":1,{}"#,
            &PROVIDER_ENDPOINT_JSON.trim_start()[1..]
        ))]);
        let params = ProviderWebhookUpdateRequest::new("live", "fp_1")
            .url("https://merchant.test/hooks/tok_secret")
            .events(["charge.refunded"])
            .enabled(false);
        let out = client
            .connectors()
            .update_provider_webhook("mer_1", "mca_1", "we/1", &params)
            .await
            .unwrap();
        assert_eq!(out.id, "we_1");
        assert_eq!(out.extra["surprise_field"], 1);
        // Mutation: derive `Debug` — the destination's token leaks.
        assert!(!format!("{params:?}").contains("tok_secret"));

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "PATCH");
        assert_eq!(
            seen[0].url,
            "https://api.test/account/mer_1/connectors/webhooks/mca_1/provider/we%2F1"
        );
        assert_eq!(
            seen[0].body_json(),
            json!({
                "environment": "live",
                "fingerprint": "fp_1",
                "url": "https://merchant.test/hooks/tok_secret",
                "events": ["charge.refunded"],
                "enabled": false
            })
        );
    }

    #[tokio::test]
    async fn delete_provider_webhook_posts_to_the_delete_path() {
        let (client, mock) = client_with(vec![Step::ok(
            r#"{"id":"we_1","url":"https://merchant.test/••••","outcome":"deleted",
                "surprise_field":1}"#,
        )]);
        let params = ProviderWebhookDeleteRequest::new("sandbox", "fp_1").confirm_managed(true);
        let out = client
            .connectors()
            .delete_provider_webhook("mer_1", "mca_1", "we_1", &params)
            .await
            .unwrap();
        assert_eq!(out.outcome, "deleted");
        assert_eq!(out.error_message, None);
        assert_eq!(out.extra["surprise_field"], 1);

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(
            seen[0].url,
            "https://api.test/account/mer_1/connectors/webhooks/mca_1/provider/we_1/delete"
        );
        assert_eq!(
            seen[0].body_json(),
            json!({"environment": "sandbox", "fingerprint": "fp_1", "confirm_managed": true})
        );
        assert!(!seen[0].had_idempotency_key());
    }

    #[tokio::test]
    async fn preview_provider_webhook_replace_sends_the_environment() {
        let (client, mock) = client_with(vec![Step::ok(&format!(
            r#"{{"connector":"stripe","environment":"live","coverage":"account",
                "sequence":"register_first","managed":{{"status":"registered"}},
                "delete":[{PROVIDER_ENDPOINT_JSON}],"keep":[],"accounts":[],
                "hidden_account_count":0,"editable":true,"surprise_field":1}}"#
        ))]);
        let out = client
            .connectors()
            .preview_provider_webhook_replace("mer_1", "mca_1", "live")
            .await
            .unwrap();
        assert_eq!(out.sequence, "register_first");
        assert_eq!(out.delete[0].fingerprint, "fp_1");
        assert!(out.keep.is_empty());
        assert_eq!(out.extra["surprise_field"], 1);

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "GET");
        assert_eq!(
            seen[0].url,
            "https://api.test/account/mer_1/connectors/webhooks/mca_1/provider/replace?environment=live"
        );
    }

    #[tokio::test]
    async fn replace_provider_webhooks_posts_the_confirmations() {
        let (client, mock) = client_with(vec![Step::ok(
            r#"{"status":"completed","sequence":"delete_first",
                "managed":{"status":"registered"},
                "results":[{"id":"we_1","url":"https://merchant.test/••••","outcome":"deleted"}],
                "remaining":[],"unconfirmed":[],"surprise_field":1}"#,
        )]);
        let params = ProviderWebhookReplaceRequest::new(
            "live",
            vec![ProviderWebhookConfirmation::new("we_1", "fp_1")],
        )
        .accept_delete_first(true);
        let out = client
            .connectors()
            .replace_provider_webhooks("mer_1", "mca_1", &params)
            .await
            .unwrap();
        assert_eq!(out.status, "completed");
        assert_eq!(out.results[0].outcome, "deleted");
        assert_eq!(out.extra["surprise_field"], 1);

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(
            seen[0].url,
            "https://api.test/account/mer_1/connectors/webhooks/mca_1/provider/replace"
        );
        assert_eq!(
            seen[0].body_json(),
            json!({
                "environment": "live",
                "confirmed": [{"id": "we_1", "fingerprint": "fp_1"}],
                "accept_delete_first": true
            })
        );
    }

    /// A blind replace must not be replayed on a 5xx: it deletes webhooks at
    /// the provider. Mutation: make the POST inherently idempotent — the
    /// mock sees a second call.
    #[tokio::test]
    async fn replace_provider_webhooks_is_not_retried_on_a_server_error() {
        let (client, mock) = crate::http::mock::client_with_retries(
            vec![Step::status(503, "{}"), Step::status(503, "{}")],
            2,
        );
        let params = ProviderWebhookReplaceRequest::new("live", vec![]);
        assert!(
            client
                .connectors()
                .replace_provider_webhooks("mer_1", "mca_1", &params)
                .await
                .is_err()
        );
        assert_eq!(mock.call_count(), 1);
    }

    /// Drift guards: each `*_NAMED` list covers every wire key its request
    /// serializes with every field set.
    fn assert_named_covers(value: Value, named: &[&str], list: &str) {
        for key in value.as_object().expect("serializes to an object").keys() {
            assert!(
                named.contains(&key.as_str()),
                "{list} is missing wire key `{key}`"
            );
        }
    }

    #[test]
    fn connector_consolidation_request_named_fields_are_complete() {
        let req = ConnectorConsolidationRequest::new(["mca_2"])
            .dry_run(true)
            .preview_token("tok")
            .choice("label", "mca_1");
        assert_named_covers(
            serde_json::to_value(req).unwrap(),
            CONNECTOR_CONSOLIDATION_REQUEST_NAMED,
            "CONNECTOR_CONSOLIDATION_REQUEST_NAMED",
        );
    }

    #[test]
    fn connector_shop_update_request_named_fields_are_complete() {
        let req = ConnectorShopUpdateRequest::new(true).reason("r");
        assert_named_covers(
            serde_json::to_value(req).unwrap(),
            CONNECTOR_SHOP_UPDATE_REQUEST_NAMED,
            "CONNECTOR_SHOP_UPDATE_REQUEST_NAMED",
        );
    }

    #[test]
    fn connector_currency_policy_update_request_named_fields_are_complete() {
        let req = ConnectorCurrencyPolicyUpdateRequest::new()
            .allowed_currencies(["EUR"])
            .conversion(ConnectorCurrencyConversionSetting::convert_to("EUR"))
            .dry_run(true);
        assert_named_covers(
            serde_json::to_value(req).unwrap(),
            CONNECTOR_CURRENCY_POLICY_UPDATE_REQUEST_NAMED,
            "CONNECTOR_CURRENCY_POLICY_UPDATE_REQUEST_NAMED",
        );
    }

    #[test]
    fn vault_routes_preview_request_named_fields_are_complete() {
        let req = VaultRoutesPreviewRequest::new("pro_1").environment("live");
        assert_named_covers(
            serde_json::to_value(req).unwrap(),
            VAULT_ROUTES_PREVIEW_REQUEST_NAMED,
            "VAULT_ROUTES_PREVIEW_REQUEST_NAMED",
        );
    }

    #[test]
    fn vault_routes_apply_request_named_fields_are_complete() {
        let req =
            VaultRoutesApplyRequest::new("pro_1", Some("c1".to_string()), "d1").environment("live");
        assert_named_covers(
            serde_json::to_value(req).unwrap(),
            VAULT_ROUTES_APPLY_REQUEST_NAMED,
            "VAULT_ROUTES_APPLY_REQUEST_NAMED",
        );
    }

    #[test]
    fn webhook_address_request_named_fields_are_complete() {
        let req = WebhookAddressRequest::new("anonymous")
            .environment("live")
            .alias("my-shop")
            .format(WebhookAddressFormat::new("wh-", "alphanumeric", 16))
            .regenerate(true)
            .confirm_shared(true);
        assert_named_covers(
            serde_json::to_value(req).unwrap(),
            WEBHOOK_ADDRESS_REQUEST_NAMED,
            "WEBHOOK_ADDRESS_REQUEST_NAMED",
        );
    }

    /// Mutation: return `Ok(())` from any of these `validate` impls — its
    /// assertion goes red.
    #[test]
    fn new_request_validators_reject_colliding_extra_keys() {
        fn expect_collision(result: Result<()>, key: &str) {
            match result.unwrap_err() {
                DelopayError::InvalidRequest(msg) => assert!(msg.contains(key), "{msg}"),
                other => panic!("expected InvalidRequest, got {other:?}"),
            }
        }
        let mut a = ConnectorConsolidationRequest::new(["mca_2"]);
        a.extra.insert("choices".to_string(), json!({}));
        expect_collision(a.validate(), "choices");
        let mut b = ConnectorShopUpdateRequest::new(true);
        b.extra.insert("disabled".to_string(), json!(false));
        expect_collision(b.validate(), "disabled");
        let mut c = ConnectorCurrencyPolicyUpdateRequest::new();
        c.extra.insert("conversion".to_string(), json!(null));
        expect_collision(c.validate(), "conversion");
        let mut d = VaultRoutesPreviewRequest::new("pro_1");
        d.extra.insert("profile_id".to_string(), json!("x"));
        expect_collision(d.validate(), "profile_id");
        let mut e = VaultRoutesApplyRequest::new("pro_1", None, "d1");
        e.extra
            .insert("expected_desired_fingerprint".to_string(), json!("x"));
        expect_collision(e.validate(), "expected_desired_fingerprint");
        let mut f = WebhookAddressRequest::new("standard");
        f.extra.insert("mode".to_string(), json!("custom"));
        expect_collision(f.validate(), "mode");
    }

    /// A client built with `with_idempotency_key` over a mock that answers
    /// 503 twice, with a retry budget of 2.
    fn keyed_client_over_503s() -> (
        crate::Delopay,
        std::sync::Arc<crate::http::mock::MockTransport>,
    ) {
        let (client, mock) = crate::http::mock::client_with_retries(
            vec![Step::status(503, "{}"), Step::status(503, "{}")],
            2,
        );
        (client.with_idempotency_key("client-wide-key"), mock)
    }

    /// Assert the one request sent carried no `Idempotency-Key` and was not
    /// replayed after its 503.
    fn assert_sent_once_unkeyed(mock: &crate::http::mock::MockTransport) {
        assert_eq!(mock.call_count(), 1, "a 503 was replayed");
        assert!(
            !mock.seen.lock().unwrap()[0].had_idempotency_key(),
            "the client-wide key was inherited"
        );
    }

    /// Mutation: switch the call site back to `request(.., None)` — the
    /// client-wide key is sent and the 503 replayed, so both assertions fail.
    #[tokio::test]
    async fn new_writes_do_not_inherit_the_client_key() {
        let (client, mock) = keyed_client_over_503s();
        let params = VaultVerifyRequest::new("pro_1");
        assert!(
            client
                .connectors()
                .verify_vault("mer_1", "mca_1", &params)
                .await
                .is_err()
        );
        assert_sent_once_unkeyed(&mock);

        let (client, mock) = keyed_client_over_503s();
        let params = ProviderWebhookReplaceRequest::new("live", vec![]);
        assert!(
            client
                .connectors()
                .replace_provider_webhooks("mer_1", "mca_1", &params)
                .await
                .is_err()
        );
        assert_sent_once_unkeyed(&mock);
    }
}