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

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

use serde::de::DeserializeOwned;

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::analytics::Analytics;
use crate::resources::analytics_dashboard::AnalyticsDashboard;
use crate::resources::api_keys::ApiKeys;
use crate::resources::authentication::Authentication;
use crate::resources::availability_overrides::AvailabilityOverrides;
use crate::resources::billing::Billing;
use crate::resources::blocklist::Blocklist;
use crate::resources::cards::Cards;
use crate::resources::connectors::Connectors;
use crate::resources::customers::Customers;
use crate::resources::disputes::Disputes;
use crate::resources::ephemeral_keys::EphemeralKeys;
use crate::resources::events::Events;
use crate::resources::export::Export;
use crate::resources::feature_matrix::FeatureMatrix;
use crate::resources::fees::Fees;
use crate::resources::files::Files;
use crate::resources::forex::Forex;
use crate::resources::mandates::Mandates;
use crate::resources::merchant_accounts::MerchantAccounts;
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::poll::Poll;
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::routing::Routing;
use crate::resources::search::Search;
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::{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>;

pub(crate) struct Inner {
    transport: Arc<dyn Transport>,
    base_url: String,
    checkout_base_url: String,
    api_key: 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_...`).
    pub fn new(api_key: impl Into<String>) -> Self {
        Self::builder(api_key).build()
    }

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

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

    /// 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 `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 `cards` resource.
    pub fn cards(&self) -> Cards {
        Cards::new(self.inner.clone())
    }

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

    /// The `files` resource.
    pub fn files(&self) -> Files {
        Files::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, decision config and
    /// surcharge 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. The fee-rule program is reached via
    /// [`Fees::rules`].
    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 `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 `analytics` resource.
    pub fn analytics(&self) -> Analytics {
        Analytics::new(self.inner.clone())
    }

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

    /// The `search` resource: global search across analytics domains.
    pub fn search(&self) -> Search {
        Search::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 `blocklist` resource.
    pub fn blocklist(&self) -> Blocklist {
        Blocklist::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 `feature_matrix` resource.
    pub fn feature_matrix(&self) -> FeatureMatrix {
        FeatureMatrix::new(self.inner.clone())
    }

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

    /// The `availability_overrides` resource.
    pub fn availability_overrides(&self) -> AvailabilityOverrides {
        AvailabilityOverrides::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 {
    /// 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,
            max_retries,
            logger: None,
            default_idempotency_key: None,
        }
    }

    /// 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(),
            max_retries: self.max_retries,
            logger: self.logger.clone(),
            default_idempotency_key: key,
        }
    }

    /// 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 three thin public wrappers above
    // it (`request`, `request_with_headers`, `request_with_content_type`), 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>> {
        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).
        let idempotency_key = match idempotency_key {
            Some(key) => Some(key),
            None if method.is_inherently_idempotent() => 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;

        loop {
            let mut headers: Vec<(&str, &str)> =
                vec![("api-key", &self.api_key), ("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`](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,
    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<String>) -> Self {
        Self {
            api_key: api_key.into(),
            base_url: None,
            checkout_base_url: None,
            sandbox: false,
            timeout: DEFAULT_TIMEOUT,
            max_retries: DEFAULT_MAX_RETRIES,
            proxy: ProxyMode::Env,
            logger: None,
        }
    }

    /// 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 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,
        ));

        Delopay {
            inner: Arc::new(
                Inner::with_transport(
                    transport,
                    base_url,
                    checkout_base_url,
                    self.api_key,
                    self.max_retries,
                )
                .with_logger(self.logger),
            ),
        }
    }
}

#[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,
        )
    }

    #[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 {
            email: 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 is not, and the
        // API key must never appear.
        assert!(all.contains("email"));
        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"));
    }
}