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
//! The `routing` resource: create and manage payment routing algorithms.
//!
//! Routing rules decide which gateway connector handles each payment, based on
//! card type, currency, amount, or custom conditions. Sub-resources hang off
//! it, among them:
//!
//! - [`Routing::surcharge_rules`] — merchant-friendly, per-payment-method
//!   surcharge rules that avoid hand-writing the Euclid DSL.
//!
//! Routing *algorithm* bodies stay open JSON — they are an adjacently-tagged
//! `{type, data}` union; see the API reference.

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::routing::{
    ActiveRoutingConfig, CheckoutThemeConversionResponse, CheckoutThemeProgramResponse,
    ConnectorCapOverride, ConnectorCapOverrideList, ConnectorCapOverrides, DefaultProfileRouting,
    MerchantRoutingAlgorithm, ProfileDefaultRoutingConfig, RoutableConnectorChoice,
    RoutingConfigDeleteResponse, RoutingConfigHistoryResponse, RoutingConnectorCapReset,
    RoutingDictionary, RoutingDictionaryRecord, RoutingVolumeCounters, SurchargeRuleResponse,
};
use crate::http::client::Inner;
use crate::http::transport::HttpMethod;
use crate::resources::ValidateRequest;

// `MethodSurcharge` and `PerMethodSurchargeItem` are wire values on both the
// request and the response side, so they live in `core::models::routing`
// (compiled without the `client` feature) and are re-exported here, where
// callers building a surcharge program expect to find them.
pub use crate::core::models::routing::{
    MethodSurcharge, PerMethodSurchargeItem, SurchargeCondition,
};
// The cap types are wire values on both sides of the connector-cap endpoints,
// so they live in `core::models::routing` and are re-exported here, where a
// caller setting a cap expects to find them.
pub use crate::core::models::routing::{
    RoutingConnectorCap, RoutingConnectorCapSchedule, RoutingConnectorCapScheduleEntry,
    RoutingConnectorCaps,
};

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

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

    /// The merchant-friendly surcharge-rules sub-resource
    /// (`/routing/surcharge/rules`).
    pub fn surcharge_rules(&self) -> SurchargeRules {
        SurchargeRules::new(self.inner.clone())
    }

    /// The checkout theme rules sub-resource
    /// (`/routing/checkout-theme/rules`).
    pub fn checkout_theme_rules(&self) -> CheckoutThemeRules {
        CheckoutThemeRules::new(self.inner.clone())
    }

    /// Create a new routing algorithm.
    ///
    /// Returns the metadata record for the created configuration; the full
    /// algorithm body is not echoed back — use [`retrieve`](Self::retrieve) if
    /// you need it.
    pub async fn create(
        &self,
        params: &RoutingConfigCreateRequest,
    ) -> Result<RoutingDictionaryRecord> {
        params.validate()?;
        let body = to_json_vec(params)?;
        self.inner
            .request(HttpMethod::Post, "/routing", Some(&body), &[], None)
            .await
    }

    /// Retrieve a routing algorithm by its ID, including the algorithm body.
    pub async fn retrieve(&self, algorithm_id: &str) -> Result<MerchantRoutingAlgorithm> {
        let path = format!("/routing/{}", encode_segment(algorithm_id));
        self.inner
            .request(HttpMethod::Get, &path, None, &[], None)
            .await
    }

    /// Activate a routing algorithm, making it the active routing strategy.
    ///
    /// Always sends a JSON body (`{}` when `params` is `None`) so the request
    /// carries the `Content-Type: application/json` header the server
    /// requires.
    pub async fn activate(
        &self,
        algorithm_id: &str,
        params: Option<&RoutingActivatePayload>,
    ) -> Result<RoutingDictionaryRecord> {
        let path = format!("/routing/{}/activate", encode_segment(algorithm_id));
        let body = body_or_empty_object(params)?;
        self.inner
            .request(HttpMethod::Post, &path, Some(&body), &[], None)
            .await
    }

    /// Deactivate the currently active routing algorithm, falling back to
    /// default routing.
    ///
    /// Always sends a JSON body (`{}` when `params` is `None`), for the same
    /// reason as [`activate`](Self::activate).
    pub async fn deactivate(
        &self,
        params: Option<&RoutingDeactivateRequest>,
    ) -> Result<RoutingDictionaryRecord> {
        if let Some(p) = params {
            p.validate()?;
        }
        let body = body_or_empty_object(params)?;
        self.inner
            .request(
                HttpMethod::Post,
                "/routing/deactivate",
                Some(&body),
                &[],
                None,
            )
            .await
    }

    /// List all routing algorithms for the current merchant (records plus the
    /// currently active ID).
    pub async fn list(&self) -> Result<RoutingDictionary> {
        self.inner
            .request(HttpMethod::Get, "/routing", None, &[], None)
            .await
    }

    /// Every content window a routing configuration has had, oldest first
    /// (`GET /routing/{algorithm_id}/history`).
    ///
    /// A configuration's rule can be edited in place, so this is what makes
    /// "which rule decided this payment" answerable after the fact.
    ///
    /// `limit` and `offset` page over the whole timeline including the live
    /// window, so a page holds at most `limit` entries and the live one — the
    /// only entry without a `valid_until` — comes back on exactly one page.
    /// Advance `offset` by `limit`; a page past the end is empty, and
    /// `total_count` says where that end is without probing for it.
    pub async fn history(
        &self,
        algorithm_id: &str,
        limit: Option<i32>,
        offset: Option<i32>,
    ) -> Result<RoutingConfigHistoryResponse> {
        let path = format!("/routing/{}/history", encode_segment(algorithm_id));
        let mut query: Vec<(&str, String)> = Vec::new();
        if let Some(limit) = limit {
            query.push(("limit", limit.to_string()));
        }
        if let Some(offset) = offset {
            query.push(("offset", offset.to_string()));
        }
        self.inner
            .request(HttpMethod::Get, &path, None, &query, None)
            .await
    }

    /// Soft-delete a static routing configuration (`DELETE /routing/{id}`).
    ///
    /// It disappears from every list and read while its version history stays
    /// server-side for audit.
    ///
    /// The backend refuses (400, `IR_16`) the **live** configuration of a shop —
    /// deactivate it first — and refuses (400) any kind the dashboard cannot
    /// build (`dynamic`, `three_ds_decision_rule`) as well as payout
    /// configurations.
    pub async fn delete(&self, algorithm_id: &str) -> Result<RoutingConfigDeleteResponse> {
        let path = format!("/routing/{}", encode_segment(algorithm_id));
        self.inner
            .request(HttpMethod::Delete, &path, None, &[], None)
            .await
    }

    /// One shop's default fallback routing
    /// (`GET /routing/default/profile/{profile_id}`).
    ///
    /// The narrow counterpart of [`default_profile`](Self::default_profile),
    /// which returns every shop of the merchant and needs merchant-level
    /// routing read — so a shop-scoped role could set its own default through
    /// [`update_default_profile`](Self::update_default_profile) and never read
    /// it back. This read needs profile-level routing read and is pinned to the
    /// caller's own shop: asking for a sibling shop is refused.
    pub async fn default_for_profile(
        &self,
        profile_id: &str,
    ) -> Result<ProfileDefaultRoutingConfig> {
        let path = format!("/routing/default/profile/{}", encode_segment(profile_id));
        self.inner
            .request(HttpMethod::Get, &path, None, &[], None)
            .await
    }

    /// The live `routing_volume` counters behind a shop's active advanced
    /// program (`GET /routing/volume-counters/{profile_id}`), one per distinct
    /// budget the program reads.
    ///
    /// It answers "what will routing compare against right now", not "what did
    /// the shop turn over": the counters live in Redis only, and a lost Redis
    /// restarts a window at zero.
    ///
    /// A `routing_volume` condition may also carry its own budget: the
    /// `volume_window`, `volume_scope` and `volume_currency` keys are read from
    /// the condition's own `metadata` first and fall back to the program's, so
    /// "£500 a day on this rule and £5 000 a month on that one" is one program
    /// and shows up here as two counters.
    pub async fn volume_counters(&self, profile_id: &str) -> Result<RoutingVolumeCounters> {
        let path = format!("/routing/volume-counters/{}", encode_segment(profile_id));
        self.inner
            .request(HttpMethod::Get, &path, None, &[], None)
            .await
    }

    /// A shop's lifetime per-connector payment caps, each with how much of it
    /// is already spent (`GET /routing/connector-caps/{profile_id}`).
    pub async fn connector_caps(&self, profile_id: &str) -> Result<RoutingConnectorCaps> {
        let path = format!("/routing/connector-caps/{}", encode_segment(profile_id));
        self.inner
            .request(HttpMethod::Get, &path, None, &[], None)
            .await
    }

    /// Replace a shop's per-connector payment caps
    /// (`PUT /routing/connector-caps/{profile_id}`).
    ///
    /// Whole-set replacement, not a patch: the list sent becomes the complete
    /// set of capped connector accounts, and an empty list clears them all —
    /// which is how acquirer onboarding finishes, the new account ceasing to
    /// be a special case.
    ///
    /// Every account named must belong to this shop; one that does not is
    /// refused. `used` and `reserved` are ignored on the way in.
    pub async fn set_connector_caps(
        &self,
        profile_id: &str,
        caps: &RoutingConnectorCaps,
    ) -> Result<RoutingConnectorCaps> {
        let path = format!("/routing/connector-caps/{}", encode_segment(profile_id));
        let body = to_json_vec(caps)?;
        self.inner
            .request(HttpMethod::Put, &path, Some(&body), &[], None)
            .await
    }

    /// Reset one limit's usage for the window open now
    /// (`POST /routing/connector-caps/{profile_id}/reset`).
    ///
    /// What settled payments spent stops counting, so the account takes
    /// payments again. Payments still in flight keep their hold. The
    /// account's other limit is untouched. Refused (422) for an account with
    /// no limit in that unit.
    pub async fn reset_connector_cap_usage(
        &self,
        profile_id: &str,
        params: &RoutingConnectorCapResetRequest,
    ) -> Result<RoutingConnectorCapReset> {
        let path = format!(
            "/routing/connector-caps/{}/reset",
            encode_segment(profile_id)
        );
        let body = to_json_vec(params)?;
        self.inner
            .request_body_keyed_with_query(HttpMethod::Post, &path, Some(&body), &[], None)
            .await
    }

    /// Every connector cap override of the merchant: the accounts whose
    /// limits a project or shop overrides
    /// (`GET /routing/connector-caps/overrides`).
    pub async fn connector_cap_overrides(&self) -> Result<ConnectorCapOverrideList> {
        self.inner
            .request(
                HttpMethod::Get,
                "/routing/connector-caps/overrides",
                None,
                &[],
                None,
            )
            .await
    }

    /// One connector account's overrides, and for every shop the account
    /// takes payments in, which limits apply there and where they come from
    /// (`GET /routing/connector-caps/accounts/{merchant_connector_id}/overrides`).
    pub async fn account_connector_cap_overrides(
        &self,
        merchant_connector_id: &str,
    ) -> Result<ConnectorCapOverrides> {
        let path = format!(
            "/routing/connector-caps/accounts/{}/overrides",
            encode_segment(merchant_connector_id)
        );
        self.inner
            .request(HttpMethod::Get, &path, None, &[], None)
            .await
    }

    /// Override an account's limits for one project (and every shop below
    /// it) or one shop
    /// (`PUT /routing/connector-caps/accounts/{merchant_connector_id}/overrides/{level}/{scope_id}`).
    ///
    /// `level` is `"project"` or `"shop"`. Replaces an existing override of
    /// the same target, keeping the usage its current window already counted.
    pub async fn set_connector_cap_override(
        &self,
        merchant_connector_id: &str,
        level: &str,
        scope_id: &str,
        params: &ConnectorCapOverrideRequest,
    ) -> Result<ConnectorCapOverride> {
        params.validate()?;
        let path = cap_override_path(merchant_connector_id, level, scope_id);
        let body = to_json_vec(params)?;
        self.inner
            .request_body_keyed_with_query(HttpMethod::Put, &path, Some(&body), &[], None)
            .await
    }

    /// Remove an account's override for one project or shop; the next level
    /// up applies again. Answers the override removed
    /// (`DELETE /routing/connector-caps/accounts/{merchant_connector_id}/overrides/{level}/{scope_id}`).
    pub async fn delete_connector_cap_override(
        &self,
        merchant_connector_id: &str,
        level: &str,
        scope_id: &str,
    ) -> Result<ConnectorCapOverride> {
        let path = cap_override_path(merchant_connector_id, level, scope_id);
        self.inner
            .request_body_keyed_with_query(HttpMethod::Delete, &path, None, &[], None)
            .await
    }

    /// A shop's dated limit schedule
    /// (`GET /routing/connector-cap-schedules/{profile_id}`).
    pub async fn connector_cap_schedules(
        &self,
        profile_id: &str,
    ) -> Result<RoutingConnectorCapSchedule> {
        let path = cap_schedule_path(profile_id, "");
        self.inner
            .request(HttpMethod::Get, &path, None, &[], None)
            .await
    }

    /// Replace a shop's complete limit schedule over its last-read revision
    /// (`PUT /routing/connector-cap-schedules/{profile_id}`).
    ///
    /// Remove an entry to cancel it; the ordinary caps are unchanged.
    /// Instants need explicit offsets, and overlapping entries for the same
    /// account and unit are refused. A router that offers schedules lists
    /// `"limit_schedules"` in the `features` of
    /// [`connector_caps`](Self::connector_caps); check it first when the
    /// router may be older.
    pub async fn set_connector_cap_schedules(
        &self,
        profile_id: &str,
        schedule: &RoutingConnectorCapSchedule,
    ) -> Result<RoutingConnectorCapSchedule> {
        let path = cap_schedule_path(profile_id, "");
        let body = to_json_vec(schedule)?;
        self.inner
            .request_body_keyed_with_query(HttpMethod::Put, &path, Some(&body), &[], None)
            .await
    }

    /// Change the drawn value of an active scheduled range, keeping all
    /// usage (`POST /routing/connector-cap-schedules/{profile_id}/shuffle`).
    pub async fn shuffle_connector_cap_schedule(
        &self,
        profile_id: &str,
        params: &RoutingConnectorCapScheduleShuffle,
    ) -> Result<RoutingConnectorCaps> {
        let path = cap_schedule_path(profile_id, "/shuffle");
        let body = to_json_vec(params)?;
        self.inner
            .request_body_keyed_with_query(HttpMethod::Post, &path, Some(&body), &[], None)
            .await
    }

    /// Rendered-to-paid checkout conversion, per appearance variant and
    /// segment (`GET /routing/checkout-theme/conversion`).
    ///
    /// Rates, intervals, verdicts and the variant-vs-default test are
    /// computed server-side: render them as they come.
    pub async fn checkout_theme_conversion(
        &self,
        params: &CheckoutThemeConversionParams,
    ) -> Result<CheckoutThemeConversionResponse> {
        self.inner
            .request(
                HttpMethod::Get,
                "/routing/checkout-theme/conversion",
                None,
                &params.to_query(),
                None,
            )
            .await
    }

    /// Get the active routing config (`GET /routing/active`).
    ///
    /// The backend returns either a `{ "algorithm": … }` envelope or a list of
    /// records, depending on whether routing is merchant-account or profile
    /// based; the return type covers both.
    pub async fn active(&self) -> Result<ActiveRoutingConfig> {
        self.inner
            .request(HttpMethod::Get, "/routing/active", None, &[], None)
            .await
    }

    /// Update the default routing config (`POST /routing/default`). The body
    /// is an open shape — see the API reference. Returns the resulting
    /// ordered connector list.
    pub async fn update_default(&self, params: &Value) -> Result<Vec<RoutableConnectorChoice>> {
        let body = to_json_vec(params)?;
        self.inner
            .request(HttpMethod::Post, "/routing/default", Some(&body), &[], None)
            .await
    }

    /// Retrieve the default config for profiles
    /// (`GET /routing/default/profile`).
    ///
    /// Backends differ: some return one entry per shop, others a flat
    /// connector list. The return type covers both.
    pub async fn default_profile(&self) -> Result<DefaultProfileRouting> {
        self.inner
            .request(HttpMethod::Get, "/routing/default/profile", None, &[], None)
            .await
    }

    /// Update the default config for one profile
    /// (`POST /routing/default/profile/{profile_id}`). The body is an open
    /// shape — see the API reference.
    pub async fn update_default_profile(
        &self,
        profile_id: &str,
        params: &Value,
    ) -> Result<ProfileDefaultRoutingConfig> {
        let path = format!("/routing/default/profile/{}", encode_segment(profile_id));
        let body = to_json_vec(params)?;
        self.inner
            .request(HttpMethod::Post, &path, Some(&body), &[], None)
            .await
    }

    /// Evaluate a routing rule (`POST /routing/rule/evaluate`). The body is an
    /// open shape — see the API reference.
    pub async fn evaluate_rule(&self, params: &Value) -> Result<Value> {
        let body = to_json_vec(params)?;
        self.inner
            .request(
                HttpMethod::Post,
                "/routing/rule/evaluate",
                Some(&body),
                &[],
                None,
            )
            .await
    }

    /// Evaluate routing for a payment (`POST /routing/evaluate`). The body is
    /// an open shape — see the API reference.
    pub async fn evaluate(&self, params: &Value) -> Result<Value> {
        let body = to_json_vec(params)?;
        self.inner
            .request(
                HttpMethod::Post,
                "/routing/evaluate",
                Some(&body),
                &[],
                None,
            )
            .await
    }

    /// Update gateway scores for dynamic routing (`POST /routing/feedback`).
    /// The body is an open shape — see the API reference.
    pub async fn feedback(&self, params: &Value) -> Result<Value> {
        let body = to_json_vec(params)?;
        self.inner
            .request(
                HttpMethod::Post,
                "/routing/feedback",
                Some(&body),
                &[],
                None,
            )
            .await
    }
}

/// Serialize `params`, defaulting to `{}` when absent: these endpoints reject
/// a bodyless POST, so the request must always carry a JSON body.
fn body_or_empty_object<T: Serialize>(params: Option<&T>) -> Result<Vec<u8>> {
    match params {
        Some(p) => to_json_vec(p),
        None => Ok(b"{}".to_vec()),
    }
}

/// The surcharge-rules sub-resource, obtained via
/// [`Routing::surcharge_rules`].
///
/// Configure a per-payment-method surcharge (fixed or percentage) added to the
/// amount the buyer pays, without hand-writing the Euclid DSL. Scope to a shop
/// with `profile_id`; omit it for merchant-wide rules.
///
/// This is distinct from the platform fee (a balance deduction): a surcharge
/// changes what the buyer is charged.
#[derive(Debug, Clone)]
pub struct SurchargeRules {
    inner: Arc<Inner>,
}

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

    /// Create or replace the surcharge program for a scope
    /// (`PUT /routing/surcharge/rules`).
    pub async fn upsert(&self, params: &SurchargeRuleRequest) -> Result<SurchargeRuleResponse> {
        params.validate()?;
        let body = to_json_vec(params)?;
        self.inner
            .request(
                HttpMethod::Put,
                "/routing/surcharge/rules",
                Some(&body),
                &[],
                None,
            )
            .await
    }

    /// Retrieve the active surcharge program for a scope, or `None` when none
    /// is set (`GET /routing/surcharge/rules`).
    ///
    /// Pass `None` for the merchant-wide rule.
    pub async fn retrieve(
        &self,
        profile_id: Option<&str>,
    ) -> Result<Option<SurchargeRuleResponse>> {
        let query = profile_id_query(profile_id);
        self.inner
            .request(
                HttpMethod::Get,
                "/routing/surcharge/rules",
                None,
                &query,
                None,
            )
            .await
    }

    /// Deactivate the active surcharge program for a scope
    /// (`DELETE /routing/surcharge/rules`).
    ///
    /// Pass `None` for the merchant-wide rule.
    pub async fn delete(&self, profile_id: Option<&str>) -> Result<()> {
        let query = profile_id_query(profile_id);
        // Any success body, empty or JSON, is accepted and dropped: decoding
        // it as `()` would turn a delete the server did into an error.
        self.inner
            .request::<serde::de::IgnoredAny>(
                HttpMethod::Delete,
                "/routing/surcharge/rules",
                None,
                &query,
                None,
            )
            .await
            .map(|_| ())
    }
}

/// The checkout theme rules sub-resource, obtained via
/// [`Routing::checkout_theme_rules`].
///
/// A theme program picks which of a shop's stored appearance variants a buyer
/// is shown. It uses the same rule format as advanced routing — rules run
/// top-down, first match wins, with a default selection as the fallback —
/// with a variant name as the output. It decides a look and nothing else.
///
/// Naming a variant the shop has not defined is not an error: the checkout
/// falls back to the shop default, and the name comes back in `warnings`.
#[derive(Debug, Clone)]
pub struct CheckoutThemeRules {
    inner: Arc<Inner>,
}

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

    /// Create or replace the theme program for a scope
    /// (`PUT /routing/checkout-theme/rules`).
    ///
    /// The previous active version is retired and a new one stored. With
    /// `active(false)` a revision is stored without retiring the live one.
    pub async fn upsert(
        &self,
        params: &CheckoutThemeProgramRequest,
    ) -> Result<CheckoutThemeProgramResponse> {
        params.validate()?;
        let body = to_json_vec(params)?;
        self.inner
            .request_body_keyed_with_query(
                HttpMethod::Put,
                "/routing/checkout-theme/rules",
                Some(&body),
                &[],
                None,
            )
            .await
    }

    /// Retrieve the active theme program for a scope, or `None` when none is
    /// set (`GET /routing/checkout-theme/rules`).
    ///
    /// Pass `None` for the merchant-wide program; a shop-scoped caller then
    /// gets its own shop's program.
    pub async fn retrieve(
        &self,
        profile_id: Option<&str>,
    ) -> Result<Option<CheckoutThemeProgramResponse>> {
        let query = profile_id_query(profile_id);
        self.inner
            .request(
                HttpMethod::Get,
                "/routing/checkout-theme/rules",
                None,
                &query,
                None,
            )
            .await
    }

    /// Deactivate the active theme program for a scope. Idempotent
    /// (`DELETE /routing/checkout-theme/rules`).
    ///
    /// The stored revision is kept as the record of which look was live
    /// when; shops go back to their default appearance immediately. Pass
    /// `None` for the merchant-wide program.
    pub async fn delete(&self, profile_id: Option<&str>) -> Result<()> {
        let query = profile_id_query(profile_id);
        self.inner
            .request_body_keyed_with_query::<serde::de::IgnoredAny>(
                HttpMethod::Delete,
                "/routing/checkout-theme/rules",
                None,
                &query,
                None,
            )
            .await
            .map(|_| ())
    }
}

/// `/routing/connector-caps/accounts/{id}/overrides/{level}/{scope_id}`.
fn cap_override_path(merchant_connector_id: &str, level: &str, scope_id: &str) -> String {
    format!(
        "/routing/connector-caps/accounts/{}/overrides/{}/{}",
        encode_segment(merchant_connector_id),
        encode_segment(level),
        encode_segment(scope_id)
    )
}

/// `/routing/connector-cap-schedules/{profile_id}{suffix}`.
fn cap_schedule_path(profile_id: &str, suffix: &str) -> String {
    format!(
        "/routing/connector-cap-schedules/{}{suffix}",
        encode_segment(profile_id)
    )
}

/// Parameters for [`Routing::reset_connector_cap_usage`].
#[derive(Debug, Clone, Default, Serialize)]
pub struct RoutingConnectorCapResetRequest {
    /// The connector account.
    pub merchant_connector_id: String,
    /// Which of the account's limits: `"payments"` (its payment count) or
    /// `"amount"` (its budget).
    pub unit: String,
}

impl RoutingConnectorCapResetRequest {
    /// Reset `merchant_connector_id`'s limit in `unit`.
    pub fn new(merchant_connector_id: impl Into<String>, unit: impl Into<String>) -> Self {
        Self {
            merchant_connector_id: merchant_connector_id.into(),
            unit: unit.into(),
        }
    }
}

/// Parameters for [`Routing::shuffle_connector_cap_schedule`].
#[derive(Debug, Clone, Default, Serialize)]
pub struct RoutingConnectorCapScheduleShuffle {
    /// The schedule's last-read revision.
    pub revision: String,
    /// The active entry's id.
    pub id: String,
    /// The new drawn value.
    pub value: i64,
}

impl RoutingConnectorCapScheduleShuffle {
    /// Set entry `id`'s drawn value to `value`, over `revision`.
    pub fn new(revision: impl Into<String>, id: impl Into<String>, value: i64) -> Self {
        Self {
            revision: revision.into(),
            id: id.into(),
            value,
        }
    }
}

/// Parameters for [`Routing::set_connector_cap_override`].
#[derive(Debug, Clone, Default, Serialize)]
pub struct ConnectorCapOverrideRequest {
    /// `"unlimited"` lifts the limits at the target; `"own"` sets limits of
    /// its own, counted separately from the account's.
    pub mode: String,
    /// The limits of an `own` override, at most one per unit, each naming the
    /// account in the path. Required for `own`, refused for `unlimited`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub caps: Option<Vec<RoutingConnectorCap>>,
    /// Any additional fields, merged verbatim.
    #[serde(flatten, skip_serializing_if = "serde_json::Map::is_empty")]
    pub extra: serde_json::Map<String, Value>,
}

impl ConnectorCapOverrideRequest {
    /// Lift the account's limits at the target.
    pub fn unlimited() -> Self {
        Self {
            mode: "unlimited".to_string(),
            ..Default::default()
        }
    }

    /// Give the target limits of its own.
    pub fn own(caps: Vec<RoutingConnectorCap>) -> Self {
        Self {
            mode: "own".to_string(),
            caps: Some(caps),
            extra: serde_json::Map::new(),
        }
    }
}

/// Names of `ConnectorCapOverrideRequest`'s fields as they appear on the wire
/// (`extra` excluded).
const CONNECTOR_CAP_OVERRIDE_REQUEST_NAMED: &[&str] = &["mode", "caps"];

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

/// Parameters for [`CheckoutThemeRules::upsert`].
#[derive(Debug, Clone, Default, Serialize)]
pub struct CheckoutThemeProgramRequest {
    /// Shown in the dashboard and echoed on retrieval.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    /// Shop scope; unset is merchant-wide. A shop-scoped caller may leave it
    /// unset and may not name another shop.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub profile_id: Option<String>,
    /// The program: `rules`, `defaultSelection` and `metadata`, each rule's
    /// output a `{"theme": {"variant": …}}` selection.
    pub algorithm: Value,
    /// Whether the program takes effect on save. Defaults to `true`
    /// server-side.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub active: Option<bool>,
    /// RFC 3339; defaults to now.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub valid_from: Option<String>,
    /// RFC 3339; unset is open-ended.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub valid_until: 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 CheckoutThemeProgramRequest {
    /// A program with the given `algorithm`.
    pub fn new(algorithm: Value) -> Self {
        Self {
            algorithm,
            ..Default::default()
        }
    }

    /// Name the program.
    #[must_use]
    pub fn name(mut self, name: impl Into<String>) -> Self {
        self.name = Some(name.into());
        self
    }

    /// Scope the program to a shop.
    #[must_use]
    pub fn profile_id(mut self, profile_id: impl Into<String>) -> Self {
        self.profile_id = Some(profile_id.into());
        self
    }

    /// Store as the live program (`true`) or as a draft revision (`false`).
    #[must_use]
    pub fn active(mut self, active: bool) -> Self {
        self.active = Some(active);
        self
    }

    /// Start of validity, RFC 3339.
    #[must_use]
    pub fn valid_from(mut self, valid_from: impl Into<String>) -> Self {
        self.valid_from = Some(valid_from.into());
        self
    }

    /// End of validity, RFC 3339.
    #[must_use]
    pub fn valid_until(mut self, valid_until: impl Into<String>) -> Self {
        self.valid_until = Some(valid_until.into());
        self
    }
}

/// Names of `CheckoutThemeProgramRequest`'s fields as they appear on the wire
/// (`extra` excluded).
const CHECKOUT_THEME_PROGRAM_REQUEST_NAMED: &[&str] = &[
    "name",
    "profile_id",
    "algorithm",
    "active",
    "valid_from",
    "valid_until",
];

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

/// Query for [`Routing::checkout_theme_conversion`]. Unset filters are not
/// sent.
#[derive(Debug, Clone, Default)]
pub struct CheckoutThemeConversionParams {
    /// Shop to report on; unset reports every shop the caller can see.
    pub profile_id: Option<String>,
    /// Window start, RFC 3339, inclusive.
    pub start: String,
    /// Window end, RFC 3339, exclusive.
    pub end: String,
    /// Group by `"none"` (the server default), `"device"`, `"country"` or
    /// `"hour"`.
    pub segment: Option<String>,
    /// Count only renders on this device class.
    pub device_class: Option<String>,
    /// Count only renders whose IP-derived country is this two-letter code.
    pub country: Option<String>,
    /// Count only renders whose look was chosen this way. Renders on the shop
    /// default are always counted, as the baseline.
    pub selection: Option<String>,
}

impl CheckoutThemeConversionParams {
    /// A report over `[start, end)`.
    pub fn new(start: impl Into<String>, end: impl Into<String>) -> Self {
        Self {
            start: start.into(),
            end: end.into(),
            ..Default::default()
        }
    }

    /// Report on one shop.
    #[must_use]
    pub fn profile_id(mut self, profile_id: impl Into<String>) -> Self {
        self.profile_id = Some(profile_id.into());
        self
    }

    /// Group the cells by this dimension.
    #[must_use]
    pub fn segment(mut self, segment: impl Into<String>) -> Self {
        self.segment = Some(segment.into());
        self
    }

    /// Filter by device class.
    #[must_use]
    pub fn device_class(mut self, device_class: impl Into<String>) -> Self {
        self.device_class = Some(device_class.into());
        self
    }

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

    /// Filter by how the look was chosen.
    #[must_use]
    pub fn selection(mut self, selection: impl Into<String>) -> Self {
        self.selection = Some(selection.into());
        self
    }

    fn to_query(&self) -> Vec<(&'static str, String)> {
        let mut query = Vec::new();
        if let Some(v) = &self.profile_id {
            query.push(("profile_id", v.clone()));
        }
        query.push(("start", self.start.clone()));
        query.push(("end", self.end.clone()));
        let optional = [
            ("segment", &self.segment),
            ("device_class", &self.device_class),
            ("country", &self.country),
            ("selection", &self.selection),
        ];
        for (key, value) in optional {
            if let Some(v) = value {
                query.push((key, v.clone()));
            }
        }
        query
    }
}

/// The `profile_id` query pair, omitted entirely when the scope is
/// merchant-wide.
fn profile_id_query(profile_id: Option<&str>) -> Vec<(&'static str, String)> {
    match profile_id {
        Some(id) => vec![("profile_id", id.to_string())],
        None => Vec::new(),
    }
}

/// Parameters for [`Routing::create`].
#[derive(Debug, Clone, Default, Serialize)]
pub struct RoutingConfigCreateRequest {
    /// Human-readable name for the configuration.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    /// Longer description of what the configuration does.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    /// The routing algorithm itself — an adjacently-tagged `{type, data}`
    /// object (`single`, `priority`, `volume_split`, `advanced`,
    /// `three_ds_decision_rule`). Open shape; see the API reference.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub algorithm: Option<Value>,
    /// Shop (business profile) the configuration belongs to.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub profile_id: Option<String>,
    /// Transaction type the algorithm applies to, e.g. `"payment"`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub transaction_type: Option<String>,
    /// Any additional fields not modeled above are merged in verbatim.
    #[serde(flatten, skip_serializing_if = "serde_json::Map::is_empty")]
    pub extra: serde_json::Map<String, Value>,
}

/// Names of `RoutingConfigCreateRequest`'s fields as they appear on the wire
/// (`extra` excluded).
const ROUTING_CONFIG_CREATE_REQUEST_NAMED: &[&str] = &[
    "name",
    "description",
    "algorithm",
    "profile_id",
    "transaction_type",
];

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

impl RoutingConfigCreateRequest {
    /// An empty request; set the fields you need.
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the configuration's name.
    pub fn name(mut self, name: impl Into<String>) -> Self {
        self.name = Some(name.into());
        self
    }

    /// Set the configuration's description.
    pub fn description(mut self, description: impl Into<String>) -> Self {
        self.description = Some(description.into());
        self
    }

    /// Set the routing algorithm body.
    pub fn algorithm(mut self, algorithm: Value) -> Self {
        self.algorithm = Some(algorithm);
        self
    }

    /// Scope the configuration to one shop (business profile).
    pub fn profile_id(mut self, profile_id: impl Into<String>) -> Self {
        self.profile_id = Some(profile_id.into());
        self
    }

    /// Set the transaction type the algorithm applies to.
    pub fn transaction_type(mut self, transaction_type: impl Into<String>) -> Self {
        self.transaction_type = Some(transaction_type.into());
        self
    }
}

/// Body for [`Routing::activate`].
#[derive(Debug, Clone, Default, Serialize)]
pub struct RoutingActivatePayload {
    /// Transaction type to activate the algorithm for, e.g. `"payment"`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub transaction_type: Option<String>,
}

impl RoutingActivatePayload {
    /// An empty payload; set the fields you need.
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the transaction type to activate the algorithm for.
    pub fn transaction_type(mut self, transaction_type: impl Into<String>) -> Self {
        self.transaction_type = Some(transaction_type.into());
        self
    }
}

/// Body for [`Routing::deactivate`].
#[derive(Debug, Clone, Default, Serialize)]
pub struct RoutingDeactivateRequest {
    /// Name of the configuration being deactivated.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    /// Description of the configuration being deactivated.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    /// Algorithm body (open shape — see the API reference).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub algorithm: Option<Value>,
    /// Shop (business profile) to deactivate routing for.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub profile_id: Option<String>,
    /// Transaction type to deactivate routing for.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub transaction_type: Option<String>,
    /// Any additional fields not modeled above are merged in verbatim.
    #[serde(flatten, skip_serializing_if = "serde_json::Map::is_empty")]
    pub extra: serde_json::Map<String, Value>,
}

/// Names of `RoutingDeactivateRequest`'s fields as they appear on the wire
/// (`extra` excluded).
const ROUTING_DEACTIVATE_REQUEST_NAMED: &[&str] = &[
    "name",
    "description",
    "algorithm",
    "profile_id",
    "transaction_type",
];

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

/// Parameters for [`SurchargeRules::upsert`].
#[derive(Debug, Clone, Default, Serialize)]
pub struct SurchargeRuleRequest {
    /// Human-readable name for the surcharge program.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    /// Shop scope. Omit for merchant-wide.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub profile_id: Option<String>,
    /// Per-method surcharges, evaluated top-to-bottom (first match wins).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub surcharges: Option<Vec<PerMethodSurchargeItem>>,
    /// Applied when no per-method entry matches. Omit for no surcharge.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub default_surcharge: Option<MethodSurcharge>,
    /// Whether the checkout shows a surcharge breakup screen.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub show_surcharge_breakup_screen: Option<bool>,
    /// RFC 3339 timestamp; defaults to now when omitted.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub valid_from: Option<String>,
    /// RFC 3339 timestamp; omit for open-ended.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub valid_until: Option<String>,
    /// Any additional fields not modeled above are merged in verbatim.
    #[serde(flatten, skip_serializing_if = "serde_json::Map::is_empty")]
    pub extra: serde_json::Map<String, Value>,
}

/// Names of `SurchargeRuleRequest`'s fields as they appear on the wire
/// (`extra` excluded).
const SURCHARGE_RULE_REQUEST_NAMED: &[&str] = &[
    "name",
    "profile_id",
    "surcharges",
    "default_surcharge",
    "show_surcharge_breakup_screen",
    "valid_from",
    "valid_until",
];

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

impl SurchargeRuleRequest {
    /// An empty request; set the fields you need.
    pub fn new() -> Self {
        Self::default()
    }

    /// Name the surcharge program.
    pub fn name(mut self, name: impl Into<String>) -> Self {
        self.name = Some(name.into());
        self
    }

    /// Scope the program to one shop (business profile).
    pub fn profile_id(mut self, profile_id: impl Into<String>) -> Self {
        self.profile_id = Some(profile_id.into());
        self
    }

    /// Set the per-method surcharge entries.
    pub fn surcharges(mut self, surcharges: Vec<PerMethodSurchargeItem>) -> Self {
        self.surcharges = Some(surcharges);
        self
    }

    /// Set the surcharge applied when no per-method entry matches.
    pub fn default_surcharge(mut self, surcharge: MethodSurcharge) -> Self {
        self.default_surcharge = Some(surcharge);
        self
    }
}

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

    const RECORD_JSON: &str = r#"{
        "id": "rou_1",
        "profile_id": "pro_1",
        "name": "EU Priority",
        "kind": "priority",
        "description": "EU traffic",
        "created_at": 1767225600000,
        "modified_at": 1767225600000,
        "algorithm_for": "payment"
    }"#;

    const ALGORITHM_JSON: &str = r#"{
        "id": "rou_1",
        "profile_id": "pro_1",
        "name": "EU Priority",
        "description": "EU traffic",
        "algorithm": {"type": "priority", "data": [{"connector": "stripe"}]},
        "created_at": 1767225600000,
        "modified_at": 1767225600000,
        "algorithm_for": "payment"
    }"#;

    const DICTIONARY_JSON: &str = r#"{"merchant_id":"mer_1","active_id":null,"records":[]}"#;

    const HISTORY_JSON: &str = r#"{
        "id": "rou_1",
        "profile_id": "pro_1",
        "total_count": 3,
        "versions": [
            {
                "version": 1,
                "name": "EU Priority",
                "description": "EU traffic",
                "kind": "priority",
                "algorithm": {"type": "priority", "data": [{"connector": "stripe"}]},
                "valid_from": 1718000000,
                "valid_until": 1718050000
            },
            {
                "version": 2,
                "name": "EU Priority",
                "description": "EU traffic, adyen first",
                "kind": "priority",
                "algorithm": {"type": "priority", "data": [{"connector": "adyen"}]},
                "valid_from": 1718050000
            }
        ]
    }"#;

    const CAPS_JSON: &str = r#"{
        "profile_id": "pro_1",
        "caps": [
            {"merchant_connector_id": "mca_1", "limit": 1, "used": 0, "reserved": 1},
            {"merchant_connector_id": "mca_2", "limit": 5, "used": 5, "reserved": 0},
            {"merchant_connector_id": "mca_3", "limit": 2}
        ]
    }"#;

    const SURCHARGE_JSON: &str = r#"{
        "name": "EU surcharges",
        "profile_id": "pro_1",
        "version": 2,
        "valid_from": "2026-01-01T00:00:00Z",
        "valid_until": null,
        "surcharges": [
            {"payment_method": "card", "surcharge": {"fixed": {"amount": 35}}}
        ],
        "default_surcharge": {"fixed": {"amount": 10}}
    }"#;

    #[tokio::test]
    async fn create_posts_the_algorithm_to_routing_root() {
        let (client, mock) = client_with(vec![Step::ok(RECORD_JSON)]);
        let req = RoutingConfigCreateRequest::new()
            .name("EU Priority")
            .profile_id("pro_1")
            .algorithm(json!({"type": "priority", "data": [{"connector": "stripe"}]}));
        let record = client.routing().create(&req).await.unwrap();
        assert_eq!(record.id, "rou_1");
        assert_eq!(record.kind, "priority");
        // Milliseconds since epoch — an i32 field would not hold this.
        assert_eq!(record.created_at, Some(1_767_225_600_000));

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(seen[0].url, "https://api.test/routing");
        let body = seen[0].body_json();
        assert_eq!(body["name"], "EU Priority");
        assert_eq!(body["profile_id"], "pro_1");
        assert_eq!(body["algorithm"]["type"], "priority");
    }

    #[tokio::test]
    async fn retrieve_and_list_use_the_routing_paths() {
        let (client, mock) = client_with(vec![Step::ok(ALGORITHM_JSON), Step::ok(DICTIONARY_JSON)]);
        let routing = client.routing();
        // An ID that must be percent-encoded to land on the right path.
        let algorithm = routing.retrieve("rou/1").await.unwrap();
        // `retrieve` is the only endpoint that echoes the algorithm body.
        assert_eq!(algorithm.algorithm["type"], "priority");
        let dictionary = routing.list().await.unwrap();
        assert_eq!(dictionary.merchant_id, "mer_1");
        assert_eq!(dictionary.active_id, None);

        let seen = mock.seen.lock().unwrap();
        assert_eq!(
            (seen[0].method, seen[0].url.as_str()),
            ("GET", "https://api.test/routing/rou%2F1")
        );
        assert_eq!(
            (seen[1].method, seen[1].url.as_str()),
            ("GET", "https://api.test/routing")
        );
    }

    #[tokio::test]
    async fn activate_posts_an_empty_object_body_by_default() {
        // The endpoint rejects a bodyless POST ("Unsupported content type"),
        // so `None` params must still produce a `{}` body.
        let (client, mock) = client_with(vec![Step::ok(RECORD_JSON), Step::ok(RECORD_JSON)]);
        let routing = client.routing();
        routing.activate("rou 1", None).await.unwrap();
        routing
            .activate(
                "rou_2",
                Some(&RoutingActivatePayload::new().transaction_type("payment")),
            )
            .await
            .unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(seen[0].url, "https://api.test/routing/rou%201/activate");
        assert_eq!(seen[0].body_json(), json!({}));
        assert_eq!(seen[1].url, "https://api.test/routing/rou_2/activate");
        assert_eq!(seen[1].body_json()["transaction_type"], "payment");
    }

    #[tokio::test]
    async fn deactivate_posts_to_the_deactivate_path() {
        let (client, mock) = client_with(vec![Step::ok(RECORD_JSON), Step::ok(RECORD_JSON)]);
        let routing = client.routing();
        routing.deactivate(None).await.unwrap();
        routing
            .deactivate(Some(&RoutingDeactivateRequest {
                profile_id: Some("pro_1".to_string()),
                ..Default::default()
            }))
            .await
            .unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(seen[0].url, "https://api.test/routing/deactivate");
        assert_eq!(seen[0].body_json(), json!({}));
        assert_eq!(seen[1].body_json()["profile_id"], "pro_1");
    }

    #[tokio::test]
    async fn read_only_advanced_endpoints_hit_their_paths() {
        let (client, mock) = client_with(vec![
            Step::ok(r#"{"algorithm":null}"#),
            Step::ok(r#"[{"profile_id":"pro_1","connectors":[{"connector":"stripe"}]}]"#),
        ]);
        let routing = client.routing();
        let active = routing.active().await.unwrap();
        assert!(
            matches!(active, ActiveRoutingConfig::Envelope(ref e) if e.algorithm.is_none()),
            "a `{{\"algorithm\": null}}` body means nothing is active: {active:?}"
        );
        let defaults = routing.default_profile().await.unwrap();
        match defaults {
            DefaultProfileRouting::PerProfile(p) => assert_eq!(p[0].profile_id, "pro_1"),
            other => panic!("expected the per-profile arm, got {other:?}"),
        }

        let seen = mock.seen.lock().unwrap();
        let expected = [
            "https://api.test/routing/active",
            "https://api.test/routing/default/profile",
        ];
        for (i, url) in expected.iter().enumerate() {
            assert_eq!(seen[i].method, "GET");
            assert_eq!(seen[i].url, *url);
        }
    }

    #[tokio::test]
    async fn write_advanced_endpoints_post_their_bodies() {
        let (client, mock) = client_with(vec![
            Step::ok(r#"[{"connector":"stripe","merchant_connector_id":"mca_1"}]"#),
            Step::ok(r#"{"profile_id":"pro/1","connectors":[]}"#),
            Step::ok("{}"),
            Step::ok("{}"),
            Step::ok("{}"),
        ]);
        let routing = client.routing();
        let connectors = routing
            .update_default(&json!({"marker": "default"}))
            .await
            .unwrap();
        assert_eq!(connectors[0].connector, "stripe");
        assert_eq!(
            connectors[0].merchant_connector_id.as_deref(),
            Some("mca_1")
        );
        let profile_default = routing
            .update_default_profile("pro/1", &json!({"marker": "default_profile"}))
            .await
            .unwrap();
        assert_eq!(profile_default.profile_id, "pro/1");
        routing
            .evaluate_rule(&json!({"marker": "rule_evaluate"}))
            .await
            .unwrap();
        routing
            .evaluate(&json!({"marker": "evaluate"}))
            .await
            .unwrap();
        routing
            .feedback(&json!({"marker": "feedback"}))
            .await
            .unwrap();

        let seen = mock.seen.lock().unwrap();
        let expected = [
            ("https://api.test/routing/default", "default"),
            (
                "https://api.test/routing/default/profile/pro%2F1",
                "default_profile",
            ),
            ("https://api.test/routing/rule/evaluate", "rule_evaluate"),
            ("https://api.test/routing/evaluate", "evaluate"),
            ("https://api.test/routing/feedback", "feedback"),
        ];
        for (i, (url, marker)) in expected.iter().enumerate() {
            assert_eq!(seen[i].method, "POST");
            assert_eq!(seen[i].url, *url);
            assert_eq!(seen[i].body_json()["marker"], *marker);
        }
    }

    #[tokio::test]
    async fn surcharge_rules_upsert_puts_the_structured_program() {
        let (client, mock) = client_with(vec![Step::ok(SURCHARGE_JSON)]);
        let req = SurchargeRuleRequest::new()
            .name("EU surcharges")
            .profile_id("pro_1")
            .surcharges(vec![
                PerMethodSurchargeItem::new("crypto", MethodSurcharge::Rate { percent: 1.0 }),
                PerMethodSurchargeItem::new("card", MethodSurcharge::Fixed { amount: 35 })
                    .card_network("Visa")
                    .tax_on_surcharge_percent(20.0),
            ])
            .default_surcharge(MethodSurcharge::Fixed { amount: 10 });
        let saved = client
            .routing()
            .surcharge_rules()
            .upsert(&req)
            .await
            .unwrap();
        assert_eq!(saved.version, 2);
        assert_eq!(saved.profile_id.as_deref(), Some("pro_1"));
        assert_eq!(
            saved.default_surcharge,
            Some(MethodSurcharge::Fixed { amount: 10 })
        );
        assert!(saved.warnings.is_empty());

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "PUT");
        assert_eq!(seen[0].url, "https://api.test/routing/surcharge/rules");
        let body = seen[0].body_json();
        assert_eq!(body["name"], "EU surcharges");
        assert_eq!(body["profile_id"], "pro_1");
        assert_eq!(body["surcharges"][0]["payment_method"], "crypto");
        assert_eq!(body["surcharges"][0]["surcharge"]["rate"]["percent"], 1.0);
        assert_eq!(body["surcharges"][1]["surcharge"]["fixed"]["amount"], 35);
        assert_eq!(body["surcharges"][1]["card_network"], "Visa");
        assert_eq!(body["surcharges"][1]["tax_on_surcharge_percent"], 20.0);
        assert_eq!(body["default_surcharge"]["fixed"]["amount"], 10);
    }

    #[tokio::test]
    async fn surcharge_rules_scope_the_read_and_delete_by_profile() {
        let (client, mock) = client_with(vec![
            Step::ok(SURCHARGE_JSON),
            Step::ok("null"),
            // A JSON success body and an empty one both mean the delete
            // happened. Mutation: decode the body as `()` again — the first
            // delete fails with `Decode`.
            Step::ok(r#"{"deleted":true}"#),
            Step::ok(""),
        ]);
        let rules = client.routing().surcharge_rules();
        let scoped = rules
            .retrieve(Some("pro 1"))
            .await
            .unwrap()
            .expect("a program body decodes to Some");
        assert_eq!(scoped.name, "EU surcharges");
        assert!(
            rules.retrieve(None).await.unwrap().is_none(),
            "a null body means no surcharge program is set for the scope"
        );
        rules.delete(Some("pro 1")).await.unwrap();
        rules.delete(None).await.unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(
            (seen[0].method, seen[0].url.as_str()),
            (
                "GET",
                "https://api.test/routing/surcharge/rules?profile_id=pro 1"
            )
        );
        assert_eq!(
            (seen[1].method, seen[1].url.as_str()),
            ("GET", "https://api.test/routing/surcharge/rules")
        );
        assert_eq!(
            (seen[2].method, seen[2].url.as_str()),
            (
                "DELETE",
                "https://api.test/routing/surcharge/rules?profile_id=pro 1"
            )
        );
        assert_eq!(
            (seen[3].method, seen[3].url.as_str()),
            ("DELETE", "https://api.test/routing/surcharge/rules")
        );
    }

    /// Drift guard for `ROUTING_CONFIG_CREATE_REQUEST_NAMED`.
    #[test]
    fn routing_config_create_request_named_fields_are_complete() {
        let req = RoutingConfigCreateRequest {
            name: Some("n".to_string()),
            description: Some("d".to_string()),
            algorithm: Some(json!({"type": "priority", "data": []})),
            profile_id: Some("pro_1".to_string()),
            transaction_type: Some("payment".to_string()),
            extra: serde_json::Map::new(),
        };
        let value = serde_json::to_value(req).unwrap();
        for key in value.as_object().expect("serializes to an object").keys() {
            assert!(
                ROUTING_CONFIG_CREATE_REQUEST_NAMED.contains(&key.as_str()),
                "ROUTING_CONFIG_CREATE_REQUEST_NAMED is missing wire key `{key}`"
            );
        }
    }

    /// Drift guard for `ROUTING_DEACTIVATE_REQUEST_NAMED`.
    #[test]
    fn routing_deactivate_request_named_fields_are_complete() {
        let req = RoutingDeactivateRequest {
            name: Some("n".to_string()),
            description: Some("d".to_string()),
            algorithm: Some(json!({})),
            profile_id: Some("pro_1".to_string()),
            transaction_type: Some("payment".to_string()),
            extra: serde_json::Map::new(),
        };
        let value = serde_json::to_value(req).unwrap();
        for key in value.as_object().expect("serializes to an object").keys() {
            assert!(
                ROUTING_DEACTIVATE_REQUEST_NAMED.contains(&key.as_str()),
                "ROUTING_DEACTIVATE_REQUEST_NAMED is missing wire key `{key}`"
            );
        }
    }

    /// Drift guard for `SURCHARGE_RULE_REQUEST_NAMED`.
    #[test]
    fn surcharge_rule_request_named_fields_are_complete() {
        let req = SurchargeRuleRequest {
            name: Some("n".to_string()),
            profile_id: Some("pro_1".to_string()),
            surcharges: Some(vec![PerMethodSurchargeItem::new(
                "card",
                MethodSurcharge::Fixed { amount: 1 },
            )]),
            default_surcharge: Some(MethodSurcharge::Rate { percent: 1.0 }),
            show_surcharge_breakup_screen: Some(true),
            valid_from: Some("2026-01-01T00:00:00Z".to_string()),
            valid_until: Some("2026-12-31T00:00:00Z".to_string()),
            extra: serde_json::Map::new(),
        };
        let value = serde_json::to_value(req).unwrap();
        for key in value.as_object().expect("serializes to an object").keys() {
            assert!(
                SURCHARGE_RULE_REQUEST_NAMED.contains(&key.as_str()),
                "SURCHARGE_RULE_REQUEST_NAMED is missing wire key `{key}`"
            );
        }
    }

    #[test]
    fn validate_rejects_extra_keys_colliding_with_named_fields() {
        let mut create = RoutingConfigCreateRequest::new();
        create.extra.insert("algorithm".to_string(), json!({}));
        match create.validate().unwrap_err() {
            DelopayError::InvalidRequest(msg) => assert!(msg.contains("algorithm")),
            other => panic!("expected InvalidRequest, got {other:?}"),
        }

        let mut deactivate = RoutingDeactivateRequest::default();
        deactivate
            .extra
            .insert("profile_id".to_string(), json!("pro_2"));
        assert!(matches!(
            deactivate.validate().unwrap_err(),
            DelopayError::InvalidRequest(_)
        ));

        let mut surcharge = SurchargeRuleRequest::new();
        surcharge
            .extra
            .insert("valid_until".to_string(), json!("2026-01-01T00:00:00Z"));
        assert!(matches!(
            surcharge.validate().unwrap_err(),
            DelopayError::InvalidRequest(_)
        ));
    }

    #[tokio::test]
    async fn history_pages_over_the_timeline_and_marks_the_live_window() {
        let (client, mock) = client_with(vec![Step::ok(HISTORY_JSON)]);
        let history = client
            .routing()
            .history("rou_1", Some(2), Some(4))
            .await
            .unwrap();

        assert_eq!(history.total_count, 3);
        assert_eq!(history.versions.len(), 2);
        // The window that has been replaced is not live; the one still in
        // force carries no `valid_until`.
        assert_eq!(history.versions[0].valid_until, Some(1_718_050_000));
        assert!(!history.versions[0].is_live());
        assert!(history.versions[1].is_live());
        assert_eq!(
            history.versions[1].algorithm["data"][0]["connector"],
            "adyen"
        );

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "GET");
        assert_eq!(
            seen[0].url,
            "https://api.test/routing/rou_1/history?limit=2&offset=4"
        );
    }

    #[tokio::test]
    async fn history_survives_a_window_with_no_description() {
        // The backend sends `""` for a configuration nobody described, never
        // `null` and never nothing — but an absent key degrades one field
        // rather than failing the whole page.
        const NO_DESCRIPTION: &str = r#"{
            "id": "rou_1",
            "profile_id": "pro_1",
            "total_count": 1,
            "versions": [
                {
                    "version": 1,
                    "name": "EU Priority",
                    "kind": "priority",
                    "algorithm": {"type": "priority", "data": []},
                    "valid_from": 1718000000
                }
            ]
        }"#;
        let (client, _mock) = client_with(vec![Step::ok(NO_DESCRIPTION)]);
        let history = client.routing().history("rou_1", None, None).await.unwrap();
        assert_eq!(
            history.versions.first().map(|v| v.description.as_str()),
            Some("")
        );
    }

    #[tokio::test]
    async fn history_omits_paging_it_was_not_given() {
        let (client, mock) = client_with(vec![Step::ok(HISTORY_JSON)]);
        client.routing().history("rou/1", None, None).await.unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].url, "https://api.test/routing/rou%2F1/history");
    }

    #[tokio::test]
    async fn connector_caps_reads_capacity_and_keeps_unknown_unknown() {
        let (client, mock) = client_with(vec![Step::ok(CAPS_JSON)]);
        let caps = client.routing().connector_caps("pro_1").await.unwrap();

        assert_eq!(caps.profile_id.as_deref(), Some("pro_1"));
        // Closed to new payments while `used` is still below `limit`: the
        // reservation is a checkout in progress.
        assert_eq!(caps.caps[0].has_capacity(), Some(false));
        assert_eq!(caps.caps[1].has_capacity(), Some(false));
        // No counter at all is unknown, not untouched — a cap that may
        // already have fired must not read as having room.
        assert_eq!(caps.caps[2].used, None);
        assert_eq!(caps.caps[2].has_capacity(), None);

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "GET");
        assert_eq!(seen[0].url, "https://api.test/routing/connector-caps/pro_1");
    }

    #[tokio::test]
    async fn set_connector_caps_puts_the_whole_set() {
        let (client, mock) = client_with(vec![Step::ok(CAPS_JSON)]);
        let caps = RoutingConnectorCaps::new(vec![RoutingConnectorCap::new("mca_1", 1)]);
        client
            .routing()
            .set_connector_caps("pro_1", &caps)
            .await
            .unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "PUT");
        assert_eq!(seen[0].url, "https://api.test/routing/connector-caps/pro_1");
        let body = seen[0].body_json();
        assert_eq!(body["caps"][0]["merchant_connector_id"], "mca_1");
        assert_eq!(body["caps"][0]["limit"], 1);
        // Read-only counters are not invented on the way out.
        assert!(body["caps"][0].get("used").is_none());
        assert!(body["caps"][0].get("reserved").is_none());
        // The path names the shop, so the body does not.
        assert!(body.get("profile_id").is_none());
    }

    #[tokio::test]
    async fn connector_caps_decode_ranges_amounts_and_features() {
        let (client, _mock) = client_with(vec![Step::ok(
            r#"{"profile_id":"pro_1","caps":[
                {"merchant_connector_id":"mca_1","limit":10,"limit_max":20,"unit":"payments",
                 "window":"daily","used":11,"reserved":0,"current_limit":15,
                 "current_limit_source":"reset","current_limit_drawn_at":"2026-09-01T00:00:00Z",
                 "distribution":{"kind":"normal","mean":15,"std_dev":2},
                 "current_limit_drawn_from":{"limit":10,"limit_max":20,
                     "distribution":{"kind":"normal","mean":15,"std_dev":2}}},
                {"merchant_connector_id":"mca_1","limit":500000,"unit":"amount",
                 "currency":"EUR","window":"monthly","used":100,
                 "distribution":{"kind":"weighted","bands":[{"min":1,"max":2,"weight":3}]}}],
                "active_caps":[],"scheduled_account_ids":["mca_2"],
                "features":["dual_limits","limit_ranges","payment_ranges"],
                "payment_ranges":[{"merchant_connector_id":"mca_1","currency":"EUR",
                    "min_amount":100,"max_amount":50000}]}"#,
        )]);
        let caps = client.routing().connector_caps("pro_1").await.unwrap();
        let ranged = &caps.caps[0];
        assert_eq!(ranged.limit_max, Some(20));
        assert_eq!(ranged.current_limit, Some(15));
        // Counted against the draw for the window, not the range's bottom:
        // 11 used of a 15 limit leaves room though `limit` is 10.
        assert_eq!(ranged.has_capacity(), Some(true));
        assert_eq!(ranged.distribution.as_ref().unwrap().std_dev, Some(2));
        assert_eq!(
            ranged.current_limit_drawn_from.as_ref().unwrap().limit_max,
            20
        );
        let amount = &caps.caps[1];
        assert_eq!(amount.unit.as_deref(), Some("amount"));
        assert_eq!(amount.currency.as_deref(), Some("EUR"));
        assert_eq!(
            amount
                .distribution
                .as_ref()
                .unwrap()
                .bands
                .as_ref()
                .unwrap()[0]
                .weight,
            3
        );
        assert_eq!(
            caps.features,
            ["dual_limits", "limit_ranges", "payment_ranges"]
        );
        assert_eq!(caps.scheduled_account_ids, ["mca_2"]);
        assert!(caps.active_caps.as_ref().unwrap().is_empty());
        assert_eq!(
            caps.payment_ranges.as_ref().unwrap()[0].max_amount,
            Some(50000)
        );
    }

    #[tokio::test]
    async fn set_connector_caps_sends_amount_caps_ranges_and_payment_ranges() {
        let (client, mock) = client_with(vec![Step::ok(CAPS_JSON)]);
        let caps = RoutingConnectorCaps::new(vec![
            RoutingConnectorCap::new("mca_1", 10)
                .window("daily")
                .limit_max(20)
                .distribution(ConnectorCapDistribution::triangular(12))
                .set_current_limit(14),
            RoutingConnectorCap::amount("mca_1", 500_000, "EUR", "monthly"),
        ])
        .payment_ranges(vec![RoutingConnectorPaymentRange::new("mca_1", "EUR")]);
        client
            .routing()
            .set_connector_caps("pro_1", &caps)
            .await
            .unwrap();

        let body = mock.seen.lock().unwrap()[0].body_json();
        assert_eq!(
            body["caps"][0],
            json!({"merchant_connector_id": "mca_1", "limit": 10, "window": "daily",
                   "limit_max": 20, "set_current_limit": 14,
                   "distribution": {"kind": "triangular", "mode": 12}})
        );
        assert_eq!(
            body["caps"][1],
            json!({"merchant_connector_id": "mca_1", "limit": 500000, "unit": "amount",
                   "currency": "EUR", "window": "monthly"})
        );
        assert_eq!(
            body["payment_ranges"],
            json!([{"merchant_connector_id": "mca_1", "currency": "EUR"}])
        );
        // Read-only lists are not sent.
        assert!(body.get("features").is_none());
        assert!(body.get("scheduled_account_ids").is_none());
    }

    #[tokio::test]
    async fn set_connector_caps_clears_every_cap_with_an_empty_list() {
        let (client, mock) = client_with(vec![Step::ok(r#"{"profile_id":"pro_1","caps":[]}"#)]);
        let caps = RoutingConnectorCaps::new(Vec::new());
        let out = client
            .routing()
            .set_connector_caps("pro_1", &caps)
            .await
            .unwrap();

        assert!(out.caps.is_empty());
        let seen = mock.seen.lock().unwrap();
        let body = seen[0].body_json();
        assert_eq!(body["caps"], json!([]));
    }

    const OVERRIDE_JSON: &str = r#"{
        "merchant_connector_id": "mca_1",
        "level": "shop",
        "scope_id": "pro_1",
        "scope_name": "Main shop",
        "mode": "own",
        "caps": [{"merchant_connector_id": "mca_1", "limit": 10, "unit": "payments", "used": 2}],
        "modified_at": "2026-01-01T00:00:00Z",
        "surprise_field": 1
    }"#;

    const SCHEDULE_JSON: &str = r#"{
        "revision": "rev_2",
        "entries": [{
            "id": "e1",
            "starts_at": "2026-01-01T00:00:00Z",
            "ends_at": "2026-02-01T00:00:00Z",
            "cap": {"merchant_connector_id": "mca_1", "limit": 5, "unit": "payments",
                    "cap_surprise": true}
        }],
        "timezone": "UTC",
        "observed_at": "2026-01-15T00:00:00Z",
        "next_change_at": "2026-02-01T00:00:00Z",
        "surprise_field": 1
    }"#;

    const THEME_PROGRAM_JSON: &str = r#"{
        "id": "thm_1",
        "name": "Autumn targeting",
        "profile_id": "pro_1",
        "algorithm": {"rules": [], "defaultSelection": {"theme": {"variant": "house"}}, "metadata": {}},
        "version": 3,
        "is_active": true,
        "valid_from": "2026-01-01T00:00:00Z",
        "warnings": ["variant `compact` is not defined"],
        "surprise_field": 1
    }"#;

    #[tokio::test]
    async fn reset_connector_cap_usage_posts_the_unit() {
        let (client, mock) = client_with(vec![Step::ok(
            r#"{"merchant_connector_id":"mca_1","unit":"amount","window":"month","currency":"EUR",
                "cleared":12000,"reserved":500,"reset_at":"2026-01-01T00:00:00Z","surprise_field":1}"#,
        )]);
        let out = client
            .routing()
            .reset_connector_cap_usage(
                "pro/1",
                &RoutingConnectorCapResetRequest::new("mca_1", "amount"),
            )
            .await
            .unwrap();
        assert_eq!(out.cleared, Some(12000));
        assert_eq!(out.currency.as_deref(), Some("EUR"));
        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/routing/connector-caps/pro%2F1/reset"
        );
        assert_eq!(
            seen[0].body_json(),
            json!({"merchant_connector_id": "mca_1", "unit": "amount"})
        );
    }

    /// A reset is a POST without an idempotency key: a 5xx must not replay
    /// it. Mutation: pass a key to `request` — `call_count` becomes 2.
    #[tokio::test]
    async fn reset_connector_cap_usage_is_not_retried_on_a_server_error() {
        let (client, mock) = crate::http::mock::client_with_retries(
            vec![Step::status(503, "{}"), Step::ok("{}")],
            2,
        );
        assert!(
            client
                .routing()
                .reset_connector_cap_usage(
                    "pro_1",
                    &RoutingConnectorCapResetRequest::new("mca_1", "payments"),
                )
                .await
                .is_err()
        );
        assert_eq!(mock.call_count(), 1);
    }

    #[tokio::test]
    async fn connector_cap_overrides_gets_the_merchant_list() {
        let (client, mock) = client_with(vec![Step::ok(&format!(
            r#"{{"overrides":[{OVERRIDE_JSON}],"surprise_field":1}}"#
        ))]);
        let out = client.routing().connector_cap_overrides().await.unwrap();
        assert_eq!(out.overrides[0].mode, "own");
        assert_eq!(out.overrides[0].caps[0].used, Some(2));
        assert_eq!(out.overrides[0].extra["surprise_field"], 1);
        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/routing/connector-caps/overrides"
        );
    }

    #[tokio::test]
    async fn account_connector_cap_overrides_gets_the_account_path() {
        let (client, mock) = client_with(vec![Step::ok(&format!(
            r#"{{"merchant_connector_id":"mca_1","account_scope":"pro_1",
                "overrides":[{OVERRIDE_JSON}],
                "shops":[{{"profile_id":"pro_1","source":"shop","source_id":"pro_1","mode":"own"}}],
                "surprise_field":1}}"#
        ))]);
        let out = client
            .routing()
            .account_connector_cap_overrides("mca/1")
            .await
            .unwrap();
        assert_eq!(out.account_scope, "pro_1");
        assert_eq!(out.shops[0].source, "shop");
        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/routing/connector-caps/accounts/mca%2F1/overrides"
        );
    }

    /// Mutation: swap `level` and `scope_id` in `cap_override_path` — the
    /// URL assertion fails.
    #[tokio::test]
    async fn set_connector_cap_override_puts_the_target_path() {
        let (client, mock) = client_with(vec![Step::ok(OVERRIDE_JSON)]);
        let params = ConnectorCapOverrideRequest::own(vec![RoutingConnectorCap::new("mca_1", 10)]);
        let out = client
            .routing()
            .set_connector_cap_override("mca_1", "shop", "pro/1", &params)
            .await
            .unwrap();
        assert_eq!(out.scope_name.as_deref(), Some("Main shop"));
        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/routing/connector-caps/accounts/mca_1/overrides/shop/pro%2F1"
        );
        assert_eq!(
            seen[0].body_json(),
            json!({"mode": "own", "caps": [{"merchant_connector_id": "mca_1", "limit": 10}]})
        );
    }

    #[tokio::test]
    async fn set_connector_cap_override_unlimited_sends_no_caps() {
        let (client, mock) = client_with(vec![Step::ok(OVERRIDE_JSON)]);
        client
            .routing()
            .set_connector_cap_override(
                "mca_1",
                "project",
                "prj_1",
                &ConnectorCapOverrideRequest::unlimited(),
            )
            .await
            .unwrap();

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

    #[tokio::test]
    async fn delete_connector_cap_override_deletes_the_target_path() {
        let (client, mock) = client_with(vec![Step::ok(OVERRIDE_JSON)]);
        let out = client
            .routing()
            .delete_connector_cap_override("mca_1", "project", "prj_1")
            .await
            .unwrap();
        assert_eq!(out.level, "shop");

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "DELETE");
        assert_eq!(
            seen[0].url,
            "https://api.test/routing/connector-caps/accounts/mca_1/overrides/project/prj_1"
        );
        assert!(seen[0].body.is_none());
    }

    #[tokio::test]
    async fn connector_cap_schedules_gets_and_decodes_the_schedule() {
        let (client, mock) = client_with(vec![Step::ok(SCHEDULE_JSON)]);
        let out = client
            .routing()
            .connector_cap_schedules("pro/1")
            .await
            .unwrap();
        assert_eq!(out.revision.as_deref(), Some("rev_2"));
        assert_eq!(out.entries[0].cap.limit, 5);
        assert_eq!(out.entries[0].cap.unit.as_deref(), Some("payments"));
        assert_eq!(out.entries[0].cap.extra["cap_surprise"], true);
        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/routing/connector-cap-schedules/pro%2F1"
        );
    }

    /// The first schedule is written over a `null` revision, which must be
    /// sent. Mutation: add `skip_serializing_if` to `revision` — the `null`
    /// key disappears and the body assertion fails.
    #[tokio::test]
    async fn set_connector_cap_schedules_puts_the_complete_schedule() {
        let (client, mock) = client_with(vec![Step::ok(SCHEDULE_JSON)]);
        let schedule = RoutingConnectorCapSchedule::new(
            None,
            vec![RoutingConnectorCapScheduleEntry::new(
                "e1",
                "2026-01-01T00:00:00Z",
                "2026-02-01T00:00:00Z",
                RoutingConnectorCap::new("mca_1", 5),
            )],
        );
        client
            .routing()
            .set_connector_cap_schedules("pro_1", &schedule)
            .await
            .unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "PUT");
        assert_eq!(
            seen[0].url,
            "https://api.test/routing/connector-cap-schedules/pro_1"
        );
        assert_eq!(
            seen[0].body_json(),
            json!({
                "revision": null,
                "entries": [{
                    "id": "e1",
                    "starts_at": "2026-01-01T00:00:00Z",
                    "ends_at": "2026-02-01T00:00:00Z",
                    "cap": {"merchant_connector_id": "mca_1", "limit": 5}
                }]
            })
        );
    }

    #[tokio::test]
    async fn shuffle_connector_cap_schedule_posts_to_the_shuffle_path() {
        let (client, mock) = client_with(vec![Step::ok(
            r#"{"profile_id":"pro_1","caps":[{"merchant_connector_id":"mca_1","limit":7}],
                "features":["limit_schedules"],"surprise_field":1}"#,
        )]);
        let out = client
            .routing()
            .shuffle_connector_cap_schedule(
                "pro_1",
                &RoutingConnectorCapScheduleShuffle::new("rev_2", "e1", 7),
            )
            .await
            .unwrap();
        assert_eq!(out.caps[0].limit, 7);
        assert_eq!(out.features, ["limit_schedules"]);
        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/routing/connector-cap-schedules/pro_1/shuffle"
        );
        assert_eq!(
            seen[0].body_json(),
            json!({"revision": "rev_2", "id": "e1", "value": 7})
        );
    }

    /// Mutation: drop the `start`/`end` pushes in `to_query` — the URL
    /// assertion fails; send an unset filter — an extra pair appears.
    #[tokio::test]
    async fn checkout_theme_conversion_sends_the_window_and_filters() {
        let (client, mock) = client_with(vec![Step::ok(
            r#"{"segment":"device","filters":{"device_class":"phone","country":null},
                "cells":[{"variant":"compact","segment":"phone","rendered":100,"paid":12,
                    "rate":0.12,"interval_low":0.07,"interval_high":0.2,"verdict":"enough"}],
                "comparisons":[{"variant":"compact","segment":"phone","variant_rate":0.12,
                    "baseline_rate":0.08,"separates":true,"higher":"variant"}],
                "denominator":"deduplicated_checkout_opens","caveats":["automated_traffic_excluded"],
                "surprise_field":1}"#,
        )]);
        let params =
            CheckoutThemeConversionParams::new("2026-01-01T00:00:00Z", "2026-02-01T00:00:00Z")
                .profile_id("pro_1")
                .segment("device")
                .device_class("phone");
        let out = client
            .routing()
            .checkout_theme_conversion(&params)
            .await
            .unwrap();
        assert_eq!(out.cells[0].paid, 12);
        assert_eq!(out.cells[0].rate, Some(0.12));
        assert!(out.comparisons[0].separates);
        assert_eq!(out.filters.device_class.as_deref(), Some("phone"));
        assert_eq!(out.caveats, ["automated_traffic_excluded"]);
        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/routing/checkout-theme/conversion?profile_id=pro_1&start=2026-01-01T00:00:00Z&end=2026-02-01T00:00:00Z&segment=device&device_class=phone"
        );
    }

    #[tokio::test]
    async fn checkout_theme_rules_upsert_puts_the_program() {
        let (client, mock) = client_with(vec![Step::ok(THEME_PROGRAM_JSON)]);
        let algorithm = json!({
            "rules": [],
            "defaultSelection": {"theme": {"variant": "house"}},
            "metadata": {}
        });
        let params = CheckoutThemeProgramRequest::new(algorithm.clone())
            .name("Autumn targeting")
            .profile_id("pro_1")
            .active(false);
        let out = client
            .routing()
            .checkout_theme_rules()
            .upsert(&params)
            .await
            .unwrap();
        assert_eq!(out.version, 3);
        assert_eq!(out.warnings.len(), 1);
        assert_eq!(
            out.algorithm["defaultSelection"]["theme"]["variant"],
            "house"
        );
        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/routing/checkout-theme/rules");
        assert_eq!(
            seen[0].body_json(),
            json!({
                "name": "Autumn targeting",
                "profile_id": "pro_1",
                "algorithm": algorithm,
                "active": false
            })
        );
    }

    #[tokio::test]
    async fn checkout_theme_rules_retrieve_scopes_and_decodes_null() {
        let (client, mock) = client_with(vec![Step::ok(THEME_PROGRAM_JSON), Step::ok("null")]);
        let rules = client.routing().checkout_theme_rules();
        let found = rules.retrieve(Some("pro_1")).await.unwrap();
        assert_eq!(found.unwrap().id, "thm_1");
        assert!(rules.retrieve(None).await.unwrap().is_none());

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "GET");
        assert_eq!(
            seen[0].url,
            "https://api.test/routing/checkout-theme/rules?profile_id=pro_1"
        );
        assert_eq!(seen[1].url, "https://api.test/routing/checkout-theme/rules");
    }

    #[tokio::test]
    async fn checkout_theme_rules_delete_scopes_the_deactivation() {
        let (client, mock) = client_with(vec![Step::ok("")]);
        client
            .routing()
            .checkout_theme_rules()
            .delete(Some("pro_1"))
            .await
            .unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "DELETE");
        assert_eq!(
            seen[0].url,
            "https://api.test/routing/checkout-theme/rules?profile_id=pro_1"
        );
    }

    /// The API documents no body for this 200, but a JSON success body must
    /// still read as success. Mutation: drop the `IgnoredAny` turbofish so the
    /// call decodes into `()` — this answer then fails with `Decode`.
    #[tokio::test]
    async fn checkout_theme_rules_delete_accepts_a_json_success_body() {
        let (client, mock) = client_with(vec![Step::ok(
            r#"{"deactivated":true,"profile_id":"pro_1"}"#,
        )]);
        let out = client.routing().checkout_theme_rules().delete(None).await;
        assert!(out.is_ok(), "{out:?}");

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "DELETE");
        assert_eq!(seen[0].url, "https://api.test/routing/checkout-theme/rules");
    }

    /// Drift guard for `CONNECTOR_CAP_OVERRIDE_REQUEST_NAMED`.
    #[test]
    fn connector_cap_override_request_named_fields_are_complete() {
        let req = ConnectorCapOverrideRequest::own(vec![RoutingConnectorCap::new("mca_1", 1)]);
        let value = serde_json::to_value(req).unwrap();
        for key in value.as_object().expect("serializes to an object").keys() {
            assert!(
                CONNECTOR_CAP_OVERRIDE_REQUEST_NAMED.contains(&key.as_str()),
                "CONNECTOR_CAP_OVERRIDE_REQUEST_NAMED is missing wire key `{key}`"
            );
        }
    }

    /// Drift guard for `CHECKOUT_THEME_PROGRAM_REQUEST_NAMED`.
    #[test]
    fn checkout_theme_program_request_named_fields_are_complete() {
        let req = CheckoutThemeProgramRequest::new(json!({}))
            .name("n")
            .profile_id("pro_1")
            .active(true)
            .valid_from("2026-01-01T00:00:00Z")
            .valid_until("2026-02-01T00:00:00Z");
        let value = serde_json::to_value(req).unwrap();
        for key in value.as_object().expect("serializes to an object").keys() {
            assert!(
                CHECKOUT_THEME_PROGRAM_REQUEST_NAMED.contains(&key.as_str()),
                "CHECKOUT_THEME_PROGRAM_REQUEST_NAMED is missing wire key `{key}`"
            );
        }
    }

    /// Mutation: return `Ok(())` from either `validate` — its assertion fails.
    #[test]
    fn override_and_theme_requests_reject_colliding_extra_keys() {
        let mut a = ConnectorCapOverrideRequest::unlimited();
        a.extra.insert("mode".to_string(), json!("own"));
        match a.validate().unwrap_err() {
            DelopayError::InvalidRequest(msg) => assert!(msg.contains("mode")),
            other => panic!("expected InvalidRequest, got {other:?}"),
        }
        let mut b = CheckoutThemeProgramRequest::new(json!({}));
        b.extra.insert("algorithm".to_string(), json!({}));
        match b.validate().unwrap_err() {
            DelopayError::InvalidRequest(msg) => assert!(msg.contains("algorithm")),
            other => panic!("expected InvalidRequest, got {other:?}"),
        }
    }

    /// 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 = RoutingConnectorCapResetRequest::new("mca_1", "amount");
        assert!(
            client
                .routing()
                .reset_connector_cap_usage("pro_1", &params)
                .await
                .is_err()
        );
        assert_sent_once_unkeyed(&mock);

        let (client, mock) = keyed_client_over_503s();
        assert!(
            client
                .routing()
                .checkout_theme_rules()
                .delete(None)
                .await
                .is_err()
        );
        assert_sent_once_unkeyed(&mock);
    }
}