delopay 0.20.0

Official Rust SDK for the DeloPay payments API
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
//! The `shops` resource: business profiles inside a merchant account.
//!
//! Each shop can have its own gateway connections, routing rules and fee
//! schedules. Gateway management hangs off [`Shops::gateways`].

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::profile::CheckoutBrandingResponse;
use crate::core::models::shop::{
    GatewayResponse, ProfileLogoUploadResponse, ShopResponse, ShopStatsResponse,
};
use crate::http::client::Inner;
use crate::http::multipart::{FilePart, encode_file};
use crate::http::transport::HttpMethod;
use crate::resources::ValidateRequest;
use crate::resources::projects::StatsPeriod;

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

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

    /// Gateway connection management for shops.
    pub fn gateways(&self) -> ShopGateways {
        ShopGateways::new(self.inner.clone())
    }

    /// Create a shop under a merchant account.
    pub async fn create(
        &self,
        merchant_id: &str,
        params: &ShopCreateRequest,
    ) -> Result<ShopResponse> {
        params.validate()?;
        let path = format!("/shops/{}", encode_segment(merchant_id));
        let body = to_json_vec(params)?;
        self.inner
            .request(HttpMethod::Post, &path, Some(&body), &[], None)
            .await
    }

    /// Retrieve a shop by ID.
    pub async fn retrieve(&self, merchant_id: &str, shop_id: &str) -> Result<ShopResponse> {
        let path = shop_path(merchant_id, shop_id);
        self.inner
            .request(HttpMethod::Get, &path, None, &[], None)
            .await
    }

    /// Update a shop's configuration.
    pub async fn update(
        &self,
        merchant_id: &str,
        shop_id: &str,
        params: &ShopUpdateRequest,
    ) -> Result<ShopResponse> {
        params.validate()?;
        let path = shop_path(merchant_id, shop_id);
        let body = to_json_vec(params)?;
        self.inner
            .request(HttpMethod::Put, &path, Some(&body), &[], None)
            .await
    }

    /// Delete a shop.
    pub async fn delete(&self, merchant_id: &str, shop_id: &str) -> Result<ShopResponse> {
        let path = shop_path(merchant_id, shop_id);
        self.inner
            .request(HttpMethod::Delete, &path, None, &[], None)
            .await
    }

    /// List all shops under a merchant account.
    pub async fn list(&self, merchant_id: &str) -> Result<Vec<ShopResponse>> {
        let path = format!("/shops/{}", encode_segment(merchant_id));
        self.inner
            .request(HttpMethod::Get, &path, None, &[], None)
            .await
    }

    /// Successful-order count and revenue for one shop.
    ///
    /// Unlike [`Projects::stats`](crate::resources::projects::Projects::stats)
    /// this needs only `ProfileAccountRead`, so a shop-scoped user can load it
    /// for their own shop.
    ///
    /// Revenue comes back FX-converted as `revenue_usd` (USD major units) plus
    /// a `revenue_by_currency` breakdown. The legacy `revenue` field is a raw
    /// cross-currency minor-unit sum and should not be displayed.
    ///
    /// `period` omitted means the server default of 30 days.
    pub async fn stats(
        &self,
        merchant_id: &str,
        shop_id: &str,
        period: Option<StatsPeriod>,
    ) -> Result<ShopStatsResponse> {
        let path = format!("{}/stats", shop_path(merchant_id, shop_id));
        let query = match period {
            Some(p) => vec![("period", p.to_query_value())],
            None => Vec::new(),
        };
        self.inner
            .request(HttpMethod::Get, &path, None, &query, None)
            .await
    }

    /// Restyle a shop's hosted checkout.
    ///
    /// `payment_link_config` is replaced **whole**, not merged: send the
    /// complete configuration, or the fields you leave out are cleared. Build
    /// it with [`crate::branding::encode_branding`] rather than by hand.
    ///
    /// Answers with the branding it saved — the same shape
    /// [`Self::retrieve_checkout_branding`] returns, not the whole shop. A role
    /// whose only power is restyling a checkout must not receive the webhook
    /// signing key or the card-vault configuration back from a save.
    ///
    /// `POST /shops/{merchant_id}/{shop_id}/checkout-branding`
    pub async fn update_checkout_branding(
        &self,
        merchant_id: &str,
        shop_id: &str,
        payment_link_config: &Value,
    ) -> Result<CheckoutBrandingResponse> {
        let path = format!("{}/checkout-branding", shop_path(merchant_id, shop_id));
        let body = to_json_vec(&CheckoutBrandingUpdate {
            payment_link_config,
        })?;
        self.inner
            .request(HttpMethod::Post, &path, Some(&body), &[], None)
            .await
    }

    /// Read a shop's checkout appearance, so the role that may restyle a
    /// checkout can load the checkout it may restyle.
    ///
    /// Prefer this over [`Self::retrieve`] for a branding editor: that one
    /// answers with the whole shop, including the webhook signing key and the
    /// card-vault configuration, and needs the shop-read permission for exactly
    /// that reason.
    ///
    /// `GET /shops/{merchant_id}/{shop_id}/checkout-branding`
    pub async fn retrieve_checkout_branding(
        &self,
        merchant_id: &str,
        shop_id: &str,
    ) -> Result<CheckoutBrandingResponse> {
        let path = format!("{}/checkout-branding", shop_path(merchant_id, shop_id));
        self.inner
            .request(HttpMethod::Get, &path, None, &[], None)
            .await
    }

    /// Read the appearance of the shop's Test checkout: the checkout of a
    /// payment created with `test_mode: true`. Until its first save, Test
    /// follows Live: `follows_live` is `true` and `payment_link_config` is
    /// Live's.
    ///
    /// `GET /shops/{merchant_id}/{shop_id}/checkout-branding/test`
    pub async fn retrieve_test_checkout_branding(
        &self,
        merchant_id: &str,
        shop_id: &str,
    ) -> Result<CheckoutBrandingResponse> {
        let path = format!("{}/checkout-branding/test", shop_path(merchant_id, shop_id));
        self.inner
            .request(HttpMethod::Get, &path, None, &[], None)
            .await
    }

    /// Replace the Test checkout's appearance, exactly as
    /// [`Self::update_checkout_branding`] replaces Live's. Live is not
    /// touched; a shop whose Test followed Live has its own Test settings
    /// from this save on.
    ///
    /// `POST /shops/{merchant_id}/{shop_id}/checkout-branding/test`
    pub async fn update_test_checkout_branding(
        &self,
        merchant_id: &str,
        shop_id: &str,
        payment_link_config: &Value,
    ) -> Result<CheckoutBrandingResponse> {
        let path = format!("{}/checkout-branding/test", shop_path(merchant_id, shop_id));
        let body = to_json_vec(&CheckoutBrandingUpdate {
            payment_link_config,
        })?;
        self.inner
            .request_body_keyed(HttpMethod::Post, &path, Some(&body), None)
            .await
    }

    /// Upload a shop logo. `POST /shops/{merchant_id}/{shop_id}/logo`
    ///
    /// The only `multipart/form-data` endpoint in the API. `bytes` is the
    /// whole image, held in memory — logos are small, and streaming would
    /// change the transport contract for one call.
    ///
    /// `content_type` is the image's own MIME type (`image/png`,
    /// `image/svg+xml`, …). The response carries the hosted URL, which you
    /// then set as the checkout logo:
    ///
    /// ```no_run
    /// # use delopay::Delopay;
    /// # async fn run(client: &Delopay, png: &[u8]) -> delopay::Result<()> {
    /// let uploaded = client
    ///     .shops()
    ///     .upload_logo("mer_1", "pro_1", "logo.png", "image/png", png)
    ///     .await?;
    /// let logo_url = uploaded.logo_url;
    /// # let _ = logo_url;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn upload_logo(
        &self,
        merchant_id: &str,
        shop_id: &str,
        file_name: &str,
        content_type: &str,
        bytes: &[u8],
    ) -> Result<ProfileLogoUploadResponse> {
        let path = format!("{}/logo", shop_path(merchant_id, shop_id));
        let form = encode_file(&FilePart {
            field: "file",
            file_name,
            content_type,
            bytes,
        });
        self.inner
            .request_with_content_type(HttpMethod::Post, &path, &form.body, &form.content_type)
            .await
    }
}

/// `/shops/{merchant_id}/{shop_id}`, both segments percent-encoded.
/// Body of [`Shops::update_checkout_branding`].
///
/// A borrowed wrapper rather than a public request struct: the endpoint takes
/// exactly one field, and its value is the branding blob the `branding`
/// module already builds.
#[derive(Debug, Serialize)]
struct CheckoutBrandingUpdate<'a> {
    payment_link_config: &'a Value,
}

fn shop_path(merchant_id: &str, shop_id: &str) -> String {
    format!(
        "/shops/{}/{}",
        encode_segment(merchant_id),
        encode_segment(shop_id)
    )
}

/// Gateway connections for a shop, obtained via [`Shops::gateways`].
#[derive(Debug, Clone)]
pub struct ShopGateways {
    inner: Arc<Inner>,
}

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

    /// Connect a payment gateway to a shop.
    pub async fn connect(
        &self,
        merchant_id: &str,
        shop_id: &str,
        params: &GatewayConnectRequest,
    ) -> Result<GatewayResponse> {
        params.validate()?;
        let path = format!("{}/gateways", shop_path(merchant_id, shop_id));
        let body = to_json_vec(params)?;
        self.inner
            .request(HttpMethod::Post, &path, Some(&body), &[], None)
            .await
    }

    /// List all gateway connections for a shop.
    pub async fn list(&self, merchant_id: &str, shop_id: &str) -> Result<Vec<GatewayResponse>> {
        let path = format!("{}/gateways", shop_path(merchant_id, shop_id));
        self.inner
            .request(HttpMethod::Get, &path, None, &[], None)
            .await
    }

    /// Disconnect a gateway from a shop.
    pub async fn disconnect(
        &self,
        merchant_id: &str,
        shop_id: &str,
        gateway_id: &str,
    ) -> Result<GatewayResponse> {
        let path = format!(
            "{}/gateways/{}",
            shop_path(merchant_id, shop_id),
            encode_segment(gateway_id)
        );
        self.inner
            .request(HttpMethod::Delete, &path, None, &[], None)
            .await
    }
}

/// Parameters for [`Shops::create`].
#[derive(Debug, Clone, Default, Serialize)]
pub struct ShopCreateRequest {
    /// Display name of the shop.
    pub shop_name: String,
    /// URL customers are returned to after checkout.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub return_url: Option<String>,
    /// URL webhooks for this shop are delivered to.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub webhook_url: Option<String>,
    /// Project this shop belongs to, if any.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub project_id: Option<String>,
    /// Any additional fields, merged verbatim.
    #[serde(flatten, skip_serializing_if = "serde_json::Map::is_empty")]
    pub extra: serde_json::Map<String, Value>,
}

impl ShopCreateRequest {
    /// A create request for a shop with the given name.
    pub fn new(shop_name: impl Into<String>) -> Self {
        Self {
            shop_name: shop_name.into(),
            ..Default::default()
        }
    }

    /// Set the shop's return URL.
    #[must_use]
    pub fn return_url(mut self, return_url: impl Into<String>) -> Self {
        self.return_url = Some(return_url.into());
        self
    }

    /// Set the shop's webhook URL.
    #[must_use]
    pub fn webhook_url(mut self, webhook_url: impl Into<String>) -> Self {
        self.webhook_url = Some(webhook_url.into());
        self
    }

    /// Put the shop in a project.
    #[must_use]
    pub fn project_id(mut self, project_id: impl Into<String>) -> Self {
        self.project_id = Some(project_id.into());
        self
    }
}

/// Names of `ShopCreateRequest`'s fields as they appear on the wire
/// (`extra` excluded).
const SHOP_CREATE_REQUEST_NAMED: &[&str] =
    &["shop_name", "return_url", "webhook_url", "project_id"];

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

/// Parameters for [`Shops::update`]. Only the fields you set are sent.
///
/// `Debug` is hand-written: [`payment_response_hash_key`](Self::payment_response_hash_key)
/// is a webhook signing secret and is redacted.
#[derive(Clone, Default, Serialize)]
pub struct ShopUpdateRequest {
    /// New display name.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub shop_name: Option<String>,
    /// New return URL.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub return_url: Option<String>,
    /// New webhook URL.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub webhook_url: Option<String>,
    /// Whether the shop is active.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub is_active: Option<bool>,
    /// Webhook signing secret for this shop. Outgoing webhooks are HMAC-SHA512
    /// signed with this key, so it is redacted from `Debug` output.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub payment_response_hash_key: Option<String>,
    /// Branding and behavior overrides for the hosted checkout (open shape —
    /// see the API reference).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub payment_link_config: Option<Value>,
    /// Origins permitted to embed this shop's hosted checkout in an iframe.
    /// Each entry must be a full origin (`scheme://host[:port]`, no path, no
    /// wildcards). Empty defaults to same-origin only.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub iframe_allowed_origins: Option<Vec<String>>,
    /// Custom format for generated payment IDs, e.g. `ORD-74219807` (open
    /// shape — see the API reference). Absent means default `pay_<random>`
    /// IDs.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub payment_id_format: Option<Value>,
    /// Custom format for generated product IDs, in the shape of
    /// `payment_id_format`. Absent keeps the stored format.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub product_id_format: Option<Value>,
    /// Any additional fields, merged verbatim.
    #[serde(flatten, skip_serializing_if = "serde_json::Map::is_empty")]
    pub extra: serde_json::Map<String, Value>,
}

// Hand-written rather than derived so the webhook signing secret cannot leak
// into logs via `{:?}`. Only its presence is reported.
impl std::fmt::Debug for ShopUpdateRequest {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ShopUpdateRequest")
            .field("shop_name", &self.shop_name)
            .field("return_url", &self.return_url)
            .field("webhook_url", &self.webhook_url)
            .field("is_active", &self.is_active)
            .field(
                "payment_response_hash_key",
                &self
                    .payment_response_hash_key
                    .as_ref()
                    .map(|_| "<redacted>"),
            )
            .field("payment_link_config", &self.payment_link_config)
            .field("iframe_allowed_origins", &self.iframe_allowed_origins)
            .field("payment_id_format", &self.payment_id_format)
            .field("product_id_format", &self.product_id_format)
            .field("extra", &self.extra)
            .finish()
    }
}

impl ShopUpdateRequest {
    /// An empty update; set the fields you want changed.
    pub fn new() -> Self {
        Self::default()
    }

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

    /// Set the shop's return URL.
    #[must_use]
    pub fn return_url(mut self, return_url: impl Into<String>) -> Self {
        self.return_url = Some(return_url.into());
        self
    }

    /// Set the shop's webhook URL.
    #[must_use]
    pub fn webhook_url(mut self, webhook_url: impl Into<String>) -> Self {
        self.webhook_url = Some(webhook_url.into());
        self
    }

    /// Activate or deactivate the shop.
    #[must_use]
    pub fn is_active(mut self, is_active: bool) -> Self {
        self.is_active = Some(is_active);
        self
    }

    /// Set the shop's webhook signing secret.
    #[must_use]
    pub fn payment_response_hash_key(mut self, key: impl Into<String>) -> Self {
        self.payment_response_hash_key = Some(key.into());
        self
    }

    /// Set the hosted-checkout branding config.
    #[must_use]
    pub fn payment_link_config(mut self, config: Value) -> Self {
        self.payment_link_config = Some(config);
        self
    }

    /// Set the origins allowed to iframe this shop's hosted checkout.
    #[must_use]
    pub fn iframe_allowed_origins(mut self, origins: Vec<String>) -> Self {
        self.iframe_allowed_origins = Some(origins);
        self
    }

    /// Set the custom payment-ID format.
    #[must_use]
    pub fn payment_id_format(mut self, format: Value) -> Self {
        self.payment_id_format = Some(format);
        self
    }

    /// Set the custom product-ID format.
    #[must_use]
    pub fn product_id_format(mut self, format: Value) -> Self {
        self.product_id_format = Some(format);
        self
    }
}

/// Names of `ShopUpdateRequest`'s fields as they appear on the wire
/// (`extra` excluded).
const SHOP_UPDATE_REQUEST_NAMED: &[&str] = &[
    "shop_name",
    "return_url",
    "webhook_url",
    "is_active",
    "payment_response_hash_key",
    "payment_link_config",
    "iframe_allowed_origins",
    "payment_id_format",
    "product_id_format",
];

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

/// Parameters for [`ShopGateways::connect`].
///
/// `Debug` is hand-written: the connector credential fields are redacted.
#[derive(Clone, Default, Serialize)]
pub struct GatewayConnectRequest {
    /// Connector category, e.g. `"payment_processor"`.
    pub connector_type: String,
    /// Connector identifier, e.g. `"stripe"`.
    pub connector_name: String,
    /// Your own label for this connection.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub connector_label: Option<String>,
    /// Shop (business profile) the connection belongs to.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub profile_id: Option<String>,
    /// Connector credentials (open shape — see the API reference). Redacted
    /// from `Debug` output.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub connector_account_details: Option<Value>,
    /// Payment methods to enable on this connector (open shape).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub payment_methods_enabled: Option<Vec<Value>>,
    /// Arbitrary key-value metadata.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub metadata: Option<Value>,
    /// Whether the connector runs against the PSP's test environment.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub test_mode: Option<bool>,
    /// Whether the connection starts disabled.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub disabled: Option<bool>,
    /// Connector webhook details, including signing secrets (open shape).
    /// Redacted from `Debug` output.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub connector_webhook_details: Option<Value>,
    /// Additional merchant data required by some connectors (open shape).
    /// Redacted from `Debug` output.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub additional_merchant_data: Option<Value>,
    /// Any additional fields, merged verbatim.
    #[serde(flatten, skip_serializing_if = "serde_json::Map::is_empty")]
    pub extra: serde_json::Map<String, Value>,
}

// Hand-written rather than derived: three of these fields carry PSP
// credentials and webhook signing secrets, which must never reach a log
// through `{:?}`. Only their presence is reported.
impl std::fmt::Debug for GatewayConnectRequest {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("GatewayConnectRequest")
            .field("connector_type", &self.connector_type)
            .field("connector_name", &self.connector_name)
            .field("connector_label", &self.connector_label)
            .field("profile_id", &self.profile_id)
            .field(
                "connector_account_details",
                &self
                    .connector_account_details
                    .as_ref()
                    .map(|_| "<redacted>"),
            )
            .field("payment_methods_enabled", &self.payment_methods_enabled)
            .field("metadata", &self.metadata)
            .field("test_mode", &self.test_mode)
            .field("disabled", &self.disabled)
            .field(
                "connector_webhook_details",
                &self
                    .connector_webhook_details
                    .as_ref()
                    .map(|_| "<redacted>"),
            )
            .field(
                "additional_merchant_data",
                &self.additional_merchant_data.as_ref().map(|_| "<redacted>"),
            )
            .field("extra", &self.extra)
            .finish()
    }
}

impl GatewayConnectRequest {
    /// A connect request for the given connector category and identifier,
    /// e.g. `("payment_processor", "stripe")`.
    pub fn new(connector_type: impl Into<String>, connector_name: impl Into<String>) -> Self {
        Self {
            connector_type: connector_type.into(),
            connector_name: connector_name.into(),
            ..Default::default()
        }
    }

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

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

    /// Set the connector credentials.
    #[must_use]
    pub fn connector_account_details(mut self, details: Value) -> Self {
        self.connector_account_details = Some(details);
        self
    }

    /// Set the payment methods to enable.
    #[must_use]
    pub fn payment_methods_enabled(mut self, methods: Vec<Value>) -> Self {
        self.payment_methods_enabled = Some(methods);
        self
    }

    /// Run this connector against the PSP's test environment.
    #[must_use]
    pub fn test_mode(mut self, test_mode: bool) -> Self {
        self.test_mode = Some(test_mode);
        self
    }
}

/// Names of `GatewayConnectRequest`'s fields as they appear on the wire
/// (`extra` excluded).
const GATEWAY_CONNECT_REQUEST_NAMED: &[&str] = &[
    "connector_type",
    "connector_name",
    "connector_label",
    "profile_id",
    "connector_account_details",
    "payment_methods_enabled",
    "metadata",
    "test_mode",
    "disabled",
    "connector_webhook_details",
    "additional_merchant_data",
];

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

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

    const SHOP_JSON: &str = r#"{
        "shop_id": "pro_1",
        "shop_name": "EU Store",
        "is_active": true,
        "created_at": "2024-01-01T00:00:00Z",
        "modified_at": "2024-01-02T00:00:00Z",
        "return_url": "https://acme.test/return",
        "webhook_url": "https://acme.test/hook",
        "project_id": "prj_1",
        "iframe_allowed_origins": ["https://shop.acme.com"],
        "payment_id_format": {"prefix": "ORD-", "style": "numeric", "length": 8},
        "product_id_format": {"prefix": "PRD-"},
        "surprise_field": 1
    }"#;

    #[tokio::test]
    async fn update_checkout_branding_posts_the_config_under_its_own_key() {
        let (client, mock) = client_with(vec![Step::ok(
            r##"{"profile_id":"pro_1","profile_name":"EU Store","payment_link_config":{"theme":"#0a0a0a"}}"##,
        )]);
        let config = json!({"theme": "#0a0a0a", "logo": "https://cdn.test/l.png"});
        let saved = client
            .shops()
            .update_checkout_branding("mer_1", "pro/1", &config)
            .await
            .unwrap();
        assert_eq!(saved.profile_id, "pro_1");
        assert_eq!(saved.profile_name, "EU Store");

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(
            seen[0].url,
            "https://api.test/shops/mer_1/pro%2F1/checkout-branding"
        );
        // Nested under `payment_link_config`, not spread at the top level —
        // the endpoint replaces that one field and would ignore a flat body.
        assert_eq!(seen[0].body_json()["payment_link_config"], config);
    }

    /// The save answers with the branding, not the shop.
    ///
    /// It used to deserialize into a `ProfileResponse`, which carries
    /// `payment_response_hash_key` — so a role whose only power is restyling a
    /// checkout was handed the webhook signing key back from every save. The
    /// narrow type is what makes that unreachable rather than merely absent
    /// from one payload.
    ///
    /// Mutation: give `CheckoutBrandingResponse` a `payment_response_hash_key`
    /// field, or point either branding method back at `ProfileResponse`, and
    /// this stops compiling.
    #[tokio::test]
    async fn a_branding_save_cannot_carry_the_signing_key() {
        let (client, _mock) = client_with(vec![Step::ok(
            r##"{
                "profile_id": "pro_1",
                "profile_name": "EU Store",
                "payment_link_config": {"theme": "#0a0a0a"},
                "payment_response_hash_key": "whsec_leak_me"
            }"##,
        )]);
        let saved = client
            .shops()
            .update_checkout_branding("mer_1", "pro_1", &json!({"theme": "#0a0a0a"}))
            .await
            .unwrap();

        // A key the type does not model lands in `extra`, where it is data
        // rather than a field an editor can reach for by name — and where
        // `Debug` redacts it, since `extra` is printed and a derived impl
        // would put the secret in a log. The redaction itself is pinned in
        // `core::models::profile`.
        assert_eq!(
            saved.extra.get("payment_response_hash_key"),
            Some(&Value::from("whsec_leak_me"))
        );
        assert!(!format!("{saved:?}").contains("whsec_leak_me"));
    }

    /// `None` is the shop nobody has styled, and it has to survive the round
    /// trip: an editor reads it as "seed my defaults", where a stored-but-empty
    /// style means "render this, it is deliberate".
    ///
    /// Mutation: default `payment_link_config` to `Some(Value::Null)` or to an
    /// empty object and this fails.
    #[tokio::test]
    async fn a_never_styled_shop_reads_back_as_none() {
        let (client, mock) = client_with(vec![Step::ok(
            r#"{"profile_id":"pro_1","profile_name":"EU Store","payment_link_config":null}"#,
        )]);
        let branding = client
            .shops()
            .retrieve_checkout_branding("mer_1", "pro/1")
            .await
            .unwrap();
        assert!(branding.payment_link_config.is_none());

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

    #[tokio::test]
    async fn retrieve_test_checkout_branding_gets_the_test_sub_path() {
        let (client, mock) = client_with(vec![Step::ok(
            r##"{"profile_id":"pro_1","profile_name":"EU Store","payment_link_config":{"theme":"#111111"},"test_mode":true,"follows_live":true,"surprise_field":1}"##,
        )]);
        let branding = client
            .shops()
            .retrieve_test_checkout_branding("mer_1", "pro/1")
            .await
            .unwrap();
        assert_eq!(branding.profile_id, "pro_1");
        assert_eq!(
            branding.payment_link_config,
            Some(json!({"theme": "#111111"}))
        );
        assert!(branding.test_mode);
        assert!(branding.follows_live);
        assert_eq!(branding.extra["surprise_field"], 1);

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

    #[tokio::test]
    async fn update_test_checkout_branding_posts_the_config_to_the_test_sub_path() {
        let (client, mock) = client_with(vec![Step::ok(
            r##"{"profile_id":"pro_1","profile_name":"EU Store","payment_link_config":{"theme":"#222222"},"test_mode":true,"follows_live":false}"##,
        )]);
        let config = json!({"theme": "#222222"});
        let saved = client
            .shops()
            .update_test_checkout_branding("mer/1", "pro_1", &config)
            .await
            .unwrap();
        assert!(saved.test_mode);
        assert!(!saved.follows_live);

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(
            seen[0].url,
            "https://api.test/shops/mer%2F1/pro_1/checkout-branding/test"
        );
        assert_eq!(
            seen[0].body_json(),
            json!({"payment_link_config": {"theme": "#222222"}})
        );
    }

    /// A shop payload that echoes the webhook signing secret back.
    const SHOP_WITH_SECRET_JSON: &str = r#"{
        "shop_id": "pro_1",
        "shop_name": "EU Store",
        "is_active": true,
        "created_at": "2024-01-01T00:00:00Z",
        "modified_at": "2024-01-02T00:00:00Z",
        "payment_response_hash_key": "whsec_response_leak_me"
    }"#;

    const GATEWAY_JSON: &str = r#"{
        "connector_type": "payment_processor",
        "connector_name": "stripe",
        "merchant_connector_id": "mca_1",
        "profile_id": "pro_1",
        "status": "active",
        "connector_label": "primary",
        "connector_account_details": {"api_key": "sk_live_response_leak_me"},
        "connector_webhook_details": {"merchant_secret": "whsec_response_leak_me"},
        "test_mode": false,
        "created_at": "2024-01-01T00:00:00Z"
    }"#;

    const SHOP_STATS_JSON: &str = r#"{
        "shop_id": "pro_1",
        "shop_name": "EU Store",
        "project_id": null,
        "orders": 4,
        "revenue": 5000,
        "revenue_usd": 54.5,
        "revenue_by_currency": [{"currency": "EUR", "amount_minor": 5000, "orders": 4}],
        "unconverted_orders": 1,
        "period_days": 90,
        "analytics_exclusions_active": true
    }"#;

    #[tokio::test]
    async fn create_posts_to_the_merchant_path() {
        let (client, mock) = client_with(vec![Step::ok(SHOP_JSON)]);
        let shop = client
            .shops()
            .create("merch_123", &ShopCreateRequest::new("EU Store"))
            .await
            .unwrap();
        assert_eq!(shop.shop_id, "pro_1");
        assert_eq!(shop.project_id.as_deref(), Some("prj_1"));
        assert!(shop.is_active);
        assert_eq!(
            shop.iframe_allowed_origins.as_deref().unwrap()[0],
            "https://shop.acme.com"
        );
        let format = shop.payment_id_format.as_ref().expect("a custom id format");
        assert_eq!(format.prefix.as_deref(), Some("ORD-"));
        assert_eq!(format.style.as_deref(), Some("numeric"));
        assert_eq!(format.length, Some(8));
        assert_eq!(
            shop.product_id_format.as_ref().unwrap().prefix.as_deref(),
            Some("PRD-")
        );
        // Unmodeled fields survive rather than breaking the decode.
        assert_eq!(shop.extra["surprise_field"], 1);

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(seen[0].url, "https://api.test/shops/merch_123");
        assert_eq!(seen[0].body_json()["shop_name"], "EU Store");
    }

    #[tokio::test]
    async fn retrieve_encodes_both_id_segments() {
        let (client, mock) = client_with(vec![Step::ok(SHOP_JSON)]);
        client.shops().retrieve("merch/1", "pro 1").await.unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "GET");
        assert_eq!(seen[0].url, "https://api.test/shops/merch%2F1/pro%201");
    }

    #[tokio::test]
    async fn update_puts_the_shop_path_with_a_body() {
        let (client, mock) = client_with(vec![Step::ok(SHOP_JSON)]);
        let params = ShopUpdateRequest::new()
            .shop_name("EU Store 2")
            .iframe_allowed_origins(vec!["https://shop.acme.com".to_string()]);
        client
            .shops()
            .update("merch_123", "pro_1", &params)
            .await
            .unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "PUT");
        assert_eq!(seen[0].url, "https://api.test/shops/merch_123/pro_1");
        let body = seen[0].body_json();
        assert_eq!(body["shop_name"], "EU Store 2");
        assert_eq!(body["iframe_allowed_origins"][0], "https://shop.acme.com");
    }

    #[tokio::test]
    async fn delete_deletes_the_shop_path() {
        let (client, mock) = client_with(vec![Step::ok(SHOP_JSON)]);
        client.shops().delete("merch_123", "pro_1").await.unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "DELETE");
        assert_eq!(seen[0].url, "https://api.test/shops/merch_123/pro_1");
    }

    #[tokio::test]
    async fn list_gets_the_merchant_path() {
        let (client, mock) = client_with(vec![Step::ok(&format!("[{SHOP_JSON}]"))]);
        let shops = client.shops().list("merch_123").await.unwrap();
        assert_eq!(shops[0].shop_name, "EU Store");

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

    #[tokio::test]
    async fn stats_serializes_both_period_forms_and_omits_an_absent_period() {
        let (client, mock) = client_with(vec![
            Step::ok(SHOP_STATS_JSON),
            Step::ok(SHOP_STATS_JSON),
            Step::ok(SHOP_STATS_JSON),
        ]);
        let shops = client.shops();
        shops.stats("merch_123", "pro_1", None).await.unwrap();
        shops
            .stats("merch_123", "pro_1", Some(StatsPeriod::All))
            .await
            .unwrap();
        shops
            .stats("merch_123", "pro_1", Some(StatsPeriod::Days(90)))
            .await
            .unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].url, "https://api.test/shops/merch_123/pro_1/stats");
        assert_eq!(
            seen[1].url,
            "https://api.test/shops/merch_123/pro_1/stats?period=all"
        );
        assert_eq!(
            seen[2].url,
            "https://api.test/shops/merch_123/pro_1/stats?period=90"
        );
    }

    #[tokio::test]
    async fn gateways_connect_posts_credentials_to_the_gateways_path() {
        let (client, mock) = client_with(vec![Step::ok(GATEWAY_JSON)]);
        let params = GatewayConnectRequest::new("payment_processor", "stripe")
            .connector_account_details(json!({"auth_type": "HeaderKey", "api_key": "sk_test"}));
        client
            .shops()
            .gateways()
            .connect("merch_123", "pro_1", &params)
            .await
            .unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(
            seen[0].url,
            "https://api.test/shops/merch_123/pro_1/gateways"
        );
        let body = seen[0].body_json();
        assert_eq!(body["connector_name"], "stripe");
        assert_eq!(body["connector_account_details"]["api_key"], "sk_test");
    }

    #[tokio::test]
    async fn gateways_list_gets_the_gateways_path() {
        let (client, mock) = client_with(vec![Step::ok(&format!("[{GATEWAY_JSON}]"))]);
        let gateways = client
            .shops()
            .gateways()
            .list("merch_123", "pro_1")
            .await
            .unwrap();
        assert_eq!(gateways[0].merchant_connector_id, "mca_1");
        assert_eq!(gateways[0].status, "active");

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "GET");
        assert_eq!(
            seen[0].url,
            "https://api.test/shops/merch_123/pro_1/gateways"
        );
    }

    #[tokio::test]
    async fn gateways_disconnect_deletes_the_encoded_gateway_id() {
        let (client, mock) = client_with(vec![Step::ok(GATEWAY_JSON)]);
        client
            .shops()
            .gateways()
            .disconnect("merch_123", "pro_1", "mca/1")
            .await
            .unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "DELETE");
        assert_eq!(
            seen[0].url,
            "https://api.test/shops/merch_123/pro_1/gateways/mca%2F1"
        );
    }

    #[test]
    fn shop_update_debug_redacts_the_webhook_signing_secret() {
        let req = ShopUpdateRequest::new().payment_response_hash_key("whsec_super_secret");
        let rendered = format!("{req:?}");
        assert!(
            !rendered.contains("whsec_super_secret"),
            "the signing secret leaked into Debug output: {rendered}"
        );
        assert!(rendered.contains("<redacted>"));
    }

    #[test]
    fn gateway_connect_debug_redacts_credential_fields() {
        let req = GatewayConnectRequest::new("payment_processor", "stripe")
            .connector_account_details(json!({"api_key": "sk_live_leak_me"}));
        let rendered = format!("{req:?}");
        assert!(
            !rendered.contains("sk_live_leak_me"),
            "connector credentials leaked into Debug output: {rendered}"
        );
        assert!(rendered.contains("<redacted>"));
        // The non-secret fields are still useful in a log.
        assert!(rendered.contains("stripe"));
    }

    /// Drift guard for `SHOP_CREATE_REQUEST_NAMED`.
    #[test]
    fn shop_create_request_named_fields_are_complete() {
        let req = ShopCreateRequest::new("EU Store")
            .return_url("https://acme.test/return")
            .webhook_url("https://acme.test/hook")
            .project_id("prj_1");
        let value = serde_json::to_value(req).unwrap();
        for key in value.as_object().expect("serializes to an object").keys() {
            assert!(
                SHOP_CREATE_REQUEST_NAMED.contains(&key.as_str()),
                "SHOP_CREATE_REQUEST_NAMED is missing wire key `{key}`"
            );
        }
    }

    /// Drift guard for `SHOP_UPDATE_REQUEST_NAMED`.
    #[test]
    fn shop_update_request_named_fields_are_complete() {
        let req = ShopUpdateRequest::new()
            .shop_name("EU Store")
            .return_url("https://acme.test/return")
            .webhook_url("https://acme.test/hook")
            .is_active(true)
            .payment_response_hash_key("whsec_1")
            .payment_link_config(json!({"allowed_domains": ["acme.test"]}))
            .iframe_allowed_origins(vec!["https://acme.test".to_string()])
            .payment_id_format(json!({"prefix": "ORD-", "style": "numeric", "length": 8}))
            .product_id_format(json!({"prefix": "PRD-"}));
        let value = serde_json::to_value(req).unwrap();
        assert_eq!(value["product_id_format"], json!({"prefix": "PRD-"}));
        for key in value.as_object().expect("serializes to an object").keys() {
            assert!(
                SHOP_UPDATE_REQUEST_NAMED.contains(&key.as_str()),
                "SHOP_UPDATE_REQUEST_NAMED is missing wire key `{key}`"
            );
        }
    }

    /// Drift guard for `GATEWAY_CONNECT_REQUEST_NAMED`.
    #[test]
    fn gateway_connect_request_named_fields_are_complete() {
        let req = GatewayConnectRequest {
            connector_label: Some("primary".to_string()),
            profile_id: Some("pro_1".to_string()),
            connector_account_details: Some(json!({"api_key": "sk"})),
            payment_methods_enabled: Some(vec![json!({"payment_method": "card"})]),
            metadata: Some(json!({"team": "eu"})),
            test_mode: Some(true),
            disabled: Some(false),
            connector_webhook_details: Some(json!({"merchant_secret": "whsec"})),
            additional_merchant_data: Some(json!({"open_banking": {}})),
            ..GatewayConnectRequest::new("payment_processor", "stripe")
        };
        let value = serde_json::to_value(req).unwrap();
        for key in value.as_object().expect("serializes to an object").keys() {
            assert!(
                GATEWAY_CONNECT_REQUEST_NAMED.contains(&key.as_str()),
                "GATEWAY_CONNECT_REQUEST_NAMED is missing wire key `{key}`"
            );
        }
    }

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

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

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

    #[tokio::test]
    async fn upload_logo_posts_a_multipart_body_with_a_matching_boundary() {
        let (client, mock) = client_with(vec![Step::ok(r#"{"logo_url":"https://cdn/x.png"}"#)]);
        let uploaded = client
            .shops()
            .upload_logo("mer/1", "pro_1", "logo.png", "image/png", b"PNGDATA")
            .await
            .unwrap();
        assert_eq!(uploaded.logo_url, "https://cdn/x.png");

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(seen[0].url, "https://api.test/shops/mer%2F1/pro_1/logo");

        // The upload must NOT be labelled application/json (the transport
        // default), and the boundary in the header must be the one used in the
        // body -- a mismatch is unparseable server-side.
        let content_type = seen[0]
            .content_type
            .as_deref()
            .expect("upload sets its own content type");
        let boundary = content_type
            .strip_prefix("multipart/form-data; boundary=")
            .expect("multipart content type");
        let body = String::from_utf8(seen[0].body.clone().unwrap()).unwrap();
        assert!(body.starts_with(&format!("--{boundary}\r\n")));
        assert!(body.ends_with(&format!("\r\n--{boundary}--\r\n")));
        assert!(body.contains("name=\"file\"; filename=\"logo.png\""));
        assert!(body.contains("Content-Type: image/png\r\n\r\nPNGDATA"));
    }

    #[tokio::test]
    async fn stats_decodes_the_shop_aggregate() {
        let (client, _mock) = client_with(vec![Step::ok(SHOP_STATS_JSON)]);
        let stats = client
            .shops()
            .stats("merch_123", "pro_1", Some(StatsPeriod::Days(90)))
            .await
            .unwrap();

        assert_eq!(stats.shop_id, "pro_1");
        assert_eq!(stats.orders, 4);
        assert_eq!(stats.revenue, 5000);
        assert_eq!(stats.revenue_usd, 54.5);
        assert_eq!(stats.revenue_by_currency[0].currency, "EUR");
        assert_eq!(stats.revenue_by_currency[0].amount_minor, 5000);
        assert_eq!(stats.revenue_by_currency[0].orders, 4);
        assert_eq!(stats.unconverted_orders, 1);
        assert_eq!(stats.period_days, Some(90));
        assert!(stats.analytics_exclusions_active);
        assert_eq!(stats.project_id, None);
    }

    #[tokio::test]
    async fn shop_response_debug_redacts_an_echoed_webhook_signing_secret() {
        let (client, _mock) = client_with(vec![Step::ok(SHOP_WITH_SECRET_JSON)]);
        let shop = client.shops().retrieve("merch_123", "pro_1").await.unwrap();

        // The value is still reachable for callers that need it...
        assert_eq!(
            shop.payment_response_hash_key.as_deref(),
            Some("whsec_response_leak_me")
        );
        // ...but must never be printable.
        let rendered = format!("{shop:?}");
        assert!(
            !rendered.contains("whsec_response_leak_me"),
            "the signing secret leaked into Debug output: {rendered}"
        );
        assert!(rendered.contains("<redacted>"));
        assert!(rendered.contains("EU Store"));
    }

    #[tokio::test]
    async fn gateway_response_debug_redacts_echoed_credentials() {
        let (client, _mock) = client_with(vec![Step::ok(GATEWAY_JSON)]);
        let gateway = client
            .shops()
            .gateways()
            .connect(
                "merch_123",
                "pro_1",
                &GatewayConnectRequest::new("payment_processor", "stripe"),
            )
            .await
            .unwrap();

        assert_eq!(
            gateway.connector_account_details.as_ref().unwrap()["api_key"],
            "sk_live_response_leak_me"
        );
        let rendered = format!("{gateway:?}");
        assert!(
            !rendered.contains("sk_live_response_leak_me"),
            "connector credentials leaked into Debug output: {rendered}"
        );
        assert!(
            !rendered.contains("whsec_response_leak_me"),
            "connector webhook secret leaked into Debug output: {rendered}"
        );
        assert!(rendered.contains("<redacted>"));
        // The non-secret fields are still useful in a log.
        assert!(rendered.contains("mca_1"));
    }

    /// A Test branding save never carries an idempotency key, not even the
    /// client-wide one, so a 5xx is not replayed. Mutation: switch a call
    /// site back to `request(.., None)` — the header appears and the call
    /// count grows.
    #[tokio::test]
    async fn test_branding_save_ignores_the_client_wide_idempotency_key() {
        let (client, mock) = client_with_retries(vec![Step::status(503, "{}"), Step::ok("{}")], 2);
        let out = client
            .with_idempotency_key("client-key")
            .shops()
            .update_test_checkout_branding("mer_1", "pro_1", &json!({}))
            .await;
        assert!(out.is_err());
        assert_eq!(mock.call_count(), 1);
        assert!(!mock.seen.lock().unwrap()[0].had_idempotency_key());
    }
}