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
//! The `subscriptions` resource: recurring billing through a connected
//! billing processor (Stripe Billing, PayPal, …).
//!
//! Subscription endpoints are **profile-scoped**: the backend needs an
//! `x-profile-id` header to resolve the shop / billing processor and rejects
//! calls without one (`IR_04`). Scope the resource once with
//! [`Subscriptions::with_profile_id`]:
//!
//! ```no_run
//! # use delopay::Delopay;
//! # async fn run(client: Delopay) -> delopay::Result<()> {
//! let subscriptions = client.subscriptions().with_profile_id("pro_your_shop");
//! let sub = subscriptions.retrieve("sub_123").await?;
//! # Ok(())
//! # }
//! ```

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::common::{Address, AuthenticationType, CaptureMethod, SetupFutureUsage};
use crate::core::models::subscription::{
    AdoptSubscriptionResponse, CancelSubscriptionResponse, ConfirmSubscriptionResponse,
    NativeDunningConfigResponse, NativeRecoveryMode, NativeShopConfigResponse,
    PauseSubscriptionResponse, ResumeSubscriptionResponse, SubscriptionBillingProcessorResponse,
    SubscriptionCapabilities, SubscriptionEstimateResponse, SubscriptionImportApplyResponse,
    SubscriptionImportPreviewResponse, SubscriptionInvoiceListResponse, SubscriptionItem,
    SubscriptionPaymentLookupResponse, SubscriptionResponse, SubscriptionSyncResponse,
    SubscriptionSyncResult,
};
use crate::http::client::Inner;
use crate::http::transport::HttpMethod;
use crate::resources::ValidateRequest;

/// The most ids [`Subscriptions::lookup_payments`] accepts in one call.
///
/// The server enforces the same number: the cap exists so one request cannot
/// become an unbounded `IN (...)` against the invoice table. A dashboard page
/// is 20–100 rows, so this is not a limit real callers reach.
pub const PAYMENT_LOOKUP_MAX_IDS: usize = 200;

/// The `subscriptions` resource, obtained via [`crate::Delopay::subscriptions`].
///
/// See the [module docs](self) for the required profile scoping.
#[derive(Debug, Clone)]
pub struct Subscriptions {
    inner: Arc<Inner>,
    profile_id: Option<String>,
}

impl Subscriptions {
    pub(crate) fn new(inner: Arc<Inner>) -> Self {
        Self {
            inner,
            profile_id: None,
        }
    }

    /// Scope every call from this resource to one shop (business profile) by
    /// sending its ID as the `x-profile-id` header.
    #[must_use]
    pub fn with_profile_id(mut self, profile_id: impl Into<String>) -> Self {
        self.profile_id = Some(profile_id.into());
        self
    }

    /// The scoping headers for this resource, if a profile was set.
    fn headers(&self) -> Vec<(&str, &str)> {
        match &self.profile_id {
            Some(id) => vec![("x-profile-id", id.as_str())],
            None => Vec::new(),
        }
    }

    async fn send<T: serde::de::DeserializeOwned>(
        &self,
        method: HttpMethod,
        path: &str,
        body: Option<&[u8]>,
        query: &[(&str, String)],
    ) -> Result<T> {
        self.inner
            .request_with_headers(method, path, body, query, None, &self.headers())
            .await
    }

    /// [`send`](Self::send) for a write the route does not deduplicate: no
    /// `Idempotency-Key` is sent, not even the client-wide default, so a
    /// network error or `5xx` is never replayed.
    async fn send_unkeyed<T: serde::de::DeserializeOwned>(
        &self,
        method: HttpMethod,
        path: &str,
        body: Option<&[u8]>,
        query: &[(&str, String)],
    ) -> Result<T> {
        self.inner
            .request_body_keyed_with_query_and_headers(
                method,
                path,
                body,
                query,
                &self.headers(),
                None,
            )
            .await
    }

    /// Create and immediately confirm a subscription.
    ///
    /// For billing processors that require buyer approval (e.g. PayPal), the
    /// response carries a
    /// [`redirect_url`](ConfirmSubscriptionResponse::redirect_url) the
    /// customer must be sent to.
    pub async fn create_and_confirm(
        &self,
        params: &CreateAndConfirmSubscriptionRequest,
    ) -> Result<ConfirmSubscriptionResponse> {
        params.validate()?;
        let body = to_json_vec(params)?;
        self.send(HttpMethod::Post, "/subscriptions", Some(&body), &[])
            .await
    }

    /// Create a subscription without confirming it.
    pub async fn create(&self, params: &CreateSubscriptionRequest) -> Result<SubscriptionResponse> {
        params.validate()?;
        let body = to_json_vec(params)?;
        self.send(HttpMethod::Post, "/subscriptions/create", Some(&body), &[])
            .await
    }

    /// Retrieve a subscription by ID.
    pub async fn retrieve(&self, subscription_id: &str) -> Result<SubscriptionResponse> {
        let path = format!("/subscriptions/{}", encode_segment(subscription_id));
        self.send(HttpMethod::Get, &path, None, &[]).await
    }

    /// Confirm a previously created subscription. Like
    /// [`create_and_confirm`](Self::create_and_confirm), the response may
    /// carry a `redirect_url` for processors that require buyer approval.
    pub async fn confirm(
        &self,
        subscription_id: &str,
        params: &ConfirmSubscriptionRequest,
    ) -> Result<ConfirmSubscriptionResponse> {
        let path = format!("/subscriptions/{}/confirm", encode_segment(subscription_id));
        let body = to_json_vec(params)?;
        self.send(HttpMethod::Post, &path, Some(&body), &[]).await
    }

    /// Change a subscription's price. Exactly one price source is sent;
    /// anything else is refused before sending.
    pub async fn update(
        &self,
        subscription_id: &str,
        params: &UpdateSubscriptionRequest,
    ) -> Result<SubscriptionResponse> {
        params.validate()?;
        let path = format!("/subscriptions/{}/update", encode_segment(subscription_id));
        let body = to_json_vec(params)?;
        self.send(HttpMethod::Put, &path, Some(&body), &[]).await
    }

    /// List the profile's subscriptions.
    pub async fn list(
        &self,
        params: Option<&SubscriptionListParams>,
    ) -> Result<Vec<SubscriptionResponse>> {
        let query = params
            .map(SubscriptionListParams::to_query)
            .unwrap_or_default();
        self.send(HttpMethod::Get, "/subscriptions/list", None, &query)
            .await
    }

    /// Estimate the cost of a subscription before creating it.
    pub async fn estimate(
        &self,
        params: &SubscriptionEstimateParams,
    ) -> Result<SubscriptionEstimateResponse> {
        self.send(
            HttpMethod::Get,
            "/subscriptions/estimate",
            None,
            &params.to_query(),
        )
        .await
    }

    /// List purchasable subscription items (plans or addons).
    pub async fn items(&self, params: &SubscriptionItemsParams) -> Result<Vec<SubscriptionItem>> {
        self.send(
            HttpMethod::Get,
            "/subscriptions/items",
            None,
            &params.to_query(),
        )
        .await
    }

    /// Pause a subscription.
    pub async fn pause(
        &self,
        subscription_id: &str,
        params: Option<&PauseSubscriptionRequest>,
    ) -> Result<PauseSubscriptionResponse> {
        let path = format!("/subscriptions/{}/pause", encode_segment(subscription_id));
        let body = Self::body_or_empty_object(params)?;
        self.send(HttpMethod::Post, &path, Some(&body), &[]).await
    }

    /// Resume a paused subscription.
    pub async fn resume(
        &self,
        subscription_id: &str,
        params: Option<&ResumeSubscriptionRequest>,
    ) -> Result<ResumeSubscriptionResponse> {
        let path = format!("/subscriptions/{}/resume", encode_segment(subscription_id));
        let body = Self::body_or_empty_object(params)?;
        self.send(HttpMethod::Post, &path, Some(&body), &[]).await
    }

    /// Cancel a subscription.
    ///
    /// Refused with `DE_11` when it cannot be cancelled; `error.data.reason`
    /// says why: `already_cancelled`, or `checkout_still_payable` while the
    /// first checkout can still be paid.
    pub async fn cancel(
        &self,
        subscription_id: &str,
        params: Option<&CancelSubscriptionRequest>,
    ) -> Result<CancelSubscriptionResponse> {
        let path = format!("/subscriptions/{}/cancel", encode_segment(subscription_id));
        let body = Self::body_or_empty_object(params)?;
        self.send(HttpMethod::Post, &path, Some(&body), &[]).await
    }

    /// Resolve which of the given payments were raised by a subscription.
    ///
    /// The linkage exists in **one direction only** — an invoice points at
    /// the payment it settled, and nothing is stamped on the payment — so
    /// this is the only way to tell a subscription charge from a one-off one
    /// while holding a page of payments.
    ///
    /// Do **not** infer it from `off_session` or the presence of a mandate
    /// instead: an ordinary saved-card charge sets both identically, and the
    /// guess mislabels every one of them.
    ///
    /// Ids belonging to no subscription are **absent** from the result rather
    /// than an error, so match on presence:
    ///
    /// ```no_run
    /// # use delopay::Delopay;
    /// # async fn run(client: Delopay, page: Vec<String>) -> delopay::Result<()> {
    /// let links = client
    ///     .subscriptions()
    ///     .with_profile_id("pro_shop")
    ///     .lookup_payments(&page)
    ///     .await?
    ///     .links;
    /// for link in &links {
    ///     println!("{} came from {}", link.payment_id, link.subscription_id);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// Profile-scoped like every other subscription route, and here that is
    /// part of the question rather than an optimisation: a `payment_id` is
    /// merchant-supplied and only unique within a merchant, so the shop is
    /// what makes an id mean one payment. For a list spanning several shops,
    /// group the ids by shop and call once per group.
    ///
    /// At most [`PAYMENT_LOOKUP_MAX_IDS`] ids per call, rejected here rather
    /// than on the wire — the caller is holding a page and can split it, and
    /// a local error names the limit without spending a round trip.
    ///
    /// `POST /subscriptions/payments/lookup`
    ///
    /// # Errors
    ///
    /// [`DelopayError::InvalidRequest`] when more than
    /// [`PAYMENT_LOOKUP_MAX_IDS`] ids are passed.
    pub async fn lookup_payments(
        &self,
        payment_ids: &[String],
    ) -> Result<SubscriptionPaymentLookupResponse> {
        if payment_ids.len() > PAYMENT_LOOKUP_MAX_IDS {
            return Err(DelopayError::InvalidRequest(format!(
                "payment_ids accepts at most {PAYMENT_LOOKUP_MAX_IDS} entries, got {}",
                payment_ids.len()
            )));
        }
        let body = to_json_vec(&SubscriptionPaymentLookupRequest { payment_ids })?;
        self.send(
            HttpMethod::Post,
            "/subscriptions/payments/lookup",
            Some(&body),
            &[],
        )
        .await
    }

    /// Read the shop's native enrollment settings.
    ///
    /// `GET /subscriptions/native/config`
    pub async fn native_config(&self) -> Result<NativeShopConfigResponse> {
        self.send(HttpMethod::Get, "/subscriptions/native/config", None, &[])
            .await
    }

    /// Replace the shop's native enrollment settings: whether it enrolls card
    /// subscriptions natively, through which payment account, and in which
    /// environment. Existing agreements keep the account they were created on.
    ///
    /// `PUT /subscriptions/native/config`
    pub async fn update_native_config(
        &self,
        params: &NativeShopConfigRequest,
    ) -> Result<NativeShopConfigResponse> {
        params.validate()?;
        let body = to_json_vec(params)?;
        self.send_unkeyed(
            HttpMethod::Put,
            "/subscriptions/native/config",
            Some(&body),
            &[],
        )
        .await
    }

    /// Read the merchant-wide renewal recovery settings.
    ///
    /// `GET /subscriptions/native/dunning`
    pub async fn native_dunning(&self) -> Result<NativeDunningConfigResponse> {
        self.send(HttpMethod::Get, "/subscriptions/native/dunning", None, &[])
            .await
    }

    /// Replace the merchant-wide renewal recovery settings.
    ///
    /// `PUT /subscriptions/native/dunning`
    pub async fn update_native_dunning(
        &self,
        params: &NativeDunningConfigRequest,
    ) -> Result<NativeDunningConfigResponse> {
        params.validate()?;
        let body = to_json_vec(params)?;
        self.send_unkeyed(
            HttpMethod::Put,
            "/subscriptions/native/dunning",
            Some(&body),
            &[],
        )
        .await
    }

    /// Which lifecycle actions a subscription supports.
    ///
    /// `GET /subscriptions/{subscription_id}/capabilities`
    pub async fn capabilities(&self, subscription_id: &str) -> Result<SubscriptionCapabilities> {
        let path = format!(
            "/subscriptions/{}/capabilities",
            encode_segment(subscription_id)
        );
        self.send(HttpMethod::Get, &path, None, &[]).await
    }

    /// Take a subscription already running at its billing processor into
    /// DeloPay. Only Creem is supported today, and adoption must be enabled.
    ///
    /// Adoption charges nothing and emits no invoice or webhook. Repeating the
    /// processor's subscription ID returns the existing DeloPay subscription
    /// with [`adopted`](AdoptSubscriptionResponse::adopted) set to `false`.
    /// Retry when [`handoff_confirmed`](AdoptSubscriptionResponse::handoff_confirmed)
    /// is `false`; it confirms the adoption was stored, not that your own
    /// integration stopped handling the processor's events.
    ///
    /// `POST /subscriptions/adopt`
    pub async fn adopt(
        &self,
        params: &AdoptSubscriptionRequest,
    ) -> Result<AdoptSubscriptionResponse> {
        params.validate()?;
        let body = to_json_vec(params)?;
        self.send_unkeyed(HttpMethod::Post, "/subscriptions/adopt", Some(&body), &[])
            .await
    }

    /// Read 1 to 50 subscriptions back from their billing processor and
    /// mirror what it reports.
    ///
    /// Nothing is written at the processor. A status is mirrored only with
    /// the time the processor stamped it with, and never over a newer event
    /// already recorded. One result per ID, in request order; one that fails
    /// does not stop the others.
    ///
    /// `POST /subscriptions/sync`
    pub async fn sync(&self, params: &SubscriptionSyncRequest) -> Result<SubscriptionSyncResponse> {
        let body = to_json_vec(params)?;
        self.send_unkeyed(HttpMethod::Post, "/subscriptions/sync", Some(&body), &[])
            .await
    }

    /// Read one subscription back from its billing processor and mirror what
    /// it reports, as [`sync`](Self::sync) does, with what the processor
    /// reported beside what the mirror now holds.
    ///
    /// `POST /subscriptions/{subscription_id}/sync`
    pub async fn sync_one(&self, subscription_id: &str) -> Result<SubscriptionSyncResult> {
        let path = format!("/subscriptions/{}/sync", encode_segment(subscription_id));
        self.send_unkeyed(HttpMethod::Post, &path, None, &[]).await
    }

    /// List the subscriptions a billing account holds at its processor, and
    /// how each relates to DeloPay's: already held, new, needing a customer,
    /// ended, or not adoptable here.
    ///
    /// Reads only; nothing is written here or at the processor. A processor
    /// that offers no listing says so in
    /// [`capabilities`](SubscriptionImportPreviewResponse::capabilities).
    ///
    /// `POST /subscriptions/import/preview`
    pub async fn import_preview(
        &self,
        params: &SubscriptionImportPreviewRequest,
    ) -> Result<SubscriptionImportPreviewResponse> {
        let body = to_json_vec(params)?;
        self.send_unkeyed(
            HttpMethod::Post,
            "/subscriptions/import/preview",
            Some(&body),
            &[],
        )
        .await
    }

    /// Take 1 to 25 processor subscriptions over, each through
    /// [`adopt`](Self::adopt) with every one of its checks, one after another.
    ///
    /// One result per selection, in request order; one refused does not stop
    /// the others.
    ///
    /// `POST /subscriptions/import/apply`
    pub async fn import_apply(
        &self,
        params: &SubscriptionImportApplyRequest,
    ) -> Result<SubscriptionImportApplyResponse> {
        params.validate()?;
        let body = to_json_vec(params)?;
        self.send_unkeyed(
            HttpMethod::Post,
            "/subscriptions/import/apply",
            Some(&body),
            &[],
        )
        .await
    }

    /// One subscription's billing history, newest cycle first.
    ///
    /// [`retrieve`](Self::retrieve) carries only the latest invoice. Use this
    /// wherever every billed cycle matters, in particular on processors that
    /// charge each renewal themselves.
    ///
    /// `amount` is gross. A processor-hosted origination records a first
    /// invoice at `0` before the buyer has paid, so a zero amount there is a
    /// placeholder rather than a free cycle.
    ///
    /// `GET /subscriptions/{subscription_id}/invoices`
    pub async fn list_invoices(
        &self,
        subscription_id: &str,
        params: Option<&SubscriptionInvoiceListParams>,
    ) -> Result<SubscriptionInvoiceListResponse> {
        let path = format!(
            "/subscriptions/{}/invoices",
            encode_segment(subscription_id)
        );
        let query = params
            .map(SubscriptionInvoiceListParams::to_query)
            .unwrap_or_default();
        self.send(HttpMethod::Get, &path, None, &query).await
    }

    /// Which billing processor this shop's subscriptions run on.
    ///
    /// Answers under the same authorization as the rest of the subscription
    /// API. Use it when the client must branch on the processor before
    /// calling: origination differs by processor. A shop with no billing
    /// processor assigned has nothing to report here.
    ///
    /// `GET /subscriptions/billing_processor`
    pub async fn billing_processor(&self) -> Result<SubscriptionBillingProcessorResponse> {
        self.send(
            HttpMethod::Get,
            "/subscriptions/billing_processor",
            None,
            &[],
        )
        .await
    }

    /// Serialize `params`, defaulting to `{}` when absent: the backend
    /// rejects a bodyless POST on these endpoints ("Unsupported content
    /// type"), 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()),
        }
    }
}

/// Body of [`Subscriptions::lookup_payments`].
///
/// Borrowed rather than owned: the ids come from a page the caller already
/// holds, and copying a batch of up to 200 strings to send them once is work
/// for nothing.
#[derive(Debug, Serialize)]
struct SubscriptionPaymentLookupRequest<'a> {
    payment_ids: &'a [String],
}

/// Payment options for [`Subscriptions::create`].
#[derive(Debug, Clone, Default, Serialize)]
pub struct CreateSubscriptionPaymentDetails {
    /// URL the customer is returned to after completing the purchase.
    pub return_url: String,
    /// How the saved payment method may be used for future cycles.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub setup_future_usage: Option<SetupFutureUsage>,
    /// How and when funds are captured.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub capture_method: Option<CaptureMethod>,
    /// Whether to request 3-D Secure.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub authentication_type: Option<AuthenticationType>,
    /// Payment type hint — see the API reference.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub payment_type: Option<String>,
}

/// Parameters for [`Subscriptions::create`].
#[derive(Debug, Clone, Default, Serialize)]
pub struct CreateSubscriptionRequest {
    /// The billing processor's price to bill on (from
    /// [`Subscriptions::items`]). Required unless `product_id` selects a
    /// catalog product instead; the two forms are exclusive.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub item_price_id: Option<String>,
    /// A recurring product of this shop to bill on. The server resolves its
    /// active default price, or `price_id`, to the processor's price.
    /// Exclusive with `item_price_id`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub product_id: Option<String>,
    /// One of `product_id`'s active recurring prices. Only with `product_id`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub price_id: Option<String>,
    /// Customer to subscribe.
    pub customer_id: String,
    /// Payment options for the first charge.
    pub payment_details: CreateSubscriptionPaymentDetails,
    /// Your own reference for this subscription.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub merchant_reference_id: Option<String>,
    /// Plan the price belongs to.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub plan_id: Option<String>,
    /// Coupon to apply.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub coupon_code: Option<String>,
    /// Billing address.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub billing: Option<Address>,
    /// Shipping address.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub shipping: Option<Address>,
    /// Any additional create 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 `CreateSubscriptionRequest`'s fields as they appear on the wire
/// (`extra` excluded). See `PAYMENT_CREATE_REQUEST_NAMED` in `payments.rs`
/// for why this list lives next to the struct.
const CREATE_SUBSCRIPTION_REQUEST_NAMED: &[&str] = &[
    "item_price_id",
    "product_id",
    "price_id",
    "customer_id",
    "payment_details",
    "merchant_reference_id",
    "plan_id",
    "coupon_code",
    "billing",
    "shipping",
];

impl ValidateRequest for CreateSubscriptionRequest {
    fn validate(&self) -> Result<()> {
        for key in self.extra.keys() {
            if CREATE_SUBSCRIPTION_REQUEST_NAMED.contains(&key.as_str()) {
                return Err(DelopayError::InvalidRequest(format!(
                    "`extra` key `{key}` collides with a named field on CreateSubscriptionRequest"
                )));
            }
        }
        check_price_source(
            self.item_price_id.as_deref(),
            self.product_id.as_deref(),
            self.price_id.as_deref(),
        )
    }
}

/// Payment options for [`Subscriptions::create_and_confirm`].
#[derive(Debug, Clone, Default, Serialize)]
pub struct SubscriptionPaymentDetails {
    /// Payment method family, e.g. `"card"`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub payment_method: Option<String>,
    /// Payment method sub-type, e.g. `"credit"`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub payment_method_type: Option<String>,
    /// Payment method data (open shape — see the API reference).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub payment_method_data: Option<Value>,
    /// How the saved payment method may be used for future cycles.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub setup_future_usage: Option<SetupFutureUsage>,
    /// Customer acceptance record for the mandate (open shape).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub customer_acceptance: Option<Value>,
    /// URL the customer is returned to after completing the purchase.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub return_url: Option<String>,
    /// How and when funds are captured.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub capture_method: Option<CaptureMethod>,
    /// Whether to request 3-D Secure.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub authentication_type: Option<AuthenticationType>,
    /// Payment type hint — see the API reference.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub payment_type: Option<String>,
    /// Saved payment method to charge.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub payment_method_id: Option<String>,
}

/// Parameters for [`Subscriptions::create_and_confirm`].
#[derive(Debug, Clone, Default, Serialize)]
pub struct CreateAndConfirmSubscriptionRequest {
    /// The billing processor's price to bill on (from
    /// [`Subscriptions::items`]). Required unless `product_id` selects a
    /// catalog product instead; the two forms are exclusive.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub item_price_id: Option<String>,
    /// A recurring product of this shop to bill on. The server resolves its
    /// active default price, or `price_id`, to the processor's price.
    /// Exclusive with `item_price_id`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub product_id: Option<String>,
    /// One of `product_id`'s active recurring prices. Only with `product_id`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub price_id: Option<String>,
    /// Customer to subscribe.
    pub customer_id: String,
    /// Payment options for the first charge.
    pub payment_details: SubscriptionPaymentDetails,
    /// Plan the price belongs to.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub plan_id: Option<String>,
    /// Coupon to apply.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub coupon_code: Option<String>,
    /// Billing address.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub billing: Option<Address>,
    /// Shipping address.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub shipping: Option<Address>,
    /// Your own reference for this subscription.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub merchant_reference_id: 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 `CreateAndConfirmSubscriptionRequest`'s fields as they appear on
/// the wire (`extra` excluded).
const CREATE_AND_CONFIRM_SUBSCRIPTION_REQUEST_NAMED: &[&str] = &[
    "item_price_id",
    "product_id",
    "price_id",
    "customer_id",
    "payment_details",
    "plan_id",
    "coupon_code",
    "billing",
    "shipping",
    "merchant_reference_id",
];

impl ValidateRequest for CreateAndConfirmSubscriptionRequest {
    fn validate(&self) -> Result<()> {
        for key in self.extra.keys() {
            if CREATE_AND_CONFIRM_SUBSCRIPTION_REQUEST_NAMED.contains(&key.as_str()) {
                return Err(DelopayError::InvalidRequest(format!(
                    "`extra` key `{key}` collides with a named field on \
                     CreateAndConfirmSubscriptionRequest"
                )));
            }
        }
        check_price_source(
            self.item_price_id.as_deref(),
            self.product_id.as_deref(),
            self.price_id.as_deref(),
        )
    }
}

/// Payment options for [`Subscriptions::confirm`].
#[derive(Debug, Clone, Default, Serialize)]
pub struct ConfirmSubscriptionPaymentDetails {
    /// Payment method family, e.g. `"card"`.
    pub payment_method: String,
    /// Payment method sub-type, e.g. `"credit"`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub payment_method_type: Option<String>,
    /// Payment method data (open shape — see the API reference).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub payment_method_data: Option<Value>,
    /// Customer acceptance record for the mandate (open shape).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub customer_acceptance: Option<Value>,
    /// Billing address.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub billing: Option<Address>,
    /// Shipping address.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub shipping: Option<Address>,
    /// Payment type hint — see the API reference.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub payment_type: Option<String>,
    /// Token of a saved payment method to charge.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub payment_token: Option<String>,
}

/// Parameters for [`Subscriptions::confirm`].
#[derive(Debug, Clone, Default, Serialize)]
pub struct ConfirmSubscriptionRequest {
    /// Payment options for the confirming charge.
    pub payment_details: ConfirmSubscriptionPaymentDetails,
    /// Client secret minted at create time; required for client-side confirm.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub client_secret: Option<String>,
}

/// Exactly one price source: the processor's `item_price_id`, or a catalog
/// `product_id` (optionally with one of its `price_id`s). The API refuses
/// anything else.
fn check_price_source(
    item_price_id: Option<&str>,
    product_id: Option<&str>,
    price_id: Option<&str>,
) -> Result<()> {
    match (item_price_id, product_id) {
        (Some(_), Some(_)) => Err(DelopayError::InvalidRequest(
            "`item_price_id` and `product_id` are exclusive; send one".to_owned(),
        )),
        (None, None) => Err(DelopayError::InvalidRequest(
            "a price source is required: `item_price_id` or `product_id`".to_owned(),
        )),
        (Some(_), None) if price_id.is_some() => Err(DelopayError::InvalidRequest(
            "`price_id` is only sent with `product_id`".to_owned(),
        )),
        _ => Ok(()),
    }
}

/// Parameters for [`Subscriptions::update`]: the price to move the
/// subscription to, as the processor's `item_price_id` or a catalog
/// `product_id`.
#[derive(Debug, Clone, Default, Serialize)]
pub struct UpdateSubscriptionRequest {
    /// The new plan's label. It is not sent to the processor; `None` leaves
    /// the stored label as it is. Not with `product_id`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub plan_id: Option<String>,
    /// The billing processor's price to move the subscription to.
    /// Exclusive with `product_id`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub item_price_id: Option<String>,
    /// A recurring product of this shop to move the subscription to.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub product_id: Option<String>,
    /// One of `product_id`'s active recurring prices. Only with `product_id`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub price_id: Option<String>,
}

impl UpdateSubscriptionRequest {
    /// Move the subscription to the processor's price `item_price_id`.
    pub fn for_price(item_price_id: impl Into<String>) -> Self {
        Self {
            item_price_id: Some(item_price_id.into()),
            ..Default::default()
        }
    }

    /// Move the subscription to a catalog product's active default price.
    pub fn for_product(product_id: impl Into<String>) -> Self {
        Self {
            product_id: Some(product_id.into()),
            ..Default::default()
        }
    }

    /// The new plan's label.
    #[must_use]
    pub fn plan_id(mut self, plan_id: impl Into<String>) -> Self {
        self.plan_id = Some(plan_id.into());
        self
    }

    /// One of the product's active recurring prices.
    #[must_use]
    pub fn price_id(mut self, price_id: impl Into<String>) -> Self {
        self.price_id = Some(price_id.into());
        self
    }

    fn validate(&self) -> Result<()> {
        if self.product_id.is_some() && self.plan_id.is_some() {
            return Err(DelopayError::InvalidRequest(
                "`plan_id` is not sent with `product_id`".to_owned(),
            ));
        }
        check_price_source(
            self.item_price_id.as_deref(),
            self.product_id.as_deref(),
            self.price_id.as_deref(),
        )
    }
}

/// Parameters for [`Subscriptions::pause`].
#[derive(Debug, Clone, Default, Serialize)]
pub struct PauseSubscriptionRequest {
    /// When to pause: `"immediately"`, `"end_of_term"`, or `"specific_date"`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub pause_option: Option<String>,
    /// ISO 8601 timestamp; honoured when `pause_option` is `"specific_date"`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub pause_at: Option<String>,
}

/// Parameters for [`Subscriptions::resume`].
#[derive(Debug, Clone, Default, Serialize)]
pub struct ResumeSubscriptionRequest {
    /// When to resume: `"immediately"` or `"specific_date"`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub resume_option: Option<String>,
    /// ISO 8601 timestamp; honoured when `resume_option` is `"specific_date"`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub resume_date: Option<String>,
    /// What to do with charges accrued while paused:
    /// `"invoice_immediately"` or `"add_to_unbilled_charges"`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub charges_handling: Option<String>,
    /// What to do with unpaid invoices: `"no_action"` or
    /// `"schedule_payment_collection"`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub unpaid_invoices_handling: Option<String>,
}

/// Parameters for [`Subscriptions::cancel`].
#[derive(Debug, Clone, Default, Serialize)]
pub struct CancelSubscriptionRequest {
    /// When to cancel: `"immediately"`, `"end_of_term"`, or `"specific_date"`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cancel_option: Option<String>,
    /// ISO 8601 timestamp; honoured when `cancel_option` is `"specific_date"`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cancel_at: Option<String>,
    /// What to do with unbilled charges: `"invoice"` or `"delete"`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub unbilled_charges_option: Option<String>,
    /// Credit handling for the current term: `"none"`, `"prorate"`, or
    /// `"full"`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub credit_option_for_current_term_charges: Option<String>,
    /// Receivables handling: `"no_action"`, `"schedule_payment_collection"`,
    /// or `"write_off"`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub account_receivables_handling: Option<String>,
    /// Refundable-credit handling: `"no_action"` or `"schedule_refund"`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub refundable_credits_handling: Option<String>,
    /// Your reason code for the cancellation.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cancel_reason_code: Option<String>,
}

/// Pagination parameters for [`Subscriptions::list`].
#[derive(Debug, Clone, Default)]
pub struct SubscriptionListParams {
    /// Maximum number of subscriptions to return.
    pub limit: Option<i64>,
    /// Number of subscriptions to skip.
    pub offset: Option<i64>,
    /// Which environment to read: `true` for test, `false` for live. Omitted
    /// takes the route's own default.
    pub test_mode: Option<bool>,
}

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

/// Query parameters for [`Subscriptions::items`].
#[derive(Debug, Clone, Default)]
pub struct SubscriptionItemsParams {
    /// Item kind to list: `"plan"` or `"addon"`. Required by the API.
    pub item_type: String,
    /// Client secret, for client-side listing.
    pub client_secret: Option<String>,
    /// Maximum number of items to return.
    pub limit: Option<i64>,
    /// Number of items to skip.
    pub offset: Option<i64>,
}

impl SubscriptionItemsParams {
    /// Parameters listing items of the given kind (`"plan"` or `"addon"`).
    pub fn new(item_type: impl Into<String>) -> Self {
        Self {
            item_type: item_type.into(),
            ..Default::default()
        }
    }

    fn to_query(&self) -> Vec<(&'static str, String)> {
        let mut q = vec![("item_type", self.item_type.clone())];
        if let Some(v) = &self.client_secret {
            q.push(("client_secret", v.clone()));
        }
        if let Some(v) = self.limit {
            q.push(("limit", v.to_string()));
        }
        if let Some(v) = self.offset {
            q.push(("offset", v.to_string()));
        }
        q
    }
}

/// Query parameters for [`Subscriptions::estimate`].
#[derive(Debug, Clone, Default)]
pub struct SubscriptionEstimateParams {
    /// Price to estimate. Required by the API.
    pub item_price_id: String,
    /// Plan the price belongs to.
    pub plan_id: Option<String>,
    /// Coupon to apply to the estimate.
    pub coupon_code: Option<String>,
}

impl SubscriptionEstimateParams {
    /// Parameters estimating the given price.
    pub fn new(item_price_id: impl Into<String>) -> Self {
        Self {
            item_price_id: item_price_id.into(),
            ..Default::default()
        }
    }

    fn to_query(&self) -> Vec<(&'static str, String)> {
        let mut q = vec![("item_price_id", self.item_price_id.clone())];
        if let Some(v) = &self.plan_id {
            q.push(("plan_id", v.clone()));
        }
        if let Some(v) = &self.coupon_code {
            q.push(("coupon_code", v.clone()));
        }
        q
    }
}

/// Body of [`Subscriptions::update_native_config`].
#[derive(Debug, Clone, Default, Serialize)]
pub struct NativeShopConfigRequest {
    /// Whether the shop enrolls card subscriptions natively.
    pub enabled: bool,
    /// The payment account new enrollments charge through.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub payment_connector_id: Option<String>,
    /// Whether enrollments run in the test environment.
    pub test_mode: bool,
    /// Any additional fields, merged verbatim.
    #[serde(flatten, skip_serializing_if = "serde_json::Map::is_empty")]
    pub extra: serde_json::Map<String, Value>,
}

impl NativeShopConfigRequest {
    /// Settings turning native enrollment on or off in one environment.
    pub fn new(enabled: bool, test_mode: bool) -> Self {
        Self {
            enabled,
            test_mode,
            ..Default::default()
        }
    }

    /// Select the payment account new enrollments charge through.
    #[must_use]
    pub fn payment_connector_id(mut self, payment_connector_id: impl Into<String>) -> Self {
        self.payment_connector_id = Some(payment_connector_id.into());
        self
    }
}

/// Names of `NativeShopConfigRequest`'s fields as they appear on the wire
/// (`extra` excluded).
const NATIVE_SHOP_CONFIG_REQUEST_NAMED: &[&str] = &["enabled", "payment_connector_id", "test_mode"];

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

/// Body of [`Subscriptions::update_native_dunning`].
#[derive(Debug, Clone, Default, Serialize)]
pub struct NativeDunningConfigRequest {
    /// Whether failed renewals are retried.
    pub enabled: bool,
    /// Retry days, as offsets from the first failed charge.
    pub retry_days: Vec<i32>,
    /// Charges per cycle, the opening attempt included (2 to 9).
    pub max_attempts: i32,
    /// Whether the subscription is cancelled once every attempt has failed.
    pub cancel_after_exhaustion: bool,
    /// What follows the failed off-session charges. Omitted keeps the stored
    /// mode.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub recovery_mode: Option<NativeRecoveryMode>,
    /// Off-session charges of a cycle before the buyer recovery link, the
    /// first renewal charge included (1 to `max_attempts`). Omitted keeps the
    /// stored value.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub recovery_after_attempt: Option<i32>,
    /// Any additional fields, merged verbatim.
    #[serde(flatten, skip_serializing_if = "serde_json::Map::is_empty")]
    pub extra: serde_json::Map<String, Value>,
}

impl NativeDunningConfigRequest {
    /// Recovery settings with the given schedule.
    pub fn new(
        enabled: bool,
        retry_days: Vec<i32>,
        max_attempts: i32,
        cancel_after_exhaustion: bool,
    ) -> Self {
        Self {
            enabled,
            retry_days,
            max_attempts,
            cancel_after_exhaustion,
            ..Default::default()
        }
    }

    /// Set what follows the failed off-session charges: `"off"` or
    /// `"buyer_link"`.
    #[must_use]
    pub fn recovery_mode(mut self, recovery_mode: impl Into<NativeRecoveryMode>) -> Self {
        self.recovery_mode = Some(recovery_mode.into());
        self
    }

    /// Set how many off-session charges of a cycle come before the buyer
    /// recovery link.
    #[must_use]
    pub fn recovery_after_attempt(mut self, recovery_after_attempt: i32) -> Self {
        self.recovery_after_attempt = Some(recovery_after_attempt);
        self
    }
}

/// Names of `NativeDunningConfigRequest`'s fields as they appear on the wire
/// (`extra` excluded).
const NATIVE_DUNNING_CONFIG_REQUEST_NAMED: &[&str] = &[
    "enabled",
    "retry_days",
    "max_attempts",
    "cancel_after_exhaustion",
    "recovery_mode",
    "recovery_after_attempt",
];

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

/// Body of [`Subscriptions::adopt`].
#[derive(Debug, Clone, Default, Serialize)]
pub struct AdoptSubscriptionRequest {
    /// The billing processor. Only `"creem"` is supported today.
    pub billing_processor: String,
    /// The billing account the subscription runs on.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub merchant_connector_id: Option<String>,
    /// The processor's own subscription ID.
    pub external_subscription_id: String,
    /// The existing DeloPay customer, checked against the processor's buyer.
    pub customer_id: String,
    /// The processor's ID for the buyer. Checked against the processor's
    /// buyer and stored as that customer's ID at the account.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub connector_customer_id: Option<String>,
    /// Must match the processor's product or price, when sent.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub item_price_id: Option<String>,
    /// The plan to record the subscription under.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub plan_id: Option<String>,
    /// Your own reference for the subscription.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub merchant_reference_id: Option<String>,
    /// The environment the subscription runs in at the processor (`true` =
    /// test). Omitted, the billing account's current mode is used. The mode
    /// used is fixed on the subscription, and repeating the adoption in the
    /// other mode is refused.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub test_mode: Option<bool>,
    /// Any additional fields, merged verbatim.
    #[serde(flatten, skip_serializing_if = "serde_json::Map::is_empty")]
    pub extra: serde_json::Map<String, Value>,
}

impl AdoptSubscriptionRequest {
    /// Adopt the processor's subscription `external_subscription_id` for the
    /// DeloPay customer `customer_id`.
    pub fn new(
        billing_processor: impl Into<String>,
        external_subscription_id: impl Into<String>,
        customer_id: impl Into<String>,
    ) -> Self {
        Self {
            billing_processor: billing_processor.into(),
            external_subscription_id: external_subscription_id.into(),
            customer_id: customer_id.into(),
            ..Default::default()
        }
    }

    /// Name the billing account the subscription runs on.
    #[must_use]
    pub fn merchant_connector_id(mut self, merchant_connector_id: impl Into<String>) -> Self {
        self.merchant_connector_id = Some(merchant_connector_id.into());
        self
    }

    /// Name the processor's ID for the buyer.
    #[must_use]
    pub fn connector_customer_id(mut self, connector_customer_id: impl Into<String>) -> Self {
        self.connector_customer_id = Some(connector_customer_id.into());
        self
    }

    /// Name the price the subscription must bill on.
    #[must_use]
    pub fn item_price_id(mut self, item_price_id: impl Into<String>) -> Self {
        self.item_price_id = Some(item_price_id.into());
        self
    }

    /// Set the plan to record the subscription under.
    #[must_use]
    pub fn plan_id(mut self, plan_id: impl Into<String>) -> Self {
        self.plan_id = Some(plan_id.into());
        self
    }

    /// Set your own reference for the subscription.
    #[must_use]
    pub fn merchant_reference_id(mut self, merchant_reference_id: impl Into<String>) -> Self {
        self.merchant_reference_id = Some(merchant_reference_id.into());
        self
    }

    /// Name the environment the subscription runs in at the processor
    /// (`true` = test).
    #[must_use]
    pub fn test_mode(mut self, test_mode: bool) -> Self {
        self.test_mode = Some(test_mode);
        self
    }
}

/// Names of `AdoptSubscriptionRequest`'s fields as they appear on the wire
/// (`extra` excluded).
const ADOPT_SUBSCRIPTION_REQUEST_NAMED: &[&str] = &[
    "billing_processor",
    "merchant_connector_id",
    "external_subscription_id",
    "customer_id",
    "connector_customer_id",
    "item_price_id",
    "plan_id",
    "merchant_reference_id",
    "test_mode",
];

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

/// Body of [`Subscriptions::sync`].
#[derive(Debug, Clone, Default, Serialize)]
pub struct SubscriptionSyncRequest {
    /// 1 to 50 subscriptions of the shop.
    pub subscription_ids: Vec<String>,
}

impl SubscriptionSyncRequest {
    /// Sync the given subscriptions.
    pub fn new(subscription_ids: Vec<String>) -> Self {
        Self { subscription_ids }
    }
}

/// Body of [`Subscriptions::import_preview`].
#[derive(Debug, Clone, Default, Serialize)]
pub struct SubscriptionImportPreviewRequest {
    /// The billing account whose subscriptions to list.
    pub merchant_connector_id: String,
}

impl SubscriptionImportPreviewRequest {
    /// List the subscriptions of the billing account `merchant_connector_id`.
    pub fn new(merchant_connector_id: impl Into<String>) -> Self {
        Self {
            merchant_connector_id: merchant_connector_id.into(),
        }
    }
}

/// One processor subscription to take over in
/// [`Subscriptions::import_apply`], and the DeloPay customer it belongs to.
#[derive(Debug, Clone, Default, Serialize)]
pub struct SubscriptionImportSelection {
    /// The processor's ID for the subscription.
    pub external_subscription_id: String,
    /// The DeloPay customer it belongs to.
    pub customer_id: String,
    /// The processor's ID for the buyer, when you name the customer for a
    /// `needs_customer` row. Checked against what the processor reports.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub connector_customer_id: Option<String>,
}

impl SubscriptionImportSelection {
    /// Take over `external_subscription_id` for the customer `customer_id`.
    pub fn new(
        external_subscription_id: impl Into<String>,
        customer_id: impl Into<String>,
    ) -> Self {
        Self {
            external_subscription_id: external_subscription_id.into(),
            customer_id: customer_id.into(),
            connector_customer_id: None,
        }
    }

    /// Name the processor's ID for the buyer.
    #[must_use]
    pub fn connector_customer_id(mut self, connector_customer_id: impl Into<String>) -> Self {
        self.connector_customer_id = Some(connector_customer_id.into());
        self
    }
}

/// Body of [`Subscriptions::import_apply`].
#[derive(Debug, Clone, Default, Serialize)]
pub struct SubscriptionImportApplyRequest {
    /// The billing account the subscriptions run on.
    pub merchant_connector_id: String,
    /// 1 to 25 selections.
    pub items: Vec<SubscriptionImportSelection>,
    /// Any additional fields, merged verbatim.
    #[serde(flatten, skip_serializing_if = "serde_json::Map::is_empty")]
    pub extra: serde_json::Map<String, Value>,
}

impl SubscriptionImportApplyRequest {
    /// Take over `items` from the billing account `merchant_connector_id`.
    pub fn new(
        merchant_connector_id: impl Into<String>,
        items: Vec<SubscriptionImportSelection>,
    ) -> Self {
        Self {
            merchant_connector_id: merchant_connector_id.into(),
            items,
            extra: serde_json::Map::new(),
        }
    }
}

/// Names of `SubscriptionImportApplyRequest`'s fields as they appear on the
/// wire (`extra` excluded).
const SUBSCRIPTION_IMPORT_APPLY_REQUEST_NAMED: &[&str] = &["merchant_connector_id", "items"];

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

/// Paging for [`Subscriptions::list_invoices`].
#[derive(Debug, Clone, Default)]
pub struct SubscriptionInvoiceListParams {
    /// Maximum cycles to return. The server clamps it to 100.
    pub limit: Option<i64>,
    /// Cycles to skip, counting from the newest.
    pub offset: Option<i64>,
}

impl SubscriptionInvoiceListParams {
    /// Empty paging: the server's defaults.
    pub fn new() -> Self {
        Self::default()
    }

    /// Return at most `limit` cycles.
    #[must_use]
    pub fn limit(mut self, limit: i64) -> Self {
        self.limit = Some(limit);
        self
    }

    /// Skip `offset` cycles, counting from the newest.
    #[must_use]
    pub fn offset(mut self, offset: i64) -> Self {
        self.offset = Some(offset);
        self
    }

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

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

    const SUB_JSON: &str = r#"{"id": "sub_1", "status": "active"}"#;
    const CONFIRM_JSON: &str = r#"{
        "id": "sub_1", "status": "pending",
        "redirect_url": "https://paypal.test/approve"
    }"#;

    fn create_and_confirm_request() -> CreateAndConfirmSubscriptionRequest {
        CreateAndConfirmSubscriptionRequest {
            item_price_id: Some("price_1".to_string()),
            customer_id: "cus_1".to_string(),
            payment_details: SubscriptionPaymentDetails {
                payment_method: Some("card".to_string()),
                ..Default::default()
            },
            ..Default::default()
        }
    }

    #[tokio::test]
    async fn lookup_payments_posts_the_batch_and_reports_only_matches() {
        let (client, mock) = client_with(vec![Step::ok(
            r#"{"links":[{"payment_id":"pay_1","subscription_id":"sub_1",
                "invoice_id":"inv_1","invoice_status":"paid"}]}"#,
        )]);
        let ids = vec!["pay_1".to_string(), "pay_2".to_string()];
        let out = client
            .subscriptions()
            .with_profile_id("pro_1")
            .lookup_payments(&ids)
            .await
            .unwrap();

        // Two asked about, one linked: the unmatched id is simply absent, not
        // an error and not a null entry.
        assert_eq!(out.links.len(), 1);
        assert_eq!(out.links[0].payment_id, "pay_1");
        assert_eq!(out.links[0].subscription_id, "sub_1");

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(
            seen[0].url,
            "https://api.test/subscriptions/payments/lookup"
        );
        assert_eq!(
            seen[0].body_json()["payment_ids"],
            json!(["pay_1", "pay_2"])
        );
        // Profile scoping is part of the question here: a `payment_id` is
        // only unique within a merchant.
        assert_eq!(seen[0].header("x-profile-id"), Some("pro_1"));
    }

    #[tokio::test]
    async fn lookup_payments_rejects_an_oversized_batch_before_the_wire() {
        let (client, mock) = client_with(vec![]);
        let ids: Vec<String> = (0..=PAYMENT_LOOKUP_MAX_IDS)
            .map(|n| format!("pay_{n}"))
            .collect();
        match client
            .subscriptions()
            .lookup_payments(&ids)
            .await
            .unwrap_err()
        {
            DelopayError::InvalidRequest(msg) => assert!(msg.contains("200"), "{msg}"),
            other => panic!("expected InvalidRequest, got {other:?}"),
        }
        // Never reached the wire, so the empty script is never hit.
        assert_eq!(mock.call_count(), 0);
    }

    #[tokio::test]
    async fn lookup_payments_accepts_a_batch_at_the_limit() {
        // The cap is inclusive: exactly 200 must go through, or the guard is
        // off by one in the direction that rejects valid pages.
        let (client, mock) = client_with(vec![Step::ok(r#"{"links":[]}"#)]);
        let ids: Vec<String> = (0..PAYMENT_LOOKUP_MAX_IDS)
            .map(|n| format!("pay_{n}"))
            .collect();
        client.subscriptions().lookup_payments(&ids).await.unwrap();
        assert_eq!(mock.call_count(), 1);
    }

    #[tokio::test]
    async fn sends_x_profile_id_header_when_scoped() {
        // The backend rejects unscoped subscription calls (IR_04); a mutation
        // dropping the header push makes this fail.
        let (client, mock) = client_with(vec![Step::ok(SUB_JSON)]);
        client
            .subscriptions()
            .with_profile_id("pro_1")
            .retrieve("sub_1")
            .await
            .unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].header("x-profile-id"), Some("pro_1"));
    }

    #[tokio::test]
    async fn omits_the_profile_header_when_unscoped() {
        // Companion to the test above: without it, an impl that always sent
        // some x-profile-id value would still pass.
        let (client, mock) = client_with(vec![Step::ok(SUB_JSON)]);
        client.subscriptions().retrieve("sub_1").await.unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].header("x-profile-id"), None);
    }

    #[tokio::test]
    async fn create_and_confirm_posts_to_subscriptions_root() {
        let (client, mock) = client_with(vec![Step::ok(CONFIRM_JSON)]);
        let out = client
            .subscriptions()
            .with_profile_id("pro_1")
            .create_and_confirm(&create_and_confirm_request())
            .await
            .unwrap();
        assert_eq!(
            out.redirect_url.as_deref(),
            Some("https://paypal.test/approve")
        );

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(seen[0].url, "https://api.test/subscriptions");
        let body = seen[0].body_json();
        assert_eq!(body["item_price_id"], "price_1");
        assert_eq!(body["payment_details"]["payment_method"], "card");
    }

    #[tokio::test]
    async fn update_puts_to_the_update_path() {
        let (client, mock) = client_with(vec![Step::ok(SUB_JSON)]);
        let req = UpdateSubscriptionRequest::for_price("price_2").plan_id("plan_2");
        client.subscriptions().update("sub_1", &req).await.unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "PUT");
        assert_eq!(seen[0].url, "https://api.test/subscriptions/sub_1/update");
        assert_eq!(
            seen[0].body_json(),
            json!({"plan_id": "plan_2", "item_price_id": "price_2"})
        );
    }

    #[tokio::test]
    async fn update_to_a_product_sends_only_the_product_price() {
        let (client, mock) = client_with(vec![Step::ok(SUB_JSON)]);
        let req = UpdateSubscriptionRequest::for_product("prod_1").price_id("prc_1");
        client.subscriptions().update("sub_1", &req).await.unwrap();
        assert_eq!(
            mock.seen.lock().unwrap()[0].body_json(),
            json!({"product_id": "prod_1", "price_id": "prc_1"})
        );
    }

    /// Exactly one price source. Mutation: drop the `(Some, Some)` arm of
    /// `check_price_source` — the first assertion fails.
    #[tokio::test]
    async fn a_bad_price_source_is_refused_before_sending() {
        let (client, mock) = client_with(vec![]);
        let subs = client.subscriptions();
        let both = UpdateSubscriptionRequest {
            item_price_id: Some("price_1".to_string()),
            product_id: Some("prod_1".to_string()),
            ..Default::default()
        };
        assert!(matches!(
            subs.update("sub_1", &both).await,
            Err(DelopayError::InvalidRequest(_))
        ));
        assert!(matches!(
            subs.update("sub_1", &UpdateSubscriptionRequest::default())
                .await,
            Err(DelopayError::InvalidRequest(_))
        ));
        let plan_with_product = UpdateSubscriptionRequest::for_product("prod_1").plan_id("plan_1");
        assert!(subs.update("sub_1", &plan_with_product).await.is_err());
        let price_without_product = CreateSubscriptionRequest {
            item_price_id: Some("price_1".to_string()),
            price_id: Some("prc_1".to_string()),
            ..Default::default()
        };
        assert!(subs.create(&price_without_product).await.is_err());
        let product_create = CreateAndConfirmSubscriptionRequest {
            item_price_id: None,
            product_id: Some("prod_1".to_string()),
            ..create_and_confirm_request()
        };
        assert!(product_create.validate().is_ok());
        assert_eq!(mock.call_count(), 0);
    }

    #[tokio::test]
    async fn pause_resume_cancel_send_an_empty_object_body_by_default() {
        // The backend rejects a bodyless POST on these endpoints
        // ("Unsupported content type"), so `None` params must still produce
        // a `{}` body — a mutation sending no body fails here.
        let (client, mock) = client_with(vec![
            Step::ok(r#"{"id":"sub_1","status":"paused"}"#),
            Step::ok(r#"{"id":"sub_1","status":"active"}"#),
            Step::ok(r#"{"id":"sub_1","status":"cancelled"}"#),
        ]);
        let subs = client.subscriptions();
        subs.pause("sub_1", None).await.unwrap();
        subs.resume("sub_1", None).await.unwrap();
        subs.cancel("sub_1", None).await.unwrap();

        let seen = mock.seen.lock().unwrap();
        let paths = [
            "https://api.test/subscriptions/sub_1/pause",
            "https://api.test/subscriptions/sub_1/resume",
            "https://api.test/subscriptions/sub_1/cancel",
        ];
        for (i, path) in paths.iter().enumerate() {
            assert_eq!(seen[i].url, *path);
            assert_eq!(
                seen[i].body_json(),
                json!({}),
                "call {i} must carry an empty JSON object body"
            );
        }
    }

    #[tokio::test]
    async fn cancel_serializes_scheduling_options() {
        let (client, mock) = client_with(vec![Step::ok(r#"{"id":"sub_1","status":"cancelled"}"#)]);
        let req = CancelSubscriptionRequest {
            cancel_option: Some("end_of_term".to_string()),
            cancel_reason_code: Some("too_expensive".to_string()),
            ..Default::default()
        };
        client
            .subscriptions()
            .cancel("sub_1", Some(&req))
            .await
            .unwrap();

        let seen = mock.seen.lock().unwrap();
        let body = seen[0].body_json();
        assert_eq!(body["cancel_option"], "end_of_term");
        assert_eq!(body["cancel_reason_code"], "too_expensive");
    }

    #[tokio::test]
    async fn read_endpoints_serialize_their_queries() {
        let (client, mock) = client_with(vec![
            Step::ok("[]"),
            Step::ok(r#"{"amount":999,"currency":"EUR","line_items":[]}"#),
            Step::ok("[]"),
        ]);
        let subs = client.subscriptions();
        subs.list(Some(&SubscriptionListParams {
            limit: Some(10),
            offset: Some(20),
            test_mode: None,
        }))
        .await
        .unwrap();
        subs.estimate(&SubscriptionEstimateParams::new("price_1"))
            .await
            .unwrap();
        subs.items(&SubscriptionItemsParams::new("plan"))
            .await
            .unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(
            seen[0].url,
            "https://api.test/subscriptions/list?limit=10&offset=20"
        );
        assert_eq!(
            seen[1].url,
            "https://api.test/subscriptions/estimate?item_price_id=price_1"
        );
        assert_eq!(
            seen[2].url,
            "https://api.test/subscriptions/items?item_type=plan"
        );
    }

    /// Drift guard for `CREATE_SUBSCRIPTION_REQUEST_NAMED`.
    #[test]
    fn create_request_named_fields_are_complete() {
        let req = CreateSubscriptionRequest {
            item_price_id: Some("price_1".to_string()),
            product_id: Some("prod_1".to_string()),
            price_id: Some("prc_1".to_string()),
            customer_id: "cus_1".to_string(),
            payment_details: CreateSubscriptionPaymentDetails {
                return_url: "https://example.com/r".to_string(),
                setup_future_usage: Some(SetupFutureUsage::OffSession),
                capture_method: Some(CaptureMethod::Automatic),
                authentication_type: Some(AuthenticationType::NoThreeDs),
                payment_type: Some("recurring".to_string()),
            },
            merchant_reference_id: Some("ref_1".to_string()),
            plan_id: Some("plan_1".to_string()),
            coupon_code: Some("SAVE10".to_string()),
            billing: Some(Address::default()),
            shipping: Some(Address::default()),
            extra: serde_json::Map::new(),
        };
        let value = serde_json::to_value(req).unwrap();
        for key in value.as_object().unwrap().keys() {
            assert!(
                CREATE_SUBSCRIPTION_REQUEST_NAMED.contains(&key.as_str()),
                "CREATE_SUBSCRIPTION_REQUEST_NAMED is missing wire key `{key}`"
            );
        }
    }

    /// Drift guard for `CREATE_AND_CONFIRM_SUBSCRIPTION_REQUEST_NAMED`.
    #[test]
    fn create_and_confirm_request_named_fields_are_complete() {
        let req = CreateAndConfirmSubscriptionRequest {
            product_id: Some("prod_1".to_string()),
            price_id: Some("prc_1".to_string()),
            plan_id: Some("plan_1".to_string()),
            coupon_code: Some("SAVE10".to_string()),
            billing: Some(Address::default()),
            shipping: Some(Address::default()),
            merchant_reference_id: Some("ref_1".to_string()),
            ..create_and_confirm_request()
        };
        let value = serde_json::to_value(req).unwrap();
        for key in value.as_object().unwrap().keys() {
            assert!(
                CREATE_AND_CONFIRM_SUBSCRIPTION_REQUEST_NAMED.contains(&key.as_str()),
                "CREATE_AND_CONFIRM_SUBSCRIPTION_REQUEST_NAMED is missing wire key `{key}`"
            );
        }
    }

    #[test]
    fn create_validate_rejects_colliding_extra_key() {
        let mut req = CreateSubscriptionRequest::default();
        req.extra.insert("customer_id".to_string(), json!("cus_2"));
        assert!(matches!(
            req.validate().unwrap_err(),
            DelopayError::InvalidRequest(_)
        ));
    }

    #[tokio::test]
    async fn native_config_gets_the_shop_settings() {
        let (client, mock) = client_with(vec![Step::ok(
            r#"{"enabled":true,"payment_connector_id":"mca_1","test_mode":false,
                "eligible_connectors":["stripe"],"surprise_field":1}"#,
        )]);
        let out = client
            .subscriptions()
            .with_profile_id("pro_1")
            .native_config()
            .await
            .unwrap();
        assert!(out.enabled);
        assert_eq!(out.payment_connector_id.as_deref(), Some("mca_1"));
        assert_eq!(out.eligible_connectors, ["stripe"]);
        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/subscriptions/native/config");
        assert_eq!(seen[0].header("x-profile-id"), Some("pro_1"));
    }

    #[tokio::test]
    async fn update_native_config_puts_the_settings() {
        let (client, mock) = client_with(vec![Step::ok(
            r#"{"enabled":true,"test_mode":true,"eligible_connectors":[]}"#,
        )]);
        let params = NativeShopConfigRequest::new(true, true).payment_connector_id("mca_1");
        let out = client
            .subscriptions()
            .with_profile_id("pro_1")
            .update_native_config(&params)
            .await
            .unwrap();
        assert!(out.test_mode);
        assert!(out.payment_connector_id.is_none());

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "PUT");
        assert_eq!(seen[0].url, "https://api.test/subscriptions/native/config");
        assert_eq!(
            seen[0].body_json(),
            json!({"enabled":true,"payment_connector_id":"mca_1","test_mode":true})
        );
        assert_eq!(seen[0].header("x-profile-id"), Some("pro_1"));
    }

    const DUNNING_JSON: &str = r#"{"enabled":true,"retry_days":[1,3,7],"max_attempts":4,
        "cancel_after_exhaustion":false,"recovery_mode":"buyer_link",
        "recovery_after_attempt":2,"surprise_field":"x"}"#;

    #[tokio::test]
    async fn native_dunning_gets_the_recovery_settings() {
        let (client, mock) = client_with(vec![Step::ok(DUNNING_JSON)]);
        let out = client.subscriptions().native_dunning().await.unwrap();
        assert_eq!(out.retry_days, [1, 3, 7]);
        assert_eq!(out.max_attempts, 4);
        assert_eq!(out.recovery_mode, "buyer_link");
        assert_eq!(out.recovery_after_attempt, 2);
        assert_eq!(out.extra["surprise_field"], "x");

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "GET");
        assert_eq!(seen[0].url, "https://api.test/subscriptions/native/dunning");
    }

    #[tokio::test]
    async fn update_native_dunning_puts_the_schedule_and_omits_unset_fields() {
        let (client, mock) = client_with(vec![Step::ok(DUNNING_JSON)]);
        let params = NativeDunningConfigRequest::new(true, vec![1, 3, 7], 4, false);
        client
            .subscriptions()
            .update_native_dunning(&params)
            .await
            .unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "PUT");
        assert_eq!(seen[0].url, "https://api.test/subscriptions/native/dunning");
        // Omitted keeps the stored value, so unset fields must not be sent
        // as `null`.
        assert_eq!(
            seen[0].body_json(),
            json!({"enabled":true,"retry_days":[1,3,7],"max_attempts":4,
                   "cancel_after_exhaustion":false})
        );
    }

    #[tokio::test]
    async fn capabilities_gets_the_encoded_subscription_path() {
        let (client, mock) = client_with(vec![Step::ok(
            r#"{"pause_immediately":true,"resume_immediately":true,
                "cancel_immediately":false,"cancel_at_period_end":true,
                "change_plan":false,"pause_voids_invoices":true,"surprise_field":1}"#,
        )]);
        let out = client
            .subscriptions()
            .with_profile_id("pro_1")
            .capabilities("sub/1")
            .await
            .unwrap();
        assert!(out.pause_immediately);
        assert!(!out.cancel_immediately);
        assert!(out.pause_voids_invoices);
        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/subscriptions/sub%2F1/capabilities"
        );
        assert_eq!(seen[0].header("x-profile-id"), Some("pro_1"));
    }

    const ADOPT_JSON: &str = r#"{"subscription_id":"sub_1","adopted":true,
        "billing_processor":"creem","external_subscription_id":"ext_1",
        "status":"active","customer_id":"cus_1","profile_id":"pro_1",
        "handoff_confirmed":false,"surprise_field":1}"#;

    #[tokio::test]
    async fn adopt_posts_the_adoption() {
        let (client, mock) = client_with(vec![Step::ok(ADOPT_JSON)]);
        let params =
            AdoptSubscriptionRequest::new("creem", "ext_1", "cus_1").item_price_id("price_1");
        let out = client
            .subscriptions()
            .with_profile_id("pro_1")
            .adopt(&params)
            .await
            .unwrap();
        assert_eq!(out.subscription_id, "sub_1");
        assert!(out.adopted);
        assert!(!out.handoff_confirmed);
        assert_eq!(out.billing_processor, "creem");
        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/subscriptions/adopt");
        assert_eq!(
            seen[0].body_json(),
            json!({"billing_processor":"creem","external_subscription_id":"ext_1",
                   "customer_id":"cus_1","item_price_id":"price_1"})
        );
        assert_eq!(seen[0].header("x-profile-id"), Some("pro_1"));
        assert!(!seen[0].had_idempotency_key());
    }

    #[tokio::test]
    async fn adopt_sends_the_environment_it_is_given() {
        for test_mode in [true, false] {
            let (client, mock) = client_with(vec![Step::ok(ADOPT_JSON)]);
            let params =
                AdoptSubscriptionRequest::new("creem", "ext_1", "cus_1").test_mode(test_mode);
            client.subscriptions().adopt(&params).await.unwrap();
            assert_eq!(
                mock.seen.lock().unwrap()[0].body_json(),
                json!({"billing_processor":"creem","external_subscription_id":"ext_1",
                       "customer_id":"cus_1","test_mode":test_mode})
            );
        }
    }

    #[tokio::test]
    async fn adopt_ignores_a_client_wide_key_and_is_not_replayed() {
        // Adoption is not deduplicated by the API, so a client-wide key must
        // not reach it. Mutation: route `adopt` through `send` again — the
        // header appears and the request count becomes 2.
        let (client, mock) = client_with_retries(
            vec![
                Step::status(503, r#"{"error":{"message":"down"}}"#),
                Step::ok(ADOPT_JSON),
            ],
            2,
        );
        let params = AdoptSubscriptionRequest::new("creem", "ext_1", "cus_1");
        assert!(
            client
                .with_idempotency_key("client-key")
                .subscriptions()
                .adopt(&params)
                .await
                .is_err()
        );
        assert_eq!(mock.call_count(), 1);
        assert!(!mock.seen.lock().unwrap()[0].had_idempotency_key());
    }

    #[tokio::test]
    async fn adopt_is_not_replayed_on_a_server_error() {
        // A POST without an idempotency key may already have been acted on.
        let (client, mock) = client_with_retries(vec![Step::status(500, "{}")], 2);
        let params = AdoptSubscriptionRequest::new("creem", "ext_1", "cus_1");
        assert!(client.subscriptions().adopt(&params).await.is_err());
        assert_eq!(mock.call_count(), 1);
    }

    #[tokio::test]
    async fn sync_posts_the_ids_and_decodes_each_result() {
        let (client, mock) = client_with(vec![Step::ok(
            r#"{"results":[{"subscription_id":"sub_1","outcome":"updated",
                "status":"active","provider":{"billing_processor_subscription_id":"ext_1",
                "status":"active","read_at":"2026-01-01T00:00:00Z","surprise_field":2}},
                {"subscription_id":"sub_2","outcome":"not_found"}],"surprise_field":1}"#,
        )]);
        let params = SubscriptionSyncRequest::new(vec!["sub_1".into(), "sub_2".into()]);
        let out = client
            .subscriptions()
            .with_profile_id("pro_1")
            .sync(&params)
            .await
            .unwrap();
        assert_eq!(out.results.len(), 2);
        assert_eq!(out.results[0].outcome, "updated");
        let provider = out.results[0].provider.as_ref().unwrap();
        assert_eq!(provider.billing_processor_subscription_id, "ext_1");
        assert_eq!(provider.extra["surprise_field"], 2);
        assert!(out.results[1].provider.is_none());
        assert_eq!(out.extra["surprise_field"], 1);

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(seen[0].url, "https://api.test/subscriptions/sync");
        assert_eq!(
            seen[0].body_json(),
            json!({"subscription_ids":["sub_1","sub_2"]})
        );
        assert_eq!(seen[0].header("x-profile-id"), Some("pro_1"));
    }

    #[tokio::test]
    async fn sync_one_posts_to_the_encoded_subscription_without_a_body() {
        let (client, mock) = client_with(vec![Step::ok(
            r#"{"subscription_id":"sub/1","outcome":"unchanged","status":"active",
                "surprise_field":1}"#,
        )]);
        let out = client
            .subscriptions()
            .with_profile_id("pro_1")
            .sync_one("sub/1")
            .await
            .unwrap();
        assert_eq!(out.outcome, "unchanged");
        assert_eq!(out.status.as_deref(), Some("active"));
        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/subscriptions/sub%2F1/sync");
        assert!(seen[0].body.is_none());
        assert_eq!(seen[0].header("x-profile-id"), Some("pro_1"));
    }

    #[tokio::test]
    async fn import_preview_posts_the_billing_account() {
        let (client, mock) = client_with(vec![Step::ok(
            r#"{"capabilities":{"connector":"creem","listing":true,"adoption":true},
                "counts":{"new":1,"needs_customer":0,"held":0,"ended":0,"not_adoptable":0},
                "truncated":false,
                "items":[{"external_subscription_id":"ext_1","provider_status":"active",
                    "status":"active","customer_email":"buyer@example.com",
                    "classification":"new","customer_id":"cus_1"}],
                "surprise_field":1}"#,
        )]);
        let params = SubscriptionImportPreviewRequest::new("mca_1");
        let out = client
            .subscriptions()
            .with_profile_id("pro_1")
            .import_preview(&params)
            .await
            .unwrap();
        assert!(out.capabilities.listing);
        assert_eq!(out.counts.new, 1);
        assert_eq!(out.items[0].classification, "new");
        assert_eq!(out.extra["surprise_field"], 1);
        // The buyer's email never reaches Debug output.
        let debug = format!("{:?}", out.items[0]);
        assert!(!debug.contains("buyer@example.com"), "{debug}");

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(seen[0].url, "https://api.test/subscriptions/import/preview");
        assert_eq!(
            seen[0].body_json(),
            json!({"merchant_connector_id":"mca_1"})
        );
        assert_eq!(seen[0].header("x-profile-id"), Some("pro_1"));
    }

    #[tokio::test]
    async fn import_apply_posts_the_selections() {
        let (client, mock) = client_with(vec![Step::ok(
            r#"{"results":[{"external_subscription_id":"ext_1","outcome":"adopted",
                "subscription_id":"sub_1"},{"external_subscription_id":"ext_2",
                "outcome":"failed","reason":"refused","reason_code":"adoption_refused"}],
                "surprise_field":1}"#,
        )]);
        let params = SubscriptionImportApplyRequest::new(
            "mca_1",
            vec![
                SubscriptionImportSelection::new("ext_1", "cus_1"),
                SubscriptionImportSelection::new("ext_2", "cus_2").connector_customer_id("cc_2"),
            ],
        );
        let out = client
            .subscriptions()
            .with_profile_id("pro_1")
            .import_apply(&params)
            .await
            .unwrap();
        assert_eq!(out.results[0].subscription_id.as_deref(), Some("sub_1"));
        assert_eq!(
            out.results[1].reason_code.as_deref(),
            Some("adoption_refused")
        );
        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/subscriptions/import/apply");
        assert_eq!(
            seen[0].body_json(),
            json!({"merchant_connector_id":"mca_1","items":[
                {"external_subscription_id":"ext_1","customer_id":"cus_1"},
                {"external_subscription_id":"ext_2","customer_id":"cus_2",
                 "connector_customer_id":"cc_2"}]})
        );
        assert_eq!(seen[0].header("x-profile-id"), Some("pro_1"));
    }

    #[tokio::test]
    async fn list_invoices_gets_the_encoded_path_with_paging() {
        let (client, mock) = client_with(vec![Step::ok(
            r#"{"invoices":[{"id":"inv_1","subscription_id":"sub_1","amount":1000,
                "currency":"EUR","status":"paid"}],"surprise_field":1}"#,
        )]);
        let params = SubscriptionInvoiceListParams::new().limit(10).offset(20);
        let out = client
            .subscriptions()
            .with_profile_id("pro_1")
            .list_invoices("sub/1", Some(&params))
            .await
            .unwrap();
        assert_eq!(out.invoices[0].id, "inv_1");
        assert_eq!(out.invoices[0].amount, 1000);
        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/subscriptions/sub%2F1/invoices?limit=10&offset=20"
        );
        assert_eq!(seen[0].header("x-profile-id"), Some("pro_1"));
    }

    #[tokio::test]
    async fn billing_processor_gets_the_shop_processor() {
        let (client, mock) = client_with(vec![Step::ok(
            r#"{"merchant_connector_id":"mca_1","connector_name":"paypal","surprise_field":1}"#,
        )]);
        let out = client
            .subscriptions()
            .with_profile_id("pro_1")
            .billing_processor()
            .await
            .unwrap();
        assert_eq!(out.merchant_connector_id, "mca_1");
        assert_eq!(out.connector_name, "paypal");
        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/subscriptions/billing_processor"
        );
        assert_eq!(seen[0].header("x-profile-id"), Some("pro_1"));
    }

    /// Drift guard for `NATIVE_SHOP_CONFIG_REQUEST_NAMED`.
    #[test]
    fn native_shop_config_request_named_fields_are_complete() {
        let req = NativeShopConfigRequest::new(true, false).payment_connector_id("mca_1");
        let value = serde_json::to_value(req).unwrap();
        for key in value.as_object().unwrap().keys() {
            assert!(
                NATIVE_SHOP_CONFIG_REQUEST_NAMED.contains(&key.as_str()),
                "NATIVE_SHOP_CONFIG_REQUEST_NAMED is missing wire key `{key}`"
            );
        }
    }

    /// Drift guard for `NATIVE_DUNNING_CONFIG_REQUEST_NAMED`.
    #[test]
    fn native_dunning_config_request_named_fields_are_complete() {
        let req = NativeDunningConfigRequest::new(true, vec![1], 2, true)
            .recovery_mode("buyer_link")
            .recovery_after_attempt(1);
        let value = serde_json::to_value(req).unwrap();
        for key in value.as_object().unwrap().keys() {
            assert!(
                NATIVE_DUNNING_CONFIG_REQUEST_NAMED.contains(&key.as_str()),
                "NATIVE_DUNNING_CONFIG_REQUEST_NAMED is missing wire key `{key}`"
            );
        }
    }

    /// Drift guard for `ADOPT_SUBSCRIPTION_REQUEST_NAMED`.
    #[test]
    fn adopt_subscription_request_named_fields_are_complete() {
        let req = AdoptSubscriptionRequest::new("creem", "ext_1", "cus_1")
            .merchant_connector_id("mca_1")
            .connector_customer_id("cc_1")
            .item_price_id("price_1")
            .plan_id("plan_1")
            .merchant_reference_id("ref_1")
            .test_mode(true);
        let value = serde_json::to_value(req).unwrap();
        for key in value.as_object().unwrap().keys() {
            assert!(
                ADOPT_SUBSCRIPTION_REQUEST_NAMED.contains(&key.as_str()),
                "ADOPT_SUBSCRIPTION_REQUEST_NAMED is missing wire key `{key}`"
            );
        }
    }

    /// Drift guard for `SUBSCRIPTION_IMPORT_APPLY_REQUEST_NAMED`.
    #[test]
    fn subscription_import_apply_request_named_fields_are_complete() {
        let req = SubscriptionImportApplyRequest::new(
            "mca_1",
            vec![SubscriptionImportSelection::new("ext_1", "cus_1")],
        );
        let value = serde_json::to_value(req).unwrap();
        for key in value.as_object().unwrap().keys() {
            assert!(
                SUBSCRIPTION_IMPORT_APPLY_REQUEST_NAMED.contains(&key.as_str()),
                "SUBSCRIPTION_IMPORT_APPLY_REQUEST_NAMED is missing wire key `{key}`"
            );
        }
    }

    #[test]
    fn adopt_validate_rejects_colliding_extra_key() {
        let mut req = AdoptSubscriptionRequest::new("creem", "ext_1", "cus_1");
        req.extra.insert("customer_id".to_string(), json!("cus_2"));
        match req.validate().unwrap_err() {
            DelopayError::InvalidRequest(msg) => assert!(msg.contains("customer_id")),
            other => panic!("expected InvalidRequest, got {other:?}"),
        }
    }
}