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
//! The [`Delopay`] client and its HTTP core.

use std::sync::Arc;
use std::time::Duration;

use serde::de::DeserializeOwned;

use crate::core::credentials::SecretKey;
use crate::core::error::{DelopayError, Result};
use crate::http::hyper_backend::HyperTransport;
use crate::http::proxy::ProxyMode;
use crate::http::retry::{backoff, parse_retry_after};
use crate::http::transport::{HttpMethod, RawRequest, Transport, TransportErrorKind};
use crate::resources::api_keys::ApiKeys;
use crate::resources::audit::Audit;
use crate::resources::authentication::Authentication;
use crate::resources::availability_overrides::AvailabilityOverrides;
use crate::resources::billing::Billing;
use crate::resources::buyer_account::BuyerAccount;
use crate::resources::buyer_blocklist::BuyerBlocklist;
use crate::resources::buyer_conversations::BuyerConversations;
use crate::resources::buyer_evidence_reviews::BuyerEvidenceReviews;
use crate::resources::buyer_portal::BuyerPortal;
use crate::resources::chargeback_prevention::ChargebackPrevention;
use crate::resources::checkout_methods::CheckoutMethods;
use crate::resources::checkout_recovery::CheckoutRecovery;
use crate::resources::checkout_templates::CheckoutTemplates;
use crate::resources::connectors::Connectors;
use crate::resources::cost_rules::CostRules;
use crate::resources::customers::Customers;
use crate::resources::deployment_branding::DeploymentBranding;
use crate::resources::disputes::Disputes;
use crate::resources::ephemeral_keys::EphemeralKeys;
use crate::resources::events::Events;
use crate::resources::export::Export;
use crate::resources::external_records::ExternalRecords;
use crate::resources::fees::Fees;
use crate::resources::identity_verifications::IdentityVerifications;
use crate::resources::invoice_settings::InvoiceSettings;
use crate::resources::invoices::Invoices;
use crate::resources::live::Live;
use crate::resources::mandates::Mandates;
use crate::resources::merchant_accounts::MerchantAccounts;
use crate::resources::message_templates::MessageTemplates;
use crate::resources::operation_limits::OperationLimits;
use crate::resources::payment_links::PaymentLinks;
use crate::resources::payment_methods::PaymentMethods;
use crate::resources::payments::Payments;
use crate::resources::payouts::Payouts;
use crate::resources::paypal_disputes::PaypalDisputes;
use crate::resources::poll::Poll;
use crate::resources::processor_costs::ProcessorCosts;
use crate::resources::processor_imports::ProcessorImports;
use crate::resources::products::Products;
use crate::resources::profile_acquirers::ProfileAcquirers;
use crate::resources::profiles::Profiles;
use crate::resources::projects::Projects;
use crate::resources::refunds::Refunds;
use crate::resources::regions::Regions;
use crate::resources::relay::Relay;
use crate::resources::risk::Risk;
use crate::resources::routing::Routing;
use crate::resources::sell_to_restrictions::SellToRestrictions;
use crate::resources::settings::Settings;
use crate::resources::settlement::Settlement;
use crate::resources::shop_labels::ShopLabels;
use crate::resources::shops::Shops;
use crate::resources::stripe_connect::StripeConnect;
use crate::resources::subscriptions::Subscriptions;
use crate::resources::three_ds_rules::ThreeDsRules;
use crate::resources::users::Users;
use crate::resources::verification::Verification;
use crate::resources::whop_resolution_cases::WhopResolutionCases;
use crate::{PRODUCTION_URL, SANDBOX_URL};

const DEFAULT_TIMEOUT: Duration = Duration::from_secs(30);
const DEFAULT_MAX_RETRIES: u32 = 2;

/// The DeloPay API client.
///
/// Construct once with your secret API key and reuse it — it holds a pooled
/// HTTP client internally and is cheap to [`clone`](Clone).
///
/// ```no_run
/// use delopay::Delopay;
/// let client = Delopay::new("prd_your_secret_key");        // production
/// let sandbox = Delopay::sandbox("snd_your_secret_key");   // sandbox
/// ```
#[derive(Debug, Clone)]
pub struct Delopay {
    pub(crate) inner: Arc<Inner>,
}

/// One thing worth logging, handed to a [`DelopayLogger`].
///
/// The `url` on every variant is `base_url + path` **without** the query
/// string. Query *values* carry customer-identifying data (`customer_id`) and
/// sometimes secrets (`client_secret`, `ephemeral_key`), so only the parameter
/// names are exposed, via `query_keys` on [`LogEvent::Request`]. Headers,
/// bodies and the API key are never passed to a logger.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum LogEvent<'a> {
    /// About to put a request on the wire.
    Request {
        /// HTTP verb.
        method: &'a str,
        /// Target URL, query string excluded.
        url: &'a str,
        /// Names (not values) of the query parameters being sent.
        query_keys: &'a [&'a str],
    },
    /// A response was received — including error statuses.
    Response {
        /// HTTP verb.
        method: &'a str,
        /// Target URL, query string excluded.
        url: &'a str,
        /// HTTP status code.
        status: u16,
        /// The `x-request-id` response header, when present. Quote this to
        /// DeloPay support.
        request_id: Option<&'a str>,
    },
    /// A transient failure is about to be retried.
    Retry {
        /// HTTP verb.
        method: &'a str,
        /// Target URL, query string excluded.
        url: &'a str,
        /// Which retry this is, 1-based.
        attempt: u32,
        /// The configured ceiling, from [`DelopayBuilder::max_retries`].
        max_retries: u32,
        /// How long the client will sleep before re-sending.
        delay_ms: u64,
    },
}

/// A sink for [`LogEvent`]s, installed with [`DelopayBuilder::logger`].
///
/// Called synchronously on the request path, so it must not block: hand the
/// event to `tracing`, `log`, or a channel and return.
pub type DelopayLogger = Arc<dyn Fn(LogEvent<'_>) + Send + Sync>;

/// Whether a request may fall back to the client-wide idempotency key.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum KeyPolicy {
    /// The ordinary path: a per-call key wins, else the client default.
    ClientDefaultApplies,
    /// The route deduplicates on a key in the body, so only that key may be
    /// sent — never the client default, which the body would not carry.
    BodyKeyOnly,
}

pub(crate) struct Inner {
    transport: Arc<dyn Transport>,
    base_url: String,
    checkout_base_url: String,
    api_key: String,
    /// A dashboard session token. When set it **replaces** the API key:
    /// requests carry `Authorization: Bearer <jwt>` and no `api-key`, because
    /// a route authenticated by a bearer token must not also present a key.
    jwt: Option<String>,
    max_retries: u32,
    logger: Option<DelopayLogger>,
    /// Applied to every non-GET request that does not carry its own key. Set
    /// through [`Delopay::with_idempotency_key`], never through the builder —
    /// a key is meant to identify one logical operation, not a whole client.
    default_idempotency_key: Option<String>,
}

// Hand-written rather than derived: `api_key` is deliberately omitted so a
// secret key cannot leak into logs via `{:?}` on a `Delopay`.
impl std::fmt::Debug for Inner {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Inner")
            .field("base_url", &self.base_url)
            .field("checkout_base_url", &self.checkout_base_url)
            .field("max_retries", &self.max_retries)
            // A closure has no useful `Debug`; print only whether one is set.
            // `default_idempotency_key` is a caller-chosen token, not a
            // credential, but it is omitted anyway to keep this output stable.
            .field("logger", &self.logger.is_some())
            .finish_non_exhaustive()
    }
}

impl Delopay {
    /// Create a production client with the given secret API key (`prd_...`).
    ///
    /// `&str` and `String` convert into [`SecretKey`] freely, so the usual
    /// call is unchanged. What the typed parameter rules out is passing a
    /// [`crate::credentials::PublishableKey`] or a
    /// [`crate::credentials::ClientSecret`] here — those authenticate the
    /// buyer-side surface and belong to [`crate::CheckoutSession`].
    pub fn new(api_key: impl Into<SecretKey>) -> Self {
        Self::builder(api_key).build()
    }

    /// Create a sandbox client with the given sandbox API key (`snd_...`).
    pub fn sandbox(api_key: impl Into<SecretKey>) -> Self {
        Self::builder(api_key).sandbox(true).build()
    }

    /// Start building a client with custom options.
    pub fn builder(api_key: impl Into<SecretKey>) -> DelopayBuilder {
        DelopayBuilder::new(api_key)
    }

    /// A clone of this client authenticating with a **dashboard session
    /// token** instead of its API key.
    ///
    /// The token replaces the key: requests carry
    /// `Authorization: Bearer <token>` and no `api-key`. Sending both would
    /// leave which credential the server honoured up to the server.
    ///
    /// This is what the JWT-only surfaces need — the merchant's own audit log,
    /// the user and session routes, the manual webhook trigger, the settlement
    /// aggregates. An API key cannot read them: they name people, and an API
    /// key names no one.
    ///
    /// ```no_run
    /// # use delopay::Delopay;
    /// # async fn run(client: &Delopay, token: &str) -> delopay::Result<()> {
    /// let log = client.with_jwt(token).audit().list(None).await?;
    /// # let _ = log;
    /// # Ok(())
    /// # }
    /// ```
    pub fn with_jwt(&self, token: impl Into<String>) -> Self {
        Self {
            inner: Arc::new(self.inner.clone_with_jwt(Some(token.into()))),
        }
    }

    /// The resolved API base URL used for all requests.
    pub fn base_url(&self) -> &str {
        &self.inner.base_url
    }

    /// A clone of this client that sends `key` as the `Idempotency-Key` header
    /// on every non-`GET` request that does not already carry one.
    ///
    /// An idempotency key identifies **one** logical operation: the server
    /// replays the first response for a repeated key. So scope this to a single
    /// call rather than holding the returned client for a batch of unrelated
    /// requests, which would make the second and later ones return the first
    /// one's result.
    ///
    /// ```no_run
    /// # use delopay::Delopay;
    /// # async fn run(client: &Delopay, order_id: &str) -> delopay::Result<()> {
    /// let refund = client
    ///     .with_idempotency_key(format!("refund-{order_id}"))
    ///     .refunds()
    ///     .create(&delopay::RefundCreateRequest::new("pay_123"))
    ///     .await?;
    /// # let _ = refund;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// Carrying a key also makes a `POST` retriable on 5xx and network errors —
    /// the retry policy treats it as idempotent, which is exactly why a blind
    /// `POST` is not retried.
    pub fn with_idempotency_key(&self, key: impl Into<String>) -> Self {
        Self {
            inner: Arc::new(self.inner.clone_with_idempotency_key(Some(key.into()))),
        }
    }

    /// The `payments` resource.
    pub fn payments(&self) -> Payments {
        Payments::new(self.inner.clone())
    }

    /// The `refunds` resource.
    pub fn refunds(&self) -> Refunds {
        Refunds::new(self.inner.clone())
    }

    /// The `customers` resource.
    pub fn customers(&self) -> Customers {
        Customers::new(self.inner.clone())
    }

    /// The `payment_methods` resource.
    pub fn payment_methods(&self) -> PaymentMethods {
        PaymentMethods::new(self.inner.clone())
    }

    /// The `payouts` resource.
    pub fn payouts(&self) -> Payouts {
        Payouts::new(self.inner.clone())
    }

    /// The `disputes` resource.
    pub fn disputes(&self) -> Disputes {
        Disputes::new(self.inner.clone())
    }

    /// The `paypal_disputes` resource: PayPal seller cases, including the ones
    /// raised against sales this platform never processed.
    pub fn paypal_disputes(&self) -> PaypalDisputes {
        PaypalDisputes::new(self.inner.clone())
    }

    /// The `mandates` resource.
    pub fn mandates(&self) -> Mandates {
        Mandates::new(self.inner.clone())
    }

    /// The `events` resource.
    pub fn events(&self) -> Events {
        Events::new(self.inner.clone())
    }

    /// The `payment_links` resource.
    pub fn payment_links(&self) -> PaymentLinks {
        PaymentLinks::new(self.inner.clone())
    }

    /// The `ephemeral_keys` resource.
    pub fn ephemeral_keys(&self) -> EphemeralKeys {
        EphemeralKeys::new(self.inner.clone())
    }

    /// The `poll` resource.
    pub fn poll(&self) -> Poll {
        Poll::new(self.inner.clone())
    }

    /// The `subscriptions` resource. Subscription endpoints are
    /// profile-scoped — chain
    /// [`with_profile_id`](Subscriptions::with_profile_id) to set the shop.
    pub fn subscriptions(&self) -> Subscriptions {
        Subscriptions::new(self.inner.clone())
    }

    /// The `export` resource.
    pub fn export(&self) -> Export {
        Export::new(self.inner.clone())
    }

    /// The `connectors` resource: the payment processors wired to an account.
    pub fn connectors(&self) -> Connectors {
        Connectors::new(self.inner.clone())
    }

    /// The `merchant_accounts` resource.
    pub fn merchant_accounts(&self) -> MerchantAccounts {
        MerchantAccounts::new(self.inner.clone())
    }

    /// The `profiles` resource: business profiles (shops) under an account.
    pub fn profiles(&self) -> Profiles {
        Profiles::new(self.inner.clone())
    }

    /// The `profile_acquirers` resource.
    pub fn profile_acquirers(&self) -> ProfileAcquirers {
        ProfileAcquirers::new(self.inner.clone())
    }

    /// The `routing` resource: routing algorithms, surcharge rules and
    /// checkout theme rules.
    pub fn routing(&self) -> Routing {
        Routing::new(self.inner.clone())
    }

    /// The `three_ds_rules` resource.
    pub fn three_ds_rules(&self) -> ThreeDsRules {
        ThreeDsRules::new(self.inner.clone())
    }

    /// The `api_keys` resource.
    pub fn api_keys(&self) -> ApiKeys {
        ApiKeys::new(self.inner.clone())
    }

    /// The `authentication` resource: the standalone 3DS authentication flow.
    pub fn authentication(&self) -> Authentication {
        Authentication::new(self.inner.clone())
    }

    /// The `billing` resource. Allocations are reached via
    /// [`Billing::allocations`].
    pub fn billing(&self) -> Billing {
        Billing::new(self.inner.clone())
    }

    /// The `fees` resource: merchant-scoped fee schedules.
    pub fn fees(&self) -> Fees {
        Fees::new(self.inner.clone())
    }

    /// The `shops` resource. Gateway connections are reached via
    /// [`Shops::gateways`].
    pub fn shops(&self) -> Shops {
        Shops::new(self.inner.clone())
    }

    /// The `shop_labels` resource: the merchant's own tags for grouping
    /// shops.
    pub fn shop_labels(&self) -> ShopLabels {
        ShopLabels::new(self.inner.clone())
    }

    /// The `projects` resource.
    pub fn projects(&self) -> Projects {
        Projects::new(self.inner.clone())
    }

    /// The `regions` resource.
    pub fn regions(&self) -> Regions {
        Regions::new(self.inner.clone())
    }

    /// The `users` resource: sign-in, 2FA, team members and roles.
    pub fn users(&self) -> Users {
        Users::new(self.inner.clone())
    }

    /// The `relay` resource.
    pub fn relay(&self) -> Relay {
        Relay::new(self.inner.clone())
    }

    /// The `verification` resource: Apple Pay domain registration.
    pub fn verification(&self) -> Verification {
        Verification::new(self.inner.clone())
    }

    /// The `stripe_connect` resource: Stripe connector onboarding.
    pub fn stripe_connect(&self) -> StripeConnect {
        StripeConnect::new(self.inner.clone())
    }

    /// The `settlement` resource — hosted-shop statements and payouts.
    pub fn settlement(&self) -> Settlement {
        Settlement::new(self.inner.clone())
    }

    /// The `operation_limits` resource — the caller's usage against the
    /// per-operation spending caps.
    pub fn operation_limits(&self) -> OperationLimits {
        OperationLimits::new(self.inner.clone())
    }

    /// The `settings` resource: the settings of the merchant, its projects
    /// and its shops.
    pub fn settings(&self) -> Settings {
        Settings::new(self.inner.clone())
    }

    /// The `live` resource: the record versions a dashboard editor sends in
    /// `If-Match`.
    pub fn live(&self) -> Live {
        Live::new(self.inner.clone())
    }

    /// The `deployment_branding` resource: the deployment's name, logos and
    /// default checkout colours.
    pub fn deployment_branding(&self) -> DeploymentBranding {
        DeploymentBranding::new(self.inner.clone())
    }

    /// The `checkout_methods` resource: a shop's payment-method layout for
    /// the hosted checkout.
    pub fn checkout_methods(&self) -> CheckoutMethods {
        CheckoutMethods::new(self.inner.clone())
    }

    /// The `checkout_recovery` resource: reminder emails for unfinished
    /// checkouts, and checkout reactivation.
    pub fn checkout_recovery(&self) -> CheckoutRecovery {
        CheckoutRecovery::new(self.inner.clone())
    }

    /// The `checkout_templates` resource: payment methods, behaviour and
    /// routing shared by many shops.
    pub fn checkout_templates(&self) -> CheckoutTemplates {
        CheckoutTemplates::new(self.inner.clone())
    }

    /// The `availability_overrides` resource.
    pub fn availability_overrides(&self) -> AvailabilityOverrides {
        AvailabilityOverrides::new(self.inner.clone())
    }

    /// The `products` resource: a shop's product catalogue. Every method
    /// takes the shop's `profile_id`.
    pub fn products(&self) -> Products {
        Products::new(self.inner.clone())
    }

    /// The `invoices` resource: the invoices and credit notes a merchant
    /// issues to their buyers.
    pub fn invoices(&self) -> Invoices {
        Invoices::new(self.inner.clone())
    }

    /// The `invoice_settings` resource: how invoices look and are taxed, at
    /// the merchant default and per shop.
    pub fn invoice_settings(&self) -> InvoiceSettings {
        InvoiceSettings::new(self.inner.clone())
    }

    /// The `processor_costs` resource: the merchant's own processor cost
    /// schedules.
    pub fn processor_costs(&self) -> ProcessorCosts {
        ProcessorCosts::new(self.inner.clone())
    }

    /// The `cost_rules` resource: the merchant's cost of goods and
    /// partner-share rules.
    pub fn cost_rules(&self) -> CostRules {
        CostRules::new(self.inner.clone())
    }

    /// The `audit` resource — the merchant's own audit log.
    ///
    /// Needs a dashboard JWT whose role holds the `AuditLog` permission; an
    /// API key cannot read it, because the log names people and an API key
    /// names no one.
    pub fn audit(&self) -> Audit {
        Audit::new(self.inner.clone())
    }

    /// The `buyer_portal` resource: the shop's customer portal, as the buyer
    /// reaches it.
    ///
    /// Build this client with the buyer's **customer portal grant** as its
    /// key (`Delopay::new(grant)`); the grant travels in the `api-key` header
    /// and decides who the buyer is.
    pub fn buyer_portal(&self) -> BuyerPortal {
        BuyerPortal::new(self.inner.clone())
    }

    /// The `buyer_account` resource: a buyer's sign-in and their purchases
    /// across shops.
    ///
    /// Starting and completing a sign-in need no credential (`Delopay::new("")`
    /// sends none). Everything after it needs a client built with the buyer
    /// account session `token` as its key.
    pub fn buyer_account(&self) -> BuyerAccount {
        BuyerAccount::new(self.inner.clone())
    }

    /// The `buyer_conversations` resource: the team's inbox of conversations
    /// with buyers.
    ///
    /// Needs a dashboard JWT: chain [`with_jwt`](Self::with_jwt).
    pub fn buyer_conversations(&self) -> BuyerConversations {
        BuyerConversations::new(self.inner.clone())
    }

    /// The `message_templates` resource: a shop's own texts of the emails it
    /// sends its buyers.
    ///
    /// Needs a dashboard JWT: chain [`with_jwt`](Self::with_jwt).
    pub fn message_templates(&self) -> MessageTemplates {
        MessageTemplates::new(self.inner.clone())
    }

    /// The `buyer_blocklist` resource — the buyers the merchant refuses to
    /// sell to again, and their Stripe Radar sync. Needs a dashboard JWT.
    pub fn buyer_blocklist(&self) -> BuyerBlocklist {
        BuyerBlocklist::new(self.inner.clone())
    }

    /// The `buyer_evidence_reviews` resource — the evidence buyers hand in for
    /// the shop's cases. Needs a dashboard JWT.
    pub fn buyer_evidence_reviews(&self) -> BuyerEvidenceReviews {
        BuyerEvidenceReviews::new(self.inner.clone())
    }

    /// The `external_records` resource — out-of-band transitions a payment
    /// provider made. Needs a dashboard JWT.
    pub fn external_records(&self) -> ExternalRecords {
        ExternalRecords::new(self.inner.clone())
    }

    /// The `identity_verifications` resource — KYC, KYB and AML screening
    /// through an identity verification provider account.
    pub fn identity_verifications(&self) -> IdentityVerifications {
        IdentityVerifications::new(self.inner.clone())
    }

    /// The `chargeback_prevention` resource — alerts from a chargeback
    /// prevention provider account the merchant connected.
    pub fn chargeback_prevention(&self) -> ChargebackPrevention {
        ChargebackPrevention::new(self.inner.clone())
    }

    /// The `processor_imports` resource — import refunds and disputes from
    /// connected processor accounts. Needs a dashboard JWT.
    pub fn processor_imports(&self) -> ProcessorImports {
        ProcessorImports::new(self.inner.clone())
    }

    /// The `risk` resource — stored shop risk indexes, per connector.
    pub fn risk(&self) -> Risk {
        Risk::new(self.inner.clone())
    }

    /// The `sell_to_restrictions` resource — the buyer countries the merchant
    /// refuses to sell to. Needs a dashboard JWT.
    pub fn sell_to_restrictions(&self) -> SellToRestrictions {
        SellToRestrictions::new(self.inner.clone())
    }

    /// The `whop_resolution_cases` resource — Whop Resolution Center cases,
    /// read and answered live through a Whop connector account.
    pub fn whop_resolution_cases(&self) -> WhopResolutionCases {
        WhopResolutionCases::new(self.inner.clone())
    }

    /// Build the shopper-facing hosted-checkout URL for a payment.
    ///
    /// `https://checkout.delopay.net/pay/{merchant_id}/{payment_id}`
    pub fn hosted_checkout_url(&self, merchant_id: &str, payment_id: &str) -> String {
        format!(
            "{}/pay/{}/{}",
            self.inner.checkout_base_url.trim_end_matches('/'),
            merchant_id,
            payment_id
        )
    }
}

impl Inner {
    /// The API base URL, for the few calls that hand back an address rather
    /// than make a request.
    pub(crate) fn api_base_url(&self) -> &str {
        &self.base_url
    }

    /// Build an `Inner` over an arbitrary transport. Used by the builder and by
    /// tests that inject a mock backend.
    pub(crate) fn with_transport(
        transport: Arc<dyn Transport>,
        base_url: String,
        checkout_base_url: String,
        api_key: String,
        max_retries: u32,
    ) -> Self {
        Self {
            transport,
            base_url,
            checkout_base_url,
            api_key,
            jwt: None,
            max_retries,
            logger: None,
            default_idempotency_key: None,
        }
    }

    /// Attach a dashboard session token, chained from
    /// [`with_transport`](Self::with_transport) by the builder.
    pub(crate) fn with_jwt(mut self, jwt: Option<String>) -> Self {
        self.jwt = jwt;
        self
    }

    /// Attach a logger. Chained from [`with_transport`](Self::with_transport)
    /// by the builder rather than added as a seventh positional argument.
    pub(crate) fn with_logger(mut self, logger: Option<DelopayLogger>) -> Self {
        self.logger = logger;
        self
    }

    /// A copy of this `Inner` with a different default idempotency key. Cheap:
    /// everything shared is behind an `Arc`.
    pub(crate) fn clone_with_idempotency_key(&self, key: Option<String>) -> Self {
        Self {
            transport: self.transport.clone(),
            base_url: self.base_url.clone(),
            checkout_base_url: self.checkout_base_url.clone(),
            api_key: self.api_key.clone(),
            jwt: self.jwt.clone(),
            max_retries: self.max_retries,
            logger: self.logger.clone(),
            default_idempotency_key: self.default_idempotency_key.clone(),
        }
        .with_idempotency_key_field(key)
    }

    fn with_idempotency_key_field(mut self, key: Option<String>) -> Self {
        self.default_idempotency_key = key;
        self
    }

    /// A copy of this `Inner` authenticating with a dashboard session token
    /// instead of the API key.
    pub(crate) fn clone_with_jwt(&self, jwt: Option<String>) -> Self {
        Self {
            transport: self.transport.clone(),
            base_url: self.base_url.clone(),
            checkout_base_url: self.checkout_base_url.clone(),
            api_key: self.api_key.clone(),
            jwt,
            max_retries: self.max_retries,
            logger: self.logger.clone(),
            default_idempotency_key: self.default_idempotency_key.clone(),
        }
    }

    /// Hand one event to the installed logger, if any.
    fn log(&self, event: LogEvent<'_>) {
        if let Some(logger) = &self.logger {
            logger(event);
        }
    }

    /// Perform a request with auth, timeout, retries and typed error handling.
    ///
    /// `body` is pre-serialized JSON (or `None`). Retries cover 429 always, and
    /// network/5xx only for idempotent calls (GET, or a POST carrying an
    /// idempotency key) so a create is never silently duplicated.
    ///
    /// Non-generic so the retry loop is compiled once, not per response type.
    //
    // Eight parameters, and clippy is right that this is a lot — but this is a
    // private single-call-path function with four thin crate-internal
    // wrappers above it (`request`, `request_with_headers`,
    // `request_with_content_type`, `request_bytes`), and
    // bundling the arguments into a struct would only move the same fields
    // behind a name every caller has to construct.
    #[allow(clippy::too_many_arguments)]
    pub(crate) async fn send_raw(
        &self,
        method: HttpMethod,
        path: &str,
        body: Option<&[u8]>,
        query: &[(&str, String)],
        idempotency_key: Option<&str>,
        extra_headers: &[(&str, &str)],
        content_type: Option<&str>,
    ) -> Result<Vec<u8>> {
        self.send_raw_keyed(
            method,
            path,
            body,
            query,
            idempotency_key,
            KeyPolicy::ClientDefaultApplies,
            extra_headers,
            content_type,
        )
        .await
    }

    #[allow(clippy::too_many_arguments)]
    pub(crate) async fn send_raw_keyed(
        &self,
        method: HttpMethod,
        path: &str,
        body: Option<&[u8]>,
        query: &[(&str, String)],
        idempotency_key: Option<&str>,
        key_policy: KeyPolicy,
        extra_headers: &[(&str, &str)],
        content_type: Option<&str>,
    ) -> Result<Vec<u8>> {
        let url = format!("{}{}", self.base_url, path);
        // A per-call key wins; otherwise the one set by
        // `Delopay::with_idempotency_key`, and only for methods that need it
        // (a GET is already replayable, and sending the header would be noise).
        //
        // `KeyPolicy::BodyKeyOnly` suppresses that fallback: on a route that
        // deduplicates on a key **in the body**, a header key the body does not
        // carry is not a weaker guarantee, it is a wrong one — the server would
        // dedupe on nothing while this client treated the write as replayable.
        //
        // It removes the *network and `5xx`* replays only. A `429` is retried
        // whatever the key says, here as everywhere: the request was refused
        // before the handler saw it, so replaying it cannot act twice.
        let idempotency_key = match idempotency_key {
            Some(key) => Some(key),
            None if method.is_inherently_idempotent() => None,
            None if key_policy == KeyPolicy::BodyKeyOnly => None,
            None => self.default_idempotency_key.as_deref(),
        };
        let is_idempotent = method.is_inherently_idempotent() || idempotency_key.is_some();
        let method_str = method.as_str();
        let mut attempt: u32 = 0;

        // A caller-supplied `accept` (a binary download asking for
        // `application/pdf`) replaces the default rather than joining it: two
        // `accept` headers on one request is a shape servers are free to
        // interpret either way, and "whichever it picks" is not a contract.
        let overrides_accept = extra_headers
            .iter()
            .any(|(name, _)| name.eq_ignore_ascii_case("accept"));
        // A dashboard session token replaces the API key rather than joining
        // it: the two authenticate as different principals, and sending both
        // leaves which one the server honoured up to the server.
        let bearer = self.jwt.as_deref().map(|token| format!("Bearer {token}"));
        // An empty key means "this client carries no api-key credential" —
        // `CheckoutSession`'s bearer half is built that way, and a route
        // authenticated by `Authorization: Bearer` must not also present a
        // key. Sending `api-key: ` would be a header with no meaning at best
        // and a credential-confusion bug at worst.
        let sends_api_key = bearer.is_none() && !self.api_key.is_empty();

        loop {
            let mut headers: Vec<(&str, &str)> = Vec::with_capacity(4 + extra_headers.len());
            if sends_api_key {
                headers.push(("api-key", &self.api_key));
            }
            if let Some(bearer) = bearer.as_deref() {
                headers.push(("authorization", bearer));
            }
            if !overrides_accept {
                headers.push(("accept", "application/json"));
            }
            if let Some(key) = idempotency_key {
                headers.push(("idempotency-key", key));
            }
            headers.extend_from_slice(extra_headers);

            let req = RawRequest {
                method,
                url: &url,
                headers: &headers,
                query,
                body,
                content_type,
            };

            if self.logger.is_some() {
                let query_keys: Vec<&str> = query.iter().map(|(k, _)| *k).collect();
                self.log(LogEvent::Request {
                    method: method_str,
                    url: &url,
                    query_keys: &query_keys,
                });
            }

            match self.transport.execute(req).await {
                Ok(resp) => {
                    self.log(LogEvent::Response {
                        method: method_str,
                        url: &url,
                        status: resp.status,
                        request_id: resp.header("x-request-id"),
                    });

                    if resp.is_success() {
                        return Ok(resp.body);
                    }

                    let too_many = resp.status == 429;
                    let retriable = too_many || resp.is_server_error();
                    let may_retry =
                        attempt < self.max_retries && retriable && (too_many || is_idempotent);

                    if may_retry {
                        attempt += 1;
                        let delay = parse_retry_after(resp.header("retry-after"))
                            .unwrap_or_else(|| backoff(attempt));
                        self.log(LogEvent::Retry {
                            method: method_str,
                            url: &url,
                            attempt,
                            max_retries: self.max_retries,
                            delay_ms: delay.as_millis() as u64,
                        });
                        tokio::time::sleep(delay).await;
                        continue;
                    }

                    let request_id = resp.header("x-request-id").map(str::to_owned);
                    return Err(DelopayError::from_response(
                        resp.status,
                        request_id,
                        &resp.body,
                    ));
                }
                Err(err) => {
                    if err.is_retriable() && is_idempotent && attempt < self.max_retries {
                        attempt += 1;
                        let delay = backoff(attempt);
                        self.log(LogEvent::Retry {
                            method: method_str,
                            url: &url,
                            attempt,
                            max_retries: self.max_retries,
                            delay_ms: delay.as_millis() as u64,
                        });
                        tokio::time::sleep(delay).await;
                        continue;
                    }
                    if err.kind == TransportErrorKind::Timeout {
                        return Err(DelopayError::Timeout);
                    }
                    return Err(DelopayError::Transport(err.source));
                }
            }
        }
    }

    /// Thin generic wrapper — the only part monomorphized per response type.
    pub(crate) async fn request<T: DeserializeOwned>(
        &self,
        method: HttpMethod,
        path: &str,
        body: Option<&[u8]>,
        query: &[(&str, String)],
        idempotency_key: Option<&str>,
    ) -> Result<T> {
        let bytes = self
            .send_raw(method, path, body, query, idempotency_key, &[], None)
            .await?;
        decode_success(&bytes)
    }

    /// [`request`](Self::request) for a body that is not JSON — currently only
    /// `multipart/form-data` file uploads. The caller supplies both the
    /// encoded body and the matching `Content-Type` (which for multipart
    /// carries the boundary, so the two cannot be built independently).
    pub(crate) async fn request_with_content_type<T: DeserializeOwned>(
        &self,
        method: HttpMethod,
        path: &str,
        body: &[u8],
        content_type: &str,
    ) -> Result<T> {
        let bytes = self
            .send_raw(method, path, Some(body), &[], None, &[], Some(content_type))
            .await?;
        decode_success(&bytes)
    }

    /// [`request_with_content_type`](Self::request_with_content_type) with a
    /// query string, for an upload scoped by query parameters (the buyer
    /// message attachments name their shop as `?shop=`).
    ///
    /// Never sends the client-wide key from [`Delopay::with_idempotency_key`]:
    /// these uploads deduplicate on a `client_upload_id` form field, not on
    /// the header, so the key would make a `5xx` replay look safe when the
    /// server dedupes on nothing it carries. A `429` is still replayed.
    pub(crate) async fn request_with_content_type_and_query<T: DeserializeOwned>(
        &self,
        method: HttpMethod,
        path: &str,
        query: &[(&str, String)],
        body: &[u8],
        content_type: &str,
    ) -> Result<T> {
        let bytes = self
            .send_raw_keyed(
                method,
                path,
                Some(body),
                query,
                None,
                KeyPolicy::BodyKeyOnly,
                &[],
                Some(content_type),
            )
            .await?;
        decode_success(&bytes)
    }

    /// [`request`](Self::request) for an endpoint that answers with bytes
    /// rather than JSON — today only the settlement statement PDF.
    ///
    /// Returns the body verbatim, with the same auth, retries and error
    /// mapping as every JSON call: a failure still arrives as a decoded
    /// [`DelopayError`], because the error envelope is JSON even when the
    /// success body is not.
    ///
    /// `accept` replaces the default `application/json` rather than joining
    /// it, so the server is asked for exactly one representation.
    pub(crate) async fn request_bytes(
        &self,
        method: HttpMethod,
        path: &str,
        query: &[(&str, String)],
        accept: &str,
    ) -> Result<Vec<u8>> {
        self.send_raw(method, path, None, query, None, &[("accept", accept)], None)
            .await
    }

    /// [`request`](Self::request) for a route that deduplicates on a key
    /// carried **in the request body**.
    ///
    /// `body_key` is that key, exactly as the body carries it. `None` means the
    /// body carries none, and then no `Idempotency-Key` header is sent either —
    /// not even the client-wide default from
    /// [`Delopay::with_idempotency_key`], which would make the write look
    /// replayable to this client while the server deduplicates on nothing.
    ///
    /// A `429` is still replayed either way — it never reached the handler.
    pub(crate) async fn request_body_keyed<T: DeserializeOwned>(
        &self,
        method: HttpMethod,
        path: &str,
        body: Option<&[u8]>,
        body_key: Option<&str>,
    ) -> Result<T> {
        let bytes = self
            .send_raw_keyed(
                method,
                path,
                body,
                &[],
                body_key,
                KeyPolicy::BodyKeyOnly,
                &[],
                None,
            )
            .await?;
        decode_success(&bytes)
    }

    /// [`request_body_keyed`](Self::request_body_keyed) with a query string.
    ///
    /// The write path of a route the server does not deduplicate on the
    /// `Idempotency-Key` header: with `body_key: None` no key is sent, not even
    /// the client-wide default, so a `5xx` or network error is not replayed.
    /// A `429` still is.
    pub(crate) async fn request_body_keyed_with_query<T: DeserializeOwned>(
        &self,
        method: HttpMethod,
        path: &str,
        body: Option<&[u8]>,
        query: &[(&str, String)],
        body_key: Option<&str>,
    ) -> Result<T> {
        let bytes = self
            .send_raw_keyed(
                method,
                path,
                body,
                query,
                body_key,
                KeyPolicy::BodyKeyOnly,
                &[],
                None,
            )
            .await?;
        decode_success(&bytes)
    }

    /// [`request_body_keyed_with_query`](Self::request_body_keyed_with_query)
    /// with additional per-request headers, for a write scoped by a header
    /// such as `x-profile-id`.
    ///
    /// With `body_key: None` no `Idempotency-Key` is sent, not even the
    /// client-wide default, so a `5xx` or network error is not replayed. A
    /// `429` still is.
    pub(crate) async fn request_body_keyed_with_query_and_headers<T: DeserializeOwned>(
        &self,
        method: HttpMethod,
        path: &str,
        body: Option<&[u8]>,
        query: &[(&str, String)],
        extra_headers: &[(&str, &str)],
        body_key: Option<&str>,
    ) -> Result<T> {
        let bytes = self
            .send_raw_keyed(
                method,
                path,
                body,
                query,
                body_key,
                KeyPolicy::BodyKeyOnly,
                extra_headers,
                None,
            )
            .await?;
        decode_success(&bytes)
    }

    /// [`request`](Self::request) with additional per-request headers, for the
    /// few endpoints that need one (e.g. the `x-profile-id` scoping header on
    /// subscriptions). Kept separate so the common path stays a five-argument
    /// call and existing call sites are untouched.
    pub(crate) async fn request_with_headers<T: DeserializeOwned>(
        &self,
        method: HttpMethod,
        path: &str,
        body: Option<&[u8]>,
        query: &[(&str, String)],
        idempotency_key: Option<&str>,
        extra_headers: &[(&str, &str)],
    ) -> Result<T> {
        let bytes = self
            .send_raw(
                method,
                path,
                body,
                query,
                idempotency_key,
                extra_headers,
                None,
            )
            .await?;
        decode_success(&bytes)
    }
}

fn decode_success<T: DeserializeOwned>(bytes: &[u8]) -> Result<T> {
    // Some endpoints return an empty 200/204 body; deserialize `null` so `T`
    // can be `()` or an `Option`.
    let slice: &[u8] = if bytes.is_empty() { b"null" } else { bytes };
    serde_json::from_slice(slice).map_err(|e| DelopayError::Decode(e.to_string()))
}

/// Builder for a [`Delopay`] client.
#[derive(Clone)]
pub struct DelopayBuilder {
    api_key: String,
    jwt: Option<String>,
    base_url: Option<String>,
    checkout_base_url: Option<String>,
    sandbox: bool,
    timeout: Duration,
    max_retries: u32,
    proxy: ProxyMode,
    logger: Option<DelopayLogger>,
}

// Hand-written rather than derived: `api_key` is deliberately omitted so a
// secret key cannot leak into logs via `{:?}` on a `DelopayBuilder`. Mirrors
// `Inner`'s `Debug` impl above — this is the one *public* type that also
// holds the key. `proxy` is printed through `ProxyMode`'s own redacting
// `Debug`, which never renders a proxy URL's `user:pass@`.
impl std::fmt::Debug for DelopayBuilder {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("DelopayBuilder")
            .field("base_url", &self.base_url)
            .field("checkout_base_url", &self.checkout_base_url)
            .field("sandbox", &self.sandbox)
            .field("timeout", &self.timeout)
            .field("max_retries", &self.max_retries)
            .field("proxy", &self.proxy)
            .field("logger", &self.logger.is_some())
            .finish_non_exhaustive()
    }
}

impl DelopayBuilder {
    fn new(api_key: impl Into<SecretKey>) -> Self {
        Self {
            api_key: api_key.into().into_string(),
            jwt: None,
            base_url: None,
            checkout_base_url: None,
            sandbox: false,
            timeout: DEFAULT_TIMEOUT,
            max_retries: DEFAULT_MAX_RETRIES,
            proxy: ProxyMode::Env,
            logger: None,
        }
    }

    /// Authenticate with a **dashboard session token** instead of the API key.
    ///
    /// Requests then carry `Authorization: Bearer <token>` and no `api-key`.
    /// The JWT-only surfaces — the merchant's own audit log, the user and
    /// session routes, the manual webhook trigger, the settlement aggregates —
    /// need this; an API key cannot read them.
    ///
    /// Use [`Delopay::with_jwt`] instead when the token arrives *after* the
    /// client exists, which is the usual shape for a dashboard that signs in
    /// first.
    #[must_use]
    pub fn jwt(mut self, token: impl Into<String>) -> Self {
        self.jwt = Some(token.into());
        self
    }

    /// A builder carrying **no** credential, for
    /// [`crate::CheckoutSession`], which installs its own per-half.
    ///
    /// Not public: an empty key is only meaningful for a client that
    /// authenticates some other way, and every other client needs a real one.
    pub(crate) fn for_checkout_session() -> Self {
        Self::new(SecretKey::new(String::new()))
    }

    /// Route request/response/retry events to `logger`.
    ///
    /// Nothing is logged unless one is installed. See [`LogEvent`] for exactly
    /// what is exposed — never headers, bodies, the API key, or query values.
    ///
    /// ```no_run
    /// use delopay::{Delopay, LogEvent};
    ///
    /// let client = Delopay::builder("prd_key")
    ///     .logger(|event: LogEvent<'_>| eprintln!("{event:?}"))
    ///     .build();
    /// ```
    pub fn logger<F>(mut self, logger: F) -> Self
    where
        F: Fn(LogEvent<'_>) + Send + Sync + 'static,
    {
        self.logger = Some(Arc::new(logger));
        self
    }

    /// Log every event to stderr with a `delopay:` prefix.
    ///
    /// Shorthand for a [`logger`](Self::logger) that writes with `eprintln!`;
    /// a later `logger` call replaces it, and a later `debug(true)` replaces a
    /// custom logger. `debug(false)` is a no-op — it does not uninstall a
    /// logger set earlier. For anything beyond local debugging, install your
    /// own logger and route it through `tracing` or `log`.
    pub fn debug(self, debug: bool) -> Self {
        if !debug {
            return self;
        }
        self.logger(|event| eprintln!("delopay: {event:?}"))
    }

    /// Point the client at the sandbox environment (`sandbox.delopay.net`).
    pub fn sandbox(mut self, sandbox: bool) -> Self {
        self.sandbox = sandbox;
        self
    }

    /// Override the API base URL (e.g. a local dev server).
    pub fn base_url(mut self, url: impl Into<String>) -> Self {
        self.base_url = Some(url.into());
        self
    }

    /// Override the hosted-checkout base URL.
    pub fn checkout_base_url(mut self, url: impl Into<String>) -> Self {
        self.checkout_base_url = Some(url.into());
        self
    }

    /// Per-request timeout (default 30s).
    pub fn timeout(mut self, timeout: Duration) -> Self {
        self.timeout = timeout;
        self
    }

    /// Maximum automatic retries for idempotent requests (default 2).
    pub fn max_retries(mut self, max_retries: u32) -> Self {
        self.max_retries = max_retries;
        self
    }

    /// Send every request through this HTTP proxy, ignoring the environment.
    ///
    /// Accepts `http://host:port` or `http://user:password@host:port`. The
    /// connection is made with HTTP `CONNECT` tunnelling, so for an `https://`
    /// API base URL the proxy relays encrypted bytes and never sees plaintext;
    /// the TLS certificate is still validated against the API's hostname.
    ///
    /// ```no_run
    /// # use delopay::Delopay;
    /// let client = Delopay::builder("prd_your_secret_key")
    ///     .proxy("http://corp-egress.internal:3128")
    ///     .build();
    /// ```
    ///
    /// If the URL cannot be used — it is malformed, or names a scheme other
    /// than `http` (`https://` and `socks5://` proxies are not supported) —
    /// every request fails with [`DelopayError::Transport`]. It deliberately
    /// does **not** fall back to a direct connection: if you asked for a proxy,
    /// something is probably relying on the traffic going through it.
    pub fn proxy(mut self, url: impl Into<String>) -> Self {
        self.proxy = ProxyMode::Explicit(url.into());
        self
    }

    /// Never use a proxy, ignoring `HTTPS_PROXY` and friends in the
    /// environment.
    ///
    /// ```no_run
    /// # use delopay::Delopay;
    /// let client = Delopay::builder("prd_your_secret_key").no_proxy().build();
    /// ```
    pub fn no_proxy(mut self) -> Self {
        self.proxy = ProxyMode::Disabled;
        self
    }

    /// Finish building the client.
    ///
    /// Unless [`proxy`][Self::proxy] or [`no_proxy`][Self::no_proxy] was
    /// called, the proxy is taken from the environment here — `HTTPS_PROXY` /
    /// `https_proxy`, `HTTP_PROXY` / `http_proxy`, `ALL_PROXY` / `all_proxy`,
    /// filtered by `NO_PROXY` / `no_proxy` — and resolved once against the API
    /// base URL, which is where every request from this client goes.
    pub fn build(self) -> Delopay {
        let api_key = self.api_key.clone();
        let jwt = self.jwt.clone();
        let parts = self.into_parts();
        Delopay {
            inner: Arc::new(parts.inner_with_key(api_key).with_jwt(jwt)),
        }
    }

    /// Everything a client needs except the credential.
    ///
    /// Split out because [`crate::CheckoutSession`] builds **two** `Inner`s
    /// from one configuration — one carrying a publishable key, one carrying
    /// no key at all — and they must share a transport rather than opening
    /// two connection pools to the same host.
    pub(crate) fn into_parts(self) -> ClientParts {
        let base_url = self.base_url.unwrap_or_else(|| {
            if self.sandbox {
                SANDBOX_URL
            } else {
                PRODUCTION_URL
            }
            .to_string()
        });
        let checkout_base_url = self
            .checkout_base_url
            .unwrap_or_else(|| crate::CHECKOUT_URL.to_string());

        // Resolved once, not per request: `send_raw` sends everything to
        // `base_url`'s host, so the decision cannot change between calls.
        let proxy = crate::http::proxy::resolve(&self.proxy, &base_url);

        let transport = Arc::new(HyperTransport::new(
            self.timeout,
            concat!("delopay-rust/", env!("CARGO_PKG_VERSION")),
            proxy,
        ));

        ClientParts {
            transport,
            base_url,
            checkout_base_url,
            max_retries: self.max_retries,
            logger: self.logger,
        }
    }
}

/// A built transport plus the configuration every `Inner` over it shares.
pub(crate) struct ClientParts {
    transport: Arc<dyn Transport>,
    base_url: String,
    checkout_base_url: String,
    max_retries: u32,
    logger: Option<DelopayLogger>,
}

impl ClientParts {
    /// An `Inner` over the shared transport, authenticating with `api_key`.
    ///
    /// An empty `api_key` means "send no `api-key` header" — see `send_raw`.
    pub(crate) fn inner_with_key(&self, api_key: String) -> Inner {
        Inner::with_transport(
            self.transport.clone(),
            self.base_url.clone(),
            self.checkout_base_url.clone(),
            api_key,
            self.max_retries,
        )
        .with_logger(self.logger.clone())
    }

    /// `ClientParts` over an injected transport, for tests that build a
    /// buyer-side client without a socket.
    #[cfg(test)]
    pub(crate) fn for_test(transport: Arc<dyn Transport>, base_url: &str) -> Self {
        Self {
            transport,
            base_url: base_url.to_string(),
            checkout_base_url: "https://checkout.test".to_string(),
            max_retries: 0,
            logger: None,
        }
    }
}

#[cfg(test)]
mod tests {
    use std::sync::{Arc, Mutex};

    use super::*;
    use crate::http::mock::{MockTransport, SeenRequest, Step};
    use crate::http::transport::TransportErrorKind;

    /// Minimal bodies that satisfy the response models' required fields.
    const PAYMENT_JSON: &str = r#"{
        "payment_id": "pay_1", "merchant_id": "mer_1", "status": "succeeded",
        "amount": 100, "currency": "EUR"
    }"#;

    const REFUND_JSON: &str = r#"{
        "refund_id": "ref_1", "payment_id": "pay_1", "amount": 500,
        "currency": "EUR", "status": "succeeded"
    }"#;

    fn client_with(steps: Vec<Step>, max_retries: u32) -> (Delopay, Arc<MockTransport>) {
        let mock = Arc::new(MockTransport::new(steps));
        let inner = Inner::with_transport(
            mock.clone(),
            "https://api.test".to_string(),
            "https://checkout.test".to_string(),
            "prd_test".to_string(),
            max_retries,
        );
        (
            Delopay {
                inner: Arc::new(inner),
            },
            mock,
        )
    }

    /// A dashboard token is a credential, so it must not reach a log line
    /// through `{:?}` on either type that holds one. Mutation: add
    /// `.field("jwt", &self.jwt)` to either hand-written `Debug` — the matching
    /// assertion goes red (verified).
    #[test]
    fn debug_never_renders_the_dashboard_token() {
        const TOKEN: &str = "eyJhbGciOiJIUzI1NiJ9.dashboard-token-sentinel";

        let builder = Delopay::builder("prd_secret_sentinel").jwt(TOKEN);
        let rendered = format!("{builder:?}");
        assert!(!rendered.contains(TOKEN), "builder leaked the token");
        assert!(
            !rendered.contains("prd_secret_sentinel"),
            "builder leaked the api key"
        );

        let (client, _mock) = client_with(vec![], 0);
        let with_token = client.with_jwt(TOKEN);
        let rendered = format!("{with_token:?}");
        assert!(!rendered.contains(TOKEN), "client leaked the token");
        assert!(!rendered.contains("prd_test"), "client leaked the api key");
    }

    #[tokio::test]
    async fn retries_429_even_for_non_idempotent_post() {
        let (client, mock) =
            client_with(vec![Step::status(429, ""), Step::ok(r#"{"ok":true}"#)], 2);
        let out: serde_json::Value = client
            .inner
            .request(HttpMethod::Post, "/x", None, &[], None)
            .await
            .unwrap();
        assert_eq!(out["ok"], true);
        assert_eq!(mock.call_count(), 2);
    }

    #[tokio::test]
    async fn does_not_retry_5xx_for_post_without_idempotency_key() {
        let (client, mock) = client_with(vec![Step::status(500, "")], 2);
        let err = client
            .inner
            .request::<serde_json::Value>(HttpMethod::Post, "/x", None, &[], None)
            .await
            .unwrap_err();
        assert!(matches!(err, DelopayError::Api(_)));
        assert_eq!(mock.call_count(), 1, "a bare POST must never be replayed");
    }

    #[tokio::test]
    async fn retries_5xx_for_post_with_idempotency_key() {
        let (client, mock) =
            client_with(vec![Step::status(500, ""), Step::ok(r#"{"ok":true}"#)], 2);
        let out: serde_json::Value = client
            .inner
            .request(HttpMethod::Post, "/x", None, &[], Some("key-1"))
            .await
            .unwrap();
        assert_eq!(out["ok"], true);
        assert_eq!(mock.call_count(), 2);
        assert!(
            mock.seen
                .lock()
                .unwrap()
                .iter()
                .all(SeenRequest::had_idempotency_key)
        );
    }

    #[tokio::test]
    async fn retries_5xx_for_get() {
        let (client, mock) =
            client_with(vec![Step::status(503, ""), Step::ok(r#"{"ok":true}"#)], 2);
        let _: serde_json::Value = client
            .inner
            .request(HttpMethod::Get, "/x", None, &[], None)
            .await
            .unwrap();
        assert_eq!(mock.call_count(), 2);

        // Pin what the mock actually received. Without this, nothing in the
        // suite checks the method or URL, so a request sent to the wrong path
        // or with the wrong verb would still pass every retry test.
        let seen = mock.seen.lock().unwrap();
        for req in seen.iter() {
            assert_eq!(req.method, "GET");
            assert_eq!(req.url, "https://api.test/x");
        }
    }

    #[tokio::test]
    async fn stops_after_max_retries() {
        let (client, mock) = client_with(
            vec![
                Step::status(500, ""),
                Step::status(500, ""),
                Step::status(500, ""),
            ],
            2,
        );
        let _ = client
            .inner
            .request::<serde_json::Value>(HttpMethod::Get, "/x", None, &[], None)
            .await
            .unwrap_err();
        assert_eq!(mock.call_count(), 3, "initial attempt + 2 retries");
    }

    #[tokio::test]
    async fn timeout_maps_to_timeout_variant() {
        let (client, _) = client_with(vec![Step::Fail(TransportErrorKind::Timeout)], 0);
        let err = client
            .inner
            .request::<serde_json::Value>(HttpMethod::Get, "/x", None, &[], None)
            .await
            .unwrap_err();
        assert!(matches!(err, DelopayError::Timeout));
    }

    #[tokio::test]
    async fn connect_failure_maps_to_transport_variant() {
        let (client, _) = client_with(vec![Step::Fail(TransportErrorKind::Connect)], 0);
        let err = client
            .inner
            .request::<serde_json::Value>(HttpMethod::Get, "/x", None, &[], None)
            .await
            .unwrap_err();
        assert!(matches!(err, DelopayError::Transport(_)));
    }

    #[tokio::test]
    async fn maps_401_to_authentication_error() {
        let (client, _) = client_with(
            vec![Step::status(
                401,
                r#"{"error":{"code":"AUTH_01","type":"authentication_error","message":"bad key"}}"#,
            )],
            0,
        );
        let err = client
            .inner
            .request::<serde_json::Value>(HttpMethod::Get, "/x", None, &[], None)
            .await
            .unwrap_err();
        match err {
            DelopayError::Authentication(api) => assert_eq!(api.code, "AUTH_01"),
            other => panic!("expected Authentication, got {other:?}"),
        }
    }

    #[tokio::test(start_paused = true)]
    async fn honors_retry_after_header() {
        // Asserting only that a retry happened would pass even if `Retry-After`
        // were ignored entirely, because plain backoff also retries. The delay
        // itself is the behavior under test, so measure it. `start_paused`
        // gives tokio a virtual clock: sleeps complete instantly but advance
        // `Instant::now()` exactly, so this is deterministic, not timing-flaky.
        let (client, mock) = client_with(
            vec![
                Step::status_with_header(429, "retry-after", "5"),
                Step::ok(r#"{"ok":true}"#),
            ],
            2,
        );

        let started = tokio::time::Instant::now();
        let _: serde_json::Value = client
            .inner
            .request(HttpMethod::Get, "/x", None, &[], None)
            .await
            .unwrap();
        let waited = started.elapsed();

        assert_eq!(mock.call_count(), 2);
        assert_eq!(
            waited,
            Duration::from_secs(5),
            "must wait exactly the Retry-After value, not the {:?} backoff",
            backoff(1)
        );
    }

    #[tokio::test(start_paused = true)]
    async fn falls_back_to_backoff_when_retry_after_absent() {
        // The companion to the test above: with no `Retry-After` header the
        // delay must come from the backoff schedule instead.
        let (client, mock) =
            client_with(vec![Step::status(429, ""), Step::ok(r#"{"ok":true}"#)], 2);

        let started = tokio::time::Instant::now();
        let _: serde_json::Value = client
            .inner
            .request(HttpMethod::Get, "/x", None, &[], None)
            .await
            .unwrap();

        assert_eq!(mock.call_count(), 2);
        assert_eq!(started.elapsed(), backoff(1));
    }

    #[tokio::test]
    async fn post_without_idempotency_key_is_never_replayed_on_network_failure() {
        // Duplicate-charge guard: a bare POST (no idempotency key) whose
        // connection times out mid-flight must NOT be retried, because the
        // server may already have taken the charge before the timeout. A
        // retry here would mean silently double-charging the customer.
        // Mutation coverage: deleting `&& is_idempotent` from the transport-
        // error retry branch in `send_raw` makes this test fail (call_count
        // becomes 2 and the transport error is swallowed by a successful
        // second attempt).
        let (client, mock) = client_with(vec![Step::Fail(TransportErrorKind::Timeout)], 2);
        let err = client
            .inner
            .request::<serde_json::Value>(HttpMethod::Post, "/x", None, &[], None)
            .await
            .unwrap_err();
        assert!(matches!(err, DelopayError::Timeout));
        assert_eq!(
            mock.call_count(),
            1,
            "a bare POST must never be replayed after a network failure — the \
             original attempt may already have taken effect server-side"
        );
    }

    #[tokio::test]
    async fn post_with_idempotency_key_is_retried_on_network_failure() {
        // Mirror image of the test above: once the caller has supplied an
        // idempotency key, a network-level failure IS safe to retry, because
        // the server can deduplicate the replay using that key.
        let (client, mock) = client_with(
            vec![
                Step::Fail(TransportErrorKind::Timeout),
                Step::ok(r#"{"ok":true}"#),
            ],
            2,
        );
        let out: serde_json::Value = client
            .inner
            .request(HttpMethod::Post, "/x", None, &[], Some("key-1"))
            .await
            .unwrap();
        assert_eq!(out["ok"], true);
        assert_eq!(mock.call_count(), 2);
    }

    #[tokio::test]
    async fn extra_headers_reach_the_transport() {
        // Mutation coverage: deleting `headers.extend_from_slice(extra_headers)`
        // in `send_raw` makes this fail — the scoping header silently vanishes
        // from every subscriptions call.
        let (client, mock) = client_with(vec![Step::ok(r#"{"ok":true}"#)], 0);
        let _: serde_json::Value = client
            .inner
            .request_with_headers(
                HttpMethod::Post,
                "/x",
                None,
                &[],
                None,
                &[("x-profile-id", "pro_1")],
            )
            .await
            .unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].header("x-profile-id"), Some("pro_1"));
        assert_eq!(
            seen[0].header("api-key"),
            Some("prd_test"),
            "extra headers must be appended, not replace the built-in set"
        );
    }

    #[tokio::test]
    async fn put_without_idempotency_key_is_not_retried_on_5xx() {
        // PUT is deliberately not inherently idempotent (see `HttpMethod`).
        // Mutation coverage: making `is_inherently_idempotent` return true for
        // `Put` turns this into two calls and a swallowed error.
        let (client, mock) = client_with(vec![Step::status(500, "")], 2);
        let err = client
            .inner
            .request::<serde_json::Value>(HttpMethod::Put, "/x", None, &[], None)
            .await
            .unwrap_err();
        assert!(matches!(err, DelopayError::Api(_)));
        assert_eq!(
            mock.call_count(),
            1,
            "a bare PUT must never be replayed — this API uses PUT for \
             state transitions, where a blind replay is not provably safe"
        );
    }

    #[test]
    fn delopay_builder_debug_redacts_api_key() {
        let builder = Delopay::builder("prd_super_secret_key_for_debug_test");
        let formatted = format!("{builder:?}");
        assert!(
            !formatted.contains("prd_super_secret_key_for_debug_test"),
            "DelopayBuilder's Debug output must not contain the secret api key: {formatted}"
        );
    }

    #[test]
    fn delopay_builder_debug_redacts_proxy_credentials() {
        // A proxy URL is a second secret this public type can hold. `.proxy()`
        // returns the builder, so `{:?}` on it is just as reachable as it is
        // for the API key.
        let builder =
            Delopay::builder("prd_x").proxy("http://alice:hunter2@corp-egress.internal:3128");
        let formatted = format!("{builder:?}");
        assert!(
            !formatted.contains("hunter2") && !formatted.contains("alice"),
            "DelopayBuilder's Debug output must not contain proxy credentials: {formatted}"
        );
    }

    #[test]
    fn inner_debug_redacts_api_key() {
        let mock = Arc::new(MockTransport::new(vec![]));
        let inner = Inner::with_transport(
            mock,
            "https://api.test".to_string(),
            "https://checkout.test".to_string(),
            "prd_super_secret_key_for_inner_debug_test".to_string(),
            2,
        );
        let formatted = format!("{inner:?}");
        assert!(
            !formatted.contains("prd_super_secret_key_for_inner_debug_test"),
            "Inner's Debug output must not contain the secret api key: {formatted}"
        );
    }

    #[tokio::test]
    async fn body_read_failure_is_not_retried_through_send_raw() {
        // `TransportErrorKind::Body` represents a failed body read after a
        // successful (2xx) response and must never trigger a retry — even
        // for an idempotent GET with retry budget to spare — because
        // retrying would re-issue a request whose original attempt may
        // already have taken effect server-side. `transport.rs` already
        // covers `is_retriable()` in isolation; this exercises the same
        // classification through the full `send_raw` retry loop so a
        // regression that wired `Body` into the retry branch would be
        // caught here too.
        let (client, mock) = client_with(vec![Step::Fail(TransportErrorKind::Body)], 2);
        let err = client
            .inner
            .request::<serde_json::Value>(HttpMethod::Get, "/x", None, &[], None)
            .await
            .unwrap_err();
        assert!(matches!(err, DelopayError::Transport(_)));
        assert_eq!(
            mock.call_count(),
            1,
            "a Body read failure must never be retried"
        );
    }

    /// A logger installed on the builder, capturing events into a Vec.
    fn capturing_logger() -> (DelopayLogger, Arc<Mutex<Vec<String>>>) {
        let seen: Arc<Mutex<Vec<String>>> = Arc::new(Mutex::new(Vec::new()));
        let sink = seen.clone();
        let logger: DelopayLogger = Arc::new(move |event: LogEvent<'_>| {
            sink.lock().unwrap().push(format!("{event:?}"));
        });
        (logger, seen)
    }

    fn client_with_logger(
        steps: Vec<Step>,
        max_retries: u32,
    ) -> (Delopay, Arc<MockTransport>, Arc<Mutex<Vec<String>>>) {
        let mock = Arc::new(MockTransport::new(steps));
        let (logger, seen) = capturing_logger();
        let inner = Inner::with_transport(
            mock.clone(),
            "https://api.test".to_string(),
            "https://checkout.test".to_string(),
            "prd_test".to_string(),
            max_retries,
        )
        .with_logger(Some(logger));
        (
            Delopay {
                inner: Arc::new(inner),
            },
            mock,
            seen,
        )
    }

    #[tokio::test]
    async fn logger_sees_request_and_response_but_never_secrets() {
        let (client, _mock, seen) = client_with_logger(vec![Step::ok("[]")], 0);
        let params = crate::CustomerListParams {
            search: Some("ada@example.com".to_string()),
            ..Default::default()
        };
        client.customers().list(Some(&params)).await.unwrap();

        let events = seen.lock().unwrap();
        assert_eq!(events.len(), 2, "one request event, one response event");
        assert!(events[0].starts_with("Request"));
        assert!(events[0].contains("https://api.test/customers/list"));
        assert!(events[1].starts_with("Response"));
        assert!(events[1].contains("status: 200"));

        let all = events.join("\n");
        // The query *key* is fair game; the customer's email in the search
        // text is not, and the API key must never appear.
        assert!(all.contains("search"));
        assert!(!all.contains("ada@example.com"));
        assert!(!all.contains("prd_test"));
    }

    #[tokio::test]
    async fn logger_reports_each_retry_with_its_attempt_number() {
        let (client, mock, seen) = client_with_logger(
            vec![
                Step::status(429, r#"{"error":{"message":"slow down"}}"#),
                Step::ok(PAYMENT_JSON),
            ],
            2,
        );
        client
            .payments()
            .create(&crate::PaymentCreateRequest::new(100, "EUR"))
            .await
            .unwrap();

        assert_eq!(mock.call_count(), 2);
        let events = seen.lock().unwrap();
        let retries: Vec<&String> = events.iter().filter(|e| e.starts_with("Retry")).collect();
        assert_eq!(retries.len(), 1);
        assert!(retries[0].contains("attempt: 1"));
        assert!(retries[0].contains("max_retries: 2"));
    }

    #[tokio::test]
    async fn no_logger_installed_means_no_work_and_no_panic() {
        let (client, mock) = client_with(vec![Step::ok("[]")], 0);
        client.customers().list(None).await.unwrap();
        assert_eq!(mock.call_count(), 1);
    }

    #[tokio::test]
    async fn with_idempotency_key_sets_the_header_on_a_post() {
        let (client, mock) = client_with(vec![Step::ok(REFUND_JSON)], 0);
        client
            .with_idempotency_key("order-42")
            .refunds()
            .create(&crate::RefundCreateRequest::new("pay_1"))
            .await
            .unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].header("idempotency-key"), Some("order-42"));
    }

    #[tokio::test]
    async fn with_idempotency_key_leaves_get_requests_alone() {
        let (client, mock) = client_with(vec![Step::ok("[]")], 0);
        client
            .with_idempotency_key("order-42")
            .customers()
            .list(None)
            .await
            .unwrap();

        let seen = mock.seen.lock().unwrap();
        assert!(
            !seen[0].had_idempotency_key(),
            "a GET is already replayable; the header would be noise"
        );
    }

    #[tokio::test]
    async fn a_per_call_idempotency_key_wins_over_the_client_default() {
        let (client, mock) = client_with(vec![Step::ok(REFUND_JSON)], 0);
        client
            .with_idempotency_key("client-default")
            .refunds()
            .create_idempotent(&crate::RefundCreateRequest::new("pay_1"), "per-call")
            .await
            .unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].header("idempotency-key"), Some("per-call"));
    }

    #[tokio::test]
    async fn client_default_idempotency_key_makes_a_post_retriable() {
        // Without a key, a 500 on POST is returned as-is. With one, the retry
        // policy treats the call as idempotent and re-sends it.
        let (client, mock) = client_with(
            vec![
                Step::status(500, r#"{"error":{"message":"boom"}}"#),
                Step::ok(REFUND_JSON),
            ],
            2,
        );
        client
            .with_idempotency_key("order-42")
            .refunds()
            .create(&crate::RefundCreateRequest::new("pay_1"))
            .await
            .unwrap();

        assert_eq!(mock.call_count(), 2);
    }

    #[tokio::test]
    async fn the_original_client_is_unaffected_by_with_idempotency_key() {
        let (client, mock) = client_with(vec![Step::ok(REFUND_JSON), Step::ok(REFUND_JSON)], 0);
        let keyed = client.with_idempotency_key("order-42");
        keyed
            .refunds()
            .create(&crate::RefundCreateRequest::new("pay_1"))
            .await
            .unwrap();
        client
            .refunds()
            .create(&crate::RefundCreateRequest::new("pay_1"))
            .await
            .unwrap();

        let seen = mock.seen.lock().unwrap();
        assert!(seen[0].had_idempotency_key());
        assert!(!seen[1].had_idempotency_key());
    }

    #[test]
    fn debug_output_never_reveals_whether_a_logger_holds_state() {
        let builder = Delopay::builder("prd_secret").logger(|_| {});
        let rendered = format!("{builder:?}");
        assert!(rendered.contains("logger: true"));
        assert!(!rendered.contains("prd_secret"));
    }
}