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
//! The `checkout_methods` resource: a shop's payment-method layout for the
//! hosted checkout — the express strip, the main list, the "other payment
//! methods" list and each item's overrides.
//!
//! One layout per shop (business profile) and environment. Until a shop saves
//! one, the API derives a layout from the shop's connector accounts and
//! reports `source: "derived"`. The Test checkout, used by payments created
//! with `test_mode: true`, follows Live's until its first save.
//!
//! Every endpoint is scoped by `merchant_id`, sent as `?merchant_id=…`.
//! Dashboard JWT or admin key.

use std::sync::Arc;

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

use crate::core::encoding::{encode_segment, to_json_vec};
use crate::core::error::{DelopayError, Result};
use crate::core::models::checkout_method::{
    CheckoutAccountVisibilityResponse, CheckoutEntriesResponse, CheckoutEntry,
    CheckoutMethodsAvailabilityResponse, CheckoutMethodsChildrenResponse,
    CheckoutMethodsResetResponse, CheckoutMethodsResponse, CheckoutPaymentMethodOptionsResponse,
    CheckoutRedirectRulesTestResponse,
};
use crate::http::client::Inner;
use crate::http::transport::HttpMethod;
use crate::resources::ValidateRequest;

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

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

    /// The shop's layout (stored, or derived from its accounts) and every item
    /// it may place, for one environment.
    /// `GET /checkout-methods/{profile_id}` (`/test` for Test)`?merchant_id=`
    pub async fn retrieve(
        &self,
        merchant_id: &str,
        profile_id: &str,
        environment: CheckoutEnvironment,
    ) -> Result<CheckoutMethodsResponse> {
        self.inner
            .request(
                HttpMethod::Get,
                &methods_path(profile_id, environment),
                None,
                &merchant_query(merchant_id),
                None,
            )
            .await
    }

    /// Replace the layout of one environment.
    /// `PUT /checkout-methods/{profile_id}` (`/test` for Test)`?merchant_id=`
    ///
    /// The API refuses an express item that does not draw its own button,
    /// more than two rows of two in the express strip, a title without text,
    /// or an item no account of the shop offers.
    pub async fn update(
        &self,
        merchant_id: &str,
        profile_id: &str,
        params: &CheckoutMethodsUpdateRequest,
        environment: CheckoutEnvironment,
    ) -> Result<CheckoutMethodsResponse> {
        params.validate()?;
        let body = to_json_vec(params)?;
        self.inner
            .request_body_keyed_with_query(
                HttpMethod::Put,
                &methods_path(profile_id, environment),
                Some(&body),
                &merchant_query(merchant_id),
                None,
            )
            .await
    }

    /// Delete the stored layout of one environment: Live goes back to the
    /// derived layout, Test follows Live again.
    /// `DELETE /checkout-methods/{profile_id}` (`/test` for Test)`?merchant_id=`
    pub async fn reset(
        &self,
        merchant_id: &str,
        profile_id: &str,
        environment: CheckoutEnvironment,
    ) -> Result<CheckoutMethodsResetResponse> {
        self.inner
            .request_body_keyed_with_query(
                HttpMethod::Delete,
                &methods_path(profile_id, environment),
                None,
                &merchant_query(merchant_id),
                None,
            )
            .await
    }

    /// For a buyer in `country` paying `amount` `currency`: which placeable
    /// items they are offered and every reason they are not, asked the way
    /// the hosted checkout asks, plus how each smart block evaluates.
    /// `GET /checkout-methods/{profile_id}/availability`
    /// (`/test/availability` when `test_mode` is set)
    pub async fn availability(
        &self,
        merchant_id: &str,
        profile_id: &str,
        params: &CheckoutMethodsAvailabilityParams,
    ) -> Result<CheckoutMethodsAvailabilityResponse> {
        let environment = if params.test_mode {
            CheckoutEnvironment::Test
        } else {
            CheckoutEnvironment::Live
        };
        let path = format!("{}/availability", methods_path(profile_id, environment));
        let query = vec![
            ("merchant_id", merchant_id.to_string()),
            ("country", params.country.clone()),
            ("amount", params.amount.to_string()),
            ("currency", params.currency.clone()),
        ];
        self.inner
            .request(HttpMethod::Get, &path, None, &query, None)
            .await
    }

    /// What DeloPay confirms beneath each item the shop can place: the card
    /// networks the card form's accounts accept, and the methods or coins a
    /// provider's page offers, per account. A provider that answers only per
    /// order reports `context_required` until `currency` and `amount` are
    /// given.
    /// `GET /checkout-methods/{profile_id}/children` (`/test/children` for Test)
    pub async fn children(
        &self,
        merchant_id: &str,
        profile_id: &str,
        params: &CheckoutMethodsChildrenParams,
    ) -> Result<CheckoutMethodsChildrenResponse> {
        let path = format!("{}/children", methods_path(profile_id, params.environment));
        let mut query = merchant_query(merchant_id);
        if let Some(country) = &params.country {
            query.push(("country", country.clone()));
        }
        if let Some(currency) = &params.currency {
            query.push(("currency", currency.clone()));
        }
        if let Some(amount) = params.amount {
            query.push(("amount", amount.to_string()));
        }
        self.inner
            .request(HttpMethod::Get, &path, None, &query, None)
            .await
    }

    /// Hide a connector account from the checkout of the named environments,
    /// or show it again. Its items stay in the layout, listed with
    /// `account_enabled: false`; routing and credentials are not changed.
    /// `PUT /checkout-methods/{profile_id}/accounts/{merchant_connector_id}/visibility`
    pub async fn set_account_visibility(
        &self,
        merchant_id: &str,
        profile_id: &str,
        merchant_connector_id: &str,
        params: &CheckoutAccountVisibilityRequest,
    ) -> Result<CheckoutAccountVisibilityResponse> {
        let path = format!(
            "/checkout-methods/{}/accounts/{}/visibility",
            encode_segment(profile_id),
            encode_segment(merchant_connector_id)
        );
        let body = to_json_vec(params)?;
        self.inner
            .request_body_keyed_with_query(
                HttpMethod::Put,
                &path,
                Some(&body),
                &merchant_query(merchant_id),
                None,
            )
            .await
    }

    /// The same document as [`retrieve`](Self::retrieve), on the route that
    /// stays open to a reader of the checkout's appearance while the role's
    /// payment-data visibility is restricted.
    /// `GET /checkout-methods/{profile_id}/preview` (`/test/preview` for Test)
    pub async fn preview(
        &self,
        merchant_id: &str,
        profile_id: &str,
        environment: CheckoutEnvironment,
    ) -> Result<CheckoutMethodsResponse> {
        let path = format!("{}/preview", methods_path(profile_id, environment));
        self.inner
            .request(
                HttpMethod::Get,
                &path,
                None,
                &merchant_query(merchant_id),
                None,
            )
            .await
    }

    /// The methods a payment of the shop can be limited to through
    /// `allowed_payment_method_types`, in the order its checkout places them.
    /// Names methods only, never a processor or account.
    /// `GET /checkout-methods/{profile_id}/payment-method-options`
    /// (`/test/payment-method-options` for Test)
    pub async fn payment_method_options(
        &self,
        merchant_id: &str,
        profile_id: &str,
        environment: CheckoutEnvironment,
    ) -> Result<CheckoutPaymentMethodOptionsResponse> {
        let path = format!(
            "{}/payment-method-options",
            methods_path(profile_id, environment)
        );
        self.inner
            .request(
                HttpMethod::Get,
                &path,
                None,
                &merchant_query(merchant_id),
                None,
            )
            .await
    }

    /// What the given redirect rules, saved or not, decide for the buyer the
    /// request describes, and how each rule fared. Nothing is stored.
    ///
    /// Refused with 422 when the rules are malformed or name an account that
    /// is not the shop's, and with 403 when they name one the caller may not
    /// read.
    /// `POST /checkout-methods/{profile_id}/redirect-rules/test`
    /// (`/test/redirect-rules/test` for Test)
    pub async fn test_redirect_rules(
        &self,
        merchant_id: &str,
        profile_id: &str,
        params: &CheckoutRedirectRulesTestRequest,
        environment: CheckoutEnvironment,
    ) -> Result<CheckoutRedirectRulesTestResponse> {
        params.validate()?;
        let path = format!(
            "{}/redirect-rules/test",
            methods_path(profile_id, environment)
        );
        let body = to_json_vec(params)?;
        self.inner
            .request_body_keyed_with_query(
                HttpMethod::Post,
                &path,
                Some(&body),
                &merchant_query(merchant_id),
                None,
            )
            .await
    }

    /// The shop's checkout entries: separate ways into the hosted checkout of
    /// one payment (`?entry=<key>`), each in its own named look.
    ///
    /// Refused (403) to a caller that may not see or change every method.
    /// `GET /checkout-methods/{profile_id}/entries` (`/test/entries` for Test)
    pub async fn entries(
        &self,
        merchant_id: &str,
        profile_id: &str,
        environment: CheckoutEnvironment,
    ) -> Result<CheckoutEntriesResponse> {
        self.inner
            .request(
                HttpMethod::Get,
                &entries_path(profile_id, environment),
                None,
                &merchant_query(merchant_id),
                None,
            )
            .await
    }

    /// Replace the shop's entries of one environment.
    ///
    /// Refused when a key is malformed or used twice, when an entry lists a
    /// method, group or card form that environment's layout does not place,
    /// or when a card entry's `other_entry` is not another `methods` entry.
    /// `PUT /checkout-methods/{profile_id}/entries` (`/test/entries` for Test)
    pub async fn update_entries(
        &self,
        merchant_id: &str,
        profile_id: &str,
        params: &CheckoutEntriesUpdateRequest,
        environment: CheckoutEnvironment,
    ) -> Result<CheckoutEntriesResponse> {
        params.validate()?;
        let body = to_json_vec(params)?;
        self.inner
            .request_body_keyed_with_query(
                HttpMethod::Put,
                &entries_path(profile_id, environment),
                Some(&body),
                &merchant_query(merchant_id),
                None,
            )
            .await
    }

    /// Delete every entry of one environment. A link that still names an
    /// entry then offers nothing.
    /// `DELETE /checkout-methods/{profile_id}/entries` (`/test/entries` for Test)
    pub async fn clear_entries(
        &self,
        merchant_id: &str,
        profile_id: &str,
        environment: CheckoutEnvironment,
    ) -> Result<CheckoutEntriesResponse> {
        self.inner
            .request_body_keyed_with_query(
                HttpMethod::Delete,
                &entries_path(profile_id, environment),
                None,
                &merchant_query(merchant_id),
                None,
            )
            .await
    }
}

/// `/checkout-methods/{profile_id}/entries`, or `/test/entries` for Test.
fn entries_path(profile_id: &str, environment: CheckoutEnvironment) -> String {
    format!("{}/entries", methods_path(profile_id, environment))
}

/// `/checkout-methods/{profile_id}`, plus `/test` for the Test checkout.
fn methods_path(profile_id: &str, environment: CheckoutEnvironment) -> String {
    let shop = format!("/checkout-methods/{}", encode_segment(profile_id));
    match environment {
        CheckoutEnvironment::Live => shop,
        CheckoutEnvironment::Test => format!("{shop}/test"),
    }
}

/// The `?merchant_id=…` scope every checkout-methods endpoint requires.
fn merchant_query(merchant_id: &str) -> Vec<(&'static str, String)> {
    vec![("merchant_id", merchant_id.to_string())]
}

/// Which checkout a call reads or writes: Live (the default) or Test, used by
/// payments created with `test_mode: true`.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum CheckoutEnvironment {
    /// The Live checkout.
    #[default]
    Live,
    /// The Test checkout.
    Test,
}

/// Body of [`CheckoutMethods::update`]: replaces the whole layout.
#[derive(Debug, Clone, Serialize)]
pub struct CheckoutMethodsUpdateRequest {
    /// The layout, in the shape `CheckoutMethodsResponse::layout` returns
    /// it: `express` rows, `normal` and `alternative` lists.
    pub layout: Value,
    /// Any additional fields, merged verbatim.
    #[serde(flatten, skip_serializing_if = "serde_json::Map::is_empty")]
    pub extra: serde_json::Map<String, Value>,
}

impl CheckoutMethodsUpdateRequest {
    /// A request replacing the layout with `layout`.
    pub fn new(layout: Value) -> Self {
        Self {
            layout,
            extra: serde_json::Map::new(),
        }
    }
}

/// Names of `CheckoutMethodsUpdateRequest`'s fields as they appear on the
/// wire (`extra` excluded).
const CHECKOUT_METHODS_UPDATE_REQUEST_NAMED: &[&str] = &["layout"];

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

/// Query of [`CheckoutMethods::availability`]: the buyer the answer is for.
#[derive(Debug, Clone, Default)]
pub struct CheckoutMethodsAvailabilityParams {
    /// The buyer's country, ISO 3166-1 alpha-2.
    pub country: String,
    /// The order value, in minor units of `currency`.
    pub amount: i64,
    /// ISO 4217 currency code.
    pub currency: String,
    /// Ask the Test environment's layout and accounts instead of Live's.
    pub test_mode: bool,
}

impl CheckoutMethodsAvailabilityParams {
    /// A Live question for a buyer in `country` paying `amount` `currency`.
    pub fn new(country: impl Into<String>, amount: i64, currency: impl Into<String>) -> Self {
        Self {
            country: country.into(),
            amount,
            currency: currency.into(),
            test_mode: false,
        }
    }

    /// Ask the Test environment instead of Live.
    #[must_use]
    pub fn test_mode(mut self, test_mode: bool) -> Self {
        self.test_mode = test_mode;
        self
    }
}

/// Query of [`CheckoutMethods::children`]. `currency` and `amount` go
/// together.
#[derive(Debug, Clone, Default)]
pub struct CheckoutMethodsChildrenParams {
    /// Which checkout to read. Live by default.
    pub environment: CheckoutEnvironment,
    /// The buyer's country, ISO 3166-1 alpha-2.
    pub country: Option<String>,
    /// ISO 4217 currency code.
    pub currency: Option<String>,
    /// The order value, in minor units of `currency`.
    pub amount: Option<i64>,
}

impl CheckoutMethodsChildrenParams {
    /// No order context, Live checkout.
    pub fn new() -> Self {
        Self::default()
    }

    /// Read the given checkout.
    #[must_use]
    pub fn environment(mut self, environment: CheckoutEnvironment) -> Self {
        self.environment = environment;
        self
    }

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

    /// The order: `amount` in minor units of `currency`.
    #[must_use]
    pub fn order(mut self, amount: i64, currency: impl Into<String>) -> Self {
        self.amount = Some(amount);
        self.currency = Some(currency.into());
        self
    }
}

/// Body of [`CheckoutMethods::update_entries`]: replaces every entry of one
/// environment.
#[derive(Debug, Clone, Default, Serialize)]
pub struct CheckoutEntriesUpdateRequest {
    /// The entries, as [`CheckoutMethods::entries`] returns them.
    pub entries: Vec<CheckoutEntry>,
    /// Any additional fields, merged verbatim.
    #[serde(flatten, skip_serializing_if = "serde_json::Map::is_empty")]
    pub extra: serde_json::Map<String, Value>,
}

impl CheckoutEntriesUpdateRequest {
    /// A request replacing the entries with `entries`.
    pub fn new(entries: Vec<CheckoutEntry>) -> Self {
        Self {
            entries,
            extra: serde_json::Map::new(),
        }
    }
}

/// Names of `CheckoutEntriesUpdateRequest`'s fields as they appear on the
/// wire (`extra` excluded).
const CHECKOUT_ENTRIES_UPDATE_REQUEST_NAMED: &[&str] = &["entries"];

/// Names of [`CheckoutEntry`]'s fields as they appear on the wire (`extra`
/// excluded).
const CHECKOUT_ENTRY_NAMED: &[&str] = &["key", "label", "kind", "methods", "theme", "other_entry"];

/// Names of [`crate::CheckoutEntryMethod`]'s fields as they appear on the wire
/// (`extra` excluded).
const CHECKOUT_ENTRY_METHOD_NAMED: &[&str] =
    &["kind", "group_id", "connector", "method", "capability"];

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

impl ValidateRequest for CheckoutEntriesUpdateRequest {
    fn validate(&self) -> Result<()> {
        reject_collisions(
            &self.extra,
            CHECKOUT_ENTRIES_UPDATE_REQUEST_NAMED,
            "CheckoutEntriesUpdateRequest",
        )?;
        // Entries round-trip the fields they were read with, so a nested
        // collision is the same duplicate-key hazard one level down.
        for entry in &self.entries {
            reject_collisions(&entry.extra, CHECKOUT_ENTRY_NAMED, "CheckoutEntry")?;
            for method in &entry.methods {
                reject_collisions(
                    &method.extra,
                    CHECKOUT_ENTRY_METHOD_NAMED,
                    "CheckoutEntryMethod",
                )?;
            }
        }
        Ok(())
    }
}

/// Body of [`CheckoutMethods::test_redirect_rules`]: the rules to try and the
/// buyer to try them for.
#[derive(Debug, Clone, Default, Serialize)]
pub struct CheckoutRedirectRulesTestRequest {
    /// The redirect rules, saved or not, in the shape the layout stores them.
    pub rules: Value,
    /// The buyer's country, ISO 3166-1 alpha-2.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub country: Option<String>,
    /// ISO 4217 currency code.
    pub currency: String,
    /// The order value, in minor units of `currency`.
    pub amount: i64,
    /// The buyer's device, e.g. `mobile`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub device: Option<String>,
    /// The payment's metadata, as text values.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub metadata: Option<std::collections::BTreeMap<String, String>>,
    /// Cap states to try instead of the live ones, by account id.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cap_states: Option<serde_json::Map<String, Value>>,
    /// Health states to try instead of the stored ones, by account id.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub health_states: Option<serde_json::Map<String, Value>>,
    /// Any additional fields, merged verbatim.
    #[serde(flatten, skip_serializing_if = "serde_json::Map::is_empty")]
    pub extra: serde_json::Map<String, Value>,
}

impl CheckoutRedirectRulesTestRequest {
    /// Try `rules` for a buyer paying `amount` `currency`.
    pub fn new(rules: Value, amount: i64, currency: impl Into<String>) -> Self {
        Self {
            rules,
            amount,
            currency: currency.into(),
            ..Default::default()
        }
    }

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

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

    /// The payment's metadata.
    #[must_use]
    pub fn metadata(mut self, metadata: std::collections::BTreeMap<String, String>) -> Self {
        self.metadata = Some(metadata);
        self
    }

    /// Cap states to try, by account id.
    #[must_use]
    pub fn cap_states(mut self, cap_states: serde_json::Map<String, Value>) -> Self {
        self.cap_states = Some(cap_states);
        self
    }

    /// Health states to try, by account id.
    #[must_use]
    pub fn health_states(mut self, health_states: serde_json::Map<String, Value>) -> Self {
        self.health_states = Some(health_states);
        self
    }
}

/// Names of `CheckoutRedirectRulesTestRequest`'s fields as they appear on the
/// wire (`extra` excluded).
const CHECKOUT_REDIRECT_RULES_TEST_REQUEST_NAMED: &[&str] = &[
    "rules",
    "country",
    "currency",
    "amount",
    "device",
    "metadata",
    "cap_states",
    "health_states",
];

impl ValidateRequest for CheckoutRedirectRulesTestRequest {
    fn validate(&self) -> Result<()> {
        reject_collisions(
            &self.extra,
            CHECKOUT_REDIRECT_RULES_TEST_REQUEST_NAMED,
            "CheckoutRedirectRulesTestRequest",
        )
    }
}

/// Body of [`CheckoutMethods::set_account_visibility`].
///
/// The API refuses unknown fields here, so there is no `extra` map.
#[derive(Debug, Clone, Serialize)]
pub struct CheckoutAccountVisibilityRequest {
    /// `true` hides the account from the named environments' checkouts,
    /// `false` shows it again.
    pub hidden: bool,
    /// The environments to change, at least one. The others keep theirs.
    pub environments: Vec<CheckoutEnvironment>,
    /// Why, for the audit log.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub reason: Option<String>,
}

impl CheckoutAccountVisibilityRequest {
    /// Hide (`true`) or show (`false`) the account in `environments`.
    pub fn new(hidden: bool, environments: Vec<CheckoutEnvironment>) -> Self {
        Self {
            hidden,
            environments,
            reason: None,
        }
    }

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

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

    const METHODS_JSON: &str = r#"{
        "profile_id": "pro_1",
        "source": "stored",
        "layout": {"express": [], "normal": [{"kind": "card"}], "alternative": []},
        "available": [{
            "kind": "card",
            "default_label": "Card",
            "default_category": "normal",
            "supports_native_element": true,
            "supports_open_target": false,
            "account_enabled": true,
            "accounts": [{"merchant_connector_id": "mca_1"}]
        }],
        "modified_at": "2026-01-01T00:00:00Z",
        "test_mode": false,
        "hidden_accounts": ["mca_2"],
        "surprise_field": 1
    }"#;

    #[tokio::test]
    async fn retrieve_gets_the_live_layout_with_the_merchant_scope() {
        let (client, mock) = client_with(vec![Step::ok(METHODS_JSON)]);
        let out = client
            .checkout_methods()
            .retrieve("mer_1", "pro/1", CheckoutEnvironment::Live)
            .await
            .unwrap();
        assert_eq!(out.profile_id, "pro_1");
        assert_eq!(out.source, "stored");
        assert_eq!(out.layout["normal"][0]["kind"], "card");
        assert_eq!(out.available[0].default_category, "normal");
        assert!(out.available[0].supports_native_element);
        assert_eq!(
            out.available[0].extra["accounts"][0]["merchant_connector_id"],
            "mca_1"
        );
        assert_eq!(out.hidden_accounts, ["mca_2"]);
        assert_eq!(out.extra["surprise_field"], 1);

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "GET");
        assert_eq!(
            seen[0].url,
            "https://api.test/checkout-methods/pro%2F1?merchant_id=mer_1"
        );
    }

    #[tokio::test]
    async fn update_puts_the_test_layout() {
        let (client, mock) = client_with(vec![Step::ok(METHODS_JSON)]);
        let layout = json!({"express": [], "normal": [{"kind": "card"}], "alternative": []});
        client
            .checkout_methods()
            .update(
                "mer_1",
                "pro_1",
                &CheckoutMethodsUpdateRequest::new(layout.clone()),
                CheckoutEnvironment::Test,
            )
            .await
            .unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "PUT");
        assert_eq!(
            seen[0].url,
            "https://api.test/checkout-methods/pro_1/test?merchant_id=mer_1"
        );
        assert_eq!(seen[0].body_json(), json!({ "layout": layout }));
    }

    #[tokio::test]
    async fn reset_deletes_the_live_layout() {
        let (client, mock) = client_with(vec![Step::ok(
            r#"{"profile_id":"pro_1","deleted":true,"surprise_field":"x"}"#,
        )]);
        let out = client
            .checkout_methods()
            .reset("mer_1", "pro_1", CheckoutEnvironment::Live)
            .await
            .unwrap();
        assert!(out.deleted);
        assert_eq!(out.extra["surprise_field"], "x");

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "DELETE");
        assert_eq!(
            seen[0].url,
            "https://api.test/checkout-methods/pro_1?merchant_id=mer_1"
        );
        assert!(seen[0].body.is_none());
    }

    const AVAILABILITY_JSON: &str = r#"{
        "profile_id": "pro_1",
        "country": "DE",
        "amount": 1999,
        "currency": "EUR",
        "country_defaults_enabled": true,
        "items": [{"kind": "method", "connector": "mollie", "method": "ideal", "hidden_by": ["country_default"]}],
        "smart_blocks": [],
        "surprise_field": true
    }"#;

    #[tokio::test]
    async fn availability_asks_live_with_the_buyer_query() {
        let (client, mock) = client_with(vec![Step::ok(AVAILABILITY_JSON)]);
        let out = client
            .checkout_methods()
            .availability(
                "mer_1",
                "pro_1",
                &CheckoutMethodsAvailabilityParams::new("DE", 1999, "EUR"),
            )
            .await
            .unwrap();
        assert_eq!(out.amount, 1999);
        assert_eq!(out.items[0].hidden_by, ["country_default"]);
        assert_eq!(out.items[0].method.as_deref(), Some("ideal"));
        assert_eq!(out.extra["surprise_field"], true);

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "GET");
        assert_eq!(
            seen[0].url,
            "https://api.test/checkout-methods/pro_1/availability?merchant_id=mer_1&country=DE&amount=1999&currency=EUR"
        );
    }

    #[tokio::test]
    async fn availability_in_test_mode_asks_the_test_path() {
        let (client, mock) = client_with(vec![Step::ok(AVAILABILITY_JSON)]);
        client
            .checkout_methods()
            .availability(
                "mer_1",
                "pro_1",
                &CheckoutMethodsAvailabilityParams::new("DE", 1999, "EUR").test_mode(true),
            )
            .await
            .unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(
            seen[0].url,
            "https://api.test/checkout-methods/pro_1/test/availability?merchant_id=mer_1&country=DE&amount=1999&currency=EUR"
        );
    }

    const CHILDREN_JSON: &str = r#"{
        "profile_id": "pro_1",
        "test_mode": false,
        "items": [{
            "kind": "card",
            "status": "confirmed",
            "stale": false,
            "complete": true,
            "children": [{"id": "card_network:visa", "kind": "card_network"}],
            "declarable": []
        }],
        "surprise_field": 2
    }"#;

    #[tokio::test]
    async fn children_without_an_order_sends_only_the_merchant_scope() {
        let (client, mock) = client_with(vec![Step::ok(CHILDREN_JSON)]);
        let out = client
            .checkout_methods()
            .children("mer_1", "pro_1", &CheckoutMethodsChildrenParams::new())
            .await
            .unwrap();
        assert_eq!(out.items[0].status, "confirmed");
        assert_eq!(out.items[0].children[0].id, "card_network:visa");
        assert!(out.items[0].complete);
        assert_eq!(out.extra["surprise_field"], 2);

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "GET");
        assert_eq!(
            seen[0].url,
            "https://api.test/checkout-methods/pro_1/children?merchant_id=mer_1"
        );
    }

    #[tokio::test]
    async fn children_for_test_with_an_order_asks_the_test_path() {
        let (client, mock) = client_with(vec![Step::ok(CHILDREN_JSON)]);
        let params = CheckoutMethodsChildrenParams::new()
            .environment(CheckoutEnvironment::Test)
            .country("NL")
            .order(500, "EUR");
        client
            .checkout_methods()
            .children("mer_1", "pro_1", &params)
            .await
            .unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(
            seen[0].url,
            "https://api.test/checkout-methods/pro_1/test/children?merchant_id=mer_1&country=NL&currency=EUR&amount=500"
        );
    }

    #[tokio::test]
    async fn set_account_visibility_puts_the_account_path() {
        let (client, mock) = client_with(vec![Step::ok(
            r#"{"merchant_connector_id":"mca_1","hidden_live":true,"hidden_test":false,"surprise_field":0}"#,
        )]);
        let params = CheckoutAccountVisibilityRequest::new(true, vec![CheckoutEnvironment::Live])
            .reason("paused");
        let out = client
            .checkout_methods()
            .set_account_visibility("mer_1", "pro_1", "mca/1", &params)
            .await
            .unwrap();
        assert!(out.hidden_live);
        assert!(!out.hidden_test);
        assert_eq!(out.extra["surprise_field"], 0);

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "PUT");
        assert_eq!(
            seen[0].url,
            "https://api.test/checkout-methods/pro_1/accounts/mca%2F1/visibility?merchant_id=mer_1"
        );
        assert_eq!(
            seen[0].body_json(),
            json!({"hidden": true, "environments": ["live"], "reason": "paused"})
        );
    }

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

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

    #[tokio::test]
    async fn preview_gets_the_test_preview_path() {
        let (client, mock) = client_with(vec![Step::ok(METHODS_JSON)]);
        let out = client
            .checkout_methods()
            .preview("mer_1", "pro_1", CheckoutEnvironment::Test)
            .await
            .unwrap();
        assert_eq!(out.profile_id, "pro_1");
        assert_eq!(out.extra["surprise_field"], 1);

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "GET");
        assert_eq!(
            seen[0].url,
            "https://api.test/checkout-methods/pro_1/test/preview?merchant_id=mer_1"
        );
    }

    #[tokio::test]
    async fn payment_method_options_gets_the_live_path() {
        let (client, mock) = client_with(vec![Step::ok(
            r#"{"profile_id":"pro_1","test_mode":false,"options":[
                {"payment_method":"card","payment_method_types":["credit","debit"],
                 "option_surprise":true}],"surprise_field":1}"#,
        )]);
        let out = client
            .checkout_methods()
            .payment_method_options("mer_1", "pro/1", CheckoutEnvironment::Live)
            .await
            .unwrap();
        assert!(!out.test_mode);
        assert_eq!(out.options[0].payment_method, "card");
        assert_eq!(out.options[0].payment_method_types, ["credit", "debit"]);
        assert_eq!(out.options[0].extra["option_surprise"], true);
        assert_eq!(out.extra["surprise_field"], 1);

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "GET");
        assert_eq!(
            seen[0].url,
            "https://api.test/checkout-methods/pro%2F1/payment-method-options?merchant_id=mer_1"
        );
    }

    #[tokio::test]
    async fn test_redirect_rules_posts_the_rules_and_the_buyer() {
        let (client, mock) = client_with(vec![Step::ok(
            r#"{"decision":{"kind":"redirect"},"rules":[{"matched":true}],
                "offered":[],"accounts":[],"surprise_field":1}"#,
        )]);
        let mut metadata = std::collections::BTreeMap::new();
        metadata.insert("channel".to_string(), "web".to_string());
        let params = CheckoutRedirectRulesTestRequest::new(json!({"rules": []}), 1999, "EUR")
            .country("DE")
            .device("mobile")
            .metadata(metadata);
        let out = client
            .checkout_methods()
            .test_redirect_rules("mer_1", "pro_1", &params, CheckoutEnvironment::Test)
            .await
            .unwrap();
        assert_eq!(out.decision.as_ref().unwrap()["kind"], "redirect");
        assert_eq!(out.rules[0]["matched"], true);
        assert_eq!(out.extra["surprise_field"], 1);

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(
            seen[0].url,
            "https://api.test/checkout-methods/pro_1/test/redirect-rules/test?merchant_id=mer_1"
        );
        assert_eq!(
            seen[0].body_json(),
            json!({
                "rules": {"rules": []},
                "country": "DE",
                "currency": "EUR",
                "amount": 1999,
                "device": "mobile",
                "metadata": {"channel": "web"}
            })
        );
        assert!(!seen[0].had_idempotency_key());
    }

    const ENTRIES_JSON: &str = r#"{
        "profile_id": "pro_1",
        "test_mode": false,
        "entries": [{
            "key": "crypto", "label": "Pay with crypto", "kind": "methods",
            "methods": [{"kind": "method", "connector": "cryptomus", "method": "crypto"}],
            "theme": "dark", "entry_surprise": 1
        }],
        "modified_at": "2026-11-01T00:00:00Z",
        "surprise_field": 1
    }"#;

    #[tokio::test]
    async fn entries_gets_the_live_entries_path() {
        let (client, mock) = client_with(vec![Step::ok(ENTRIES_JSON)]);
        let out = client
            .checkout_methods()
            .entries("mer_1", "pro_1", CheckoutEnvironment::Live)
            .await
            .unwrap();
        assert_eq!(out.entries[0].key, "crypto");
        assert_eq!(
            out.entries[0].methods[0].connector.as_deref(),
            Some("cryptomus")
        );
        assert_eq!(out.entries[0].extra["entry_surprise"], 1);
        assert_eq!(out.extra["surprise_field"], 1);

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "GET");
        assert_eq!(
            seen[0].url,
            "https://api.test/checkout-methods/pro_1/entries?merchant_id=mer_1"
        );
    }

    /// An entry read back keeps its unknown fields and is sent again with
    /// them. Mutation: drop the `extra` flatten on `CheckoutEntry` — the
    /// round-tripped `entry_surprise` disappears from the body.
    #[tokio::test]
    async fn update_entries_puts_the_test_entries_and_round_trips_unknown_fields() {
        let (client, mock) = client_with(vec![Step::ok(ENTRIES_JSON), Step::ok(ENTRIES_JSON)]);
        let read = client
            .checkout_methods()
            .entries("mer_1", "pro_1", CheckoutEnvironment::Live)
            .await
            .unwrap();
        let mut entries = read.entries;
        entries.push(
            CheckoutEntry::new("card", "Card form")
                .kind("card")
                .other_entry("crypto"),
        );
        let params = CheckoutEntriesUpdateRequest::new(entries);
        client
            .checkout_methods()
            .update_entries("mer_1", "pro_1", &params, CheckoutEnvironment::Test)
            .await
            .unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[1].method, "PUT");
        assert_eq!(
            seen[1].url,
            "https://api.test/checkout-methods/pro_1/test/entries?merchant_id=mer_1"
        );
        assert_eq!(
            seen[1].body_json(),
            json!({"entries": [
                {"key": "crypto", "label": "Pay with crypto", "kind": "methods",
                 "methods": [{"kind": "method", "connector": "cryptomus", "method": "crypto"}],
                 "theme": "dark", "entry_surprise": 1},
                {"key": "card", "label": "Card form", "kind": "card", "other_entry": "crypto"}
            ]})
        );
    }

    #[tokio::test]
    async fn clear_entries_deletes_the_test_entries() {
        let (client, mock) = client_with(vec![Step::ok(
            r#"{"profile_id":"pro_1","test_mode":true,"entries":[],"surprise_field":1}"#,
        )]);
        let out = client
            .checkout_methods()
            .clear_entries("mer_1", "pro_1", CheckoutEnvironment::Test)
            .await
            .unwrap();
        assert!(out.test_mode);
        assert!(out.entries.is_empty());
        assert_eq!(out.extra["surprise_field"], 1);

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "DELETE");
        assert_eq!(
            seen[0].url,
            "https://api.test/checkout-methods/pro_1/test/entries?merchant_id=mer_1"
        );
    }

    #[test]
    fn entries_validate_rejects_a_nested_colliding_extra_key() {
        let mut method = CheckoutEntryMethod::provider_method("stripe", "apple_pay");
        method.extra.insert("method".to_string(), json!("other"));
        let req = CheckoutEntriesUpdateRequest::new(vec![
            CheckoutEntry::new("e1", "Entry")
                .kind("methods")
                .method(method),
        ]);
        match req.validate().unwrap_err() {
            DelopayError::InvalidRequest(msg) => assert!(msg.contains("CheckoutEntryMethod")),
            other => panic!("expected InvalidRequest, got {other:?}"),
        }

        let mut entry = CheckoutEntry::new("e1", "Entry");
        entry.extra.insert("label".to_string(), json!("other"));
        match CheckoutEntriesUpdateRequest::new(vec![entry])
            .validate()
            .unwrap_err()
        {
            DelopayError::InvalidRequest(msg) => assert!(msg.contains("`label`")),
            other => panic!("expected InvalidRequest, got {other:?}"),
        }
    }

    #[test]
    fn redirect_rules_validate_rejects_a_colliding_extra_key() {
        let mut req = CheckoutRedirectRulesTestRequest::new(json!({}), 1, "EUR");
        req.extra.insert("amount".to_string(), json!(2));
        match req.validate().unwrap_err() {
            DelopayError::InvalidRequest(msg) => assert!(msg.contains("amount")),
            other => panic!("expected InvalidRequest, got {other:?}"),
        }
    }

    /// Drift guards for the entry and redirect-rule `*_NAMED` lists.
    #[test]
    fn entry_and_redirect_rule_named_fields_are_complete() {
        fn assert_covered(value: Value, named: &[&str], list: &str) {
            for key in value.as_object().expect("serializes to an object").keys() {
                assert!(
                    named.contains(&key.as_str()),
                    "{list} is missing wire key `{key}`"
                );
            }
        }
        let method = CheckoutEntryMethod {
            kind: Some("method".to_string()),
            group_id: Some("g".to_string()),
            connector: Some("stripe".to_string()),
            method: Some("apple_pay".to_string()),
            capability: Some("wallet.apple_pay".to_string()),
            extra: serde_json::Map::new(),
        };
        assert_covered(
            serde_json::to_value(&method).unwrap(),
            CHECKOUT_ENTRY_METHOD_NAMED,
            "CHECKOUT_ENTRY_METHOD_NAMED",
        );
        let entry = CheckoutEntry::new("k", "l")
            .kind("methods")
            .method(method)
            .theme("dark")
            .other_entry("o");
        assert_covered(
            serde_json::to_value(&entry).unwrap(),
            CHECKOUT_ENTRY_NAMED,
            "CHECKOUT_ENTRY_NAMED",
        );
        assert_covered(
            serde_json::to_value(CheckoutEntriesUpdateRequest::new(vec![entry])).unwrap(),
            CHECKOUT_ENTRIES_UPDATE_REQUEST_NAMED,
            "CHECKOUT_ENTRIES_UPDATE_REQUEST_NAMED",
        );
        let mut cap_states = serde_json::Map::new();
        cap_states.insert("mca_1".to_string(), json!("exhausted"));
        let mut metadata = std::collections::BTreeMap::new();
        metadata.insert("a".to_string(), "b".to_string());
        let rules = CheckoutRedirectRulesTestRequest::new(json!({}), 1, "EUR")
            .country("DE")
            .device("mobile")
            .metadata(metadata)
            .cap_states(cap_states.clone())
            .health_states(cap_states);
        assert_covered(
            serde_json::to_value(rules).unwrap(),
            CHECKOUT_REDIRECT_RULES_TEST_REQUEST_NAMED,
            "CHECKOUT_REDIRECT_RULES_TEST_REQUEST_NAMED",
        );
    }

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

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

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