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
//! The `profiles` resource: business profiles ("shops"), the per-storefront
//! configuration owned by a merchant account.

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::{
    ArchivedShopResponse, ProfileResponse, ShopArchiveResponse, ShopPaymentsSwitchResponse,
    VaultSwitchOffResponse,
};
use crate::http::client::Inner;
use crate::http::transport::HttpMethod;
use crate::resources::ValidateRequest;

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

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

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

    /// Retrieve one shop (business profile).
    /// `GET /account/{account_id}/business-profile/{profile_id}`
    pub async fn retrieve(&self, account_id: &str, profile_id: &str) -> Result<ProfileResponse> {
        let path = Self::profile_path(account_id, profile_id);
        self.inner
            .request(HttpMethod::Get, &path, None, &[], None)
            .await
    }

    /// List a merchant account's shops (business profiles).
    /// `GET /account/{account_id}/business-profile`
    pub async fn list(&self, account_id: &str) -> Result<Vec<ProfileResponse>> {
        let path = format!("/account/{}/business-profile", encode_segment(account_id));
        self.inner
            .request(HttpMethod::Get, &path, None, &[], None)
            .await
    }

    /// Update a shop (business profile).
    /// `POST /account/{account_id}/business-profile/{profile_id}`
    pub async fn update(
        &self,
        account_id: &str,
        profile_id: &str,
        params: &ProfileUpdateRequest,
    ) -> Result<ProfileResponse> {
        params.validate()?;
        let path = Self::profile_path(account_id, profile_id);
        let body = to_json_vec(params)?;
        self.inner
            .request(HttpMethod::Post, &path, Some(&body), &[], None)
            .await
    }

    /// Delete a shop (business profile).
    /// `DELETE /account/{account_id}/business-profile/{profile_id}`
    pub async fn delete(&self, account_id: &str, profile_id: &str) -> Result<ProfileResponse> {
        let path = Self::profile_path(account_id, profile_id);
        self.inner
            .request(HttpMethod::Delete, &path, None, &[], None)
            .await
    }

    /// Toggle extended card info for a shop.
    /// `POST /account/{account_id}/business-profile/{profile_id}/toggle-extended-card-info`
    pub async fn toggle_extended_card_info(
        &self,
        account_id: &str,
        profile_id: &str,
    ) -> Result<ProfileResponse> {
        let path = format!(
            "{}/toggle-extended-card-info",
            Self::profile_path(account_id, profile_id)
        );
        self.inner
            .request(HttpMethod::Post, &path, None, &[], None)
            .await
    }

    /// Toggle connector-agnostic MIT (merchant-initiated transactions) for a
    /// shop.
    /// `POST /account/{account_id}/business-profile/{profile_id}/toggle-connector-agnostic-mit`
    pub async fn toggle_connector_agnostic_mit(
        &self,
        account_id: &str,
        profile_id: &str,
    ) -> Result<ProfileResponse> {
        let path = format!(
            "{}/toggle-connector-agnostic-mit",
            Self::profile_path(account_id, profile_id)
        );
        self.inner
            .request(HttpMethod::Post, &path, None, &[], None)
            .await
    }

    /// Hide a shop from ordinary navigation. Its identity, project
    /// membership, settings and retained records stay unchanged, and its
    /// payments keep working. Needs shop write access. Archiving an archived
    /// shop is safe; [`restore`](Self::restore) makes it visible again.
    ///
    /// `PUT /account/{account_id}/business-profile/{profile_id}/archive`
    pub async fn archive(&self, account_id: &str, profile_id: &str) -> Result<ShopArchiveResponse> {
        self.set_archived(account_id, profile_id, true).await
    }

    /// Restore an archived shop to navigation with the same identity and
    /// project.
    ///
    /// `PUT /account/{account_id}/business-profile/{profile_id}/archive`
    pub async fn restore(&self, account_id: &str, profile_id: &str) -> Result<ShopArchiveResponse> {
        self.set_archived(account_id, profile_id, false).await
    }

    async fn set_archived(
        &self,
        account_id: &str,
        profile_id: &str,
        is_archived: bool,
    ) -> Result<ShopArchiveResponse> {
        let path = format!("{}/archive", Self::profile_path(account_id, profile_id));
        let body = to_json_vec(&ShopArchiveUpdate { is_archived })?;
        self.inner
            .request_body_keyed(HttpMethod::Put, &path, Some(&body), None)
            .await
    }

    /// The archived shops the caller may read.
    ///
    /// `GET /account/{account_id}/business-profile/archived`
    pub async fn list_archived(&self, account_id: &str) -> Result<Vec<ArchivedShopResponse>> {
        let path = format!(
            "/account/{}/business-profile/archived",
            encode_segment(account_id)
        );
        self.inner
            .request(HttpMethod::Get, &path, None, &[], None)
            .await
    }

    /// Switch a shop's payments off. While they are off the shop takes no
    /// new payment: creating one, and confirming one no provider holds yet,
    /// is refused with `DE_21`, and its hosted checkout does not render. A
    /// payment a provider already holds is finished; refunds and disputes
    /// are unaffected. Needs a signed-in user (JWT) with write access to the
    /// shop's payments switch. Repeating the same state is safe.
    ///
    /// `PUT /account/{account_id}/business-profile/{profile_id}/payments-switch`
    pub async fn disable_payments(
        &self,
        account_id: &str,
        profile_id: &str,
    ) -> Result<ShopPaymentsSwitchResponse> {
        self.set_payments_disabled(account_id, profile_id, true)
            .await
    }

    /// Switch a shop's payments on again after
    /// [`disable_payments`](Self::disable_payments).
    ///
    /// `PUT /account/{account_id}/business-profile/{profile_id}/payments-switch`
    pub async fn enable_payments(
        &self,
        account_id: &str,
        profile_id: &str,
    ) -> Result<ShopPaymentsSwitchResponse> {
        self.set_payments_disabled(account_id, profile_id, false)
            .await
    }

    async fn set_payments_disabled(
        &self,
        account_id: &str,
        profile_id: &str,
        payments_disabled: bool,
    ) -> Result<ShopPaymentsSwitchResponse> {
        let path = format!(
            "{}/payments-switch",
            Self::profile_path(account_id, profile_id)
        );
        let body = to_json_vec(&ShopPaymentsSwitch { payments_disabled })?;
        self.inner
            .request_body_keyed(HttpMethod::Put, &path, Some(&body), None)
            .await
    }

    /// Switch the shop's card vault off. From the next checkout on, the
    /// checkout draws each processor's own card form and card payments no
    /// longer depend on the vault account. Cards saved in the vault cannot be
    /// charged while it is off.
    ///
    /// The vault stays configured; switch it on again with
    /// [`update`](Self::update), which verifies the vault first. Needs the
    /// permission to edit the shop's connectors, not the one to edit the
    /// shop. A shop whose vault is already off is left unchanged.
    ///
    /// `POST /account/{account_id}/business-profile/{profile_id}/vault/switch-off`
    pub async fn switch_vault_off(
        &self,
        account_id: &str,
        profile_id: &str,
    ) -> Result<VaultSwitchOffResponse> {
        let path = format!(
            "{}/vault/switch-off",
            Self::profile_path(account_id, profile_id)
        );
        self.inner
            .request_body_keyed(HttpMethod::Post, &path, None, None)
            .await
    }

    fn profile_path(account_id: &str, profile_id: &str) -> String {
        format!(
            "/account/{}/business-profile/{}",
            encode_segment(account_id),
            encode_segment(profile_id)
        )
    }
}

/// Body of [`Profiles::archive`] and [`Profiles::restore`].
#[derive(Debug, Serialize)]
struct ShopArchiveUpdate {
    is_archived: bool,
}

/// Body of [`Profiles::disable_payments`] and [`Profiles::enable_payments`].
#[derive(Debug, Serialize)]
struct ShopPaymentsSwitch {
    payments_disabled: bool,
}

/// Placeholder printed in place of a credential-bearing field.
const REDACTED: &str = "[redacted]";

/// Parameters for [`Profiles::create`].
///
/// `Debug` is hand-written: `payment_response_hash_key` is the secret used to
/// sign payment responses, and `webhook_details` can hold outgoing-webhook
/// credentials, so a derived `Debug` would leak both into logs.
#[derive(Clone, Default, Serialize)]
pub struct ProfileCreateRequest {
    /// Display name for the shop.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub profile_name: Option<String>,
    /// URL customers are returned to after a payment.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub return_url: Option<String>,
    /// Whether payment responses are signed.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub enable_payment_response_hash: Option<bool>,
    /// Signing key for payment response hashes. **Secret.**
    #[serde(skip_serializing_if = "Option::is_none")]
    pub payment_response_hash_key: Option<String>,
    /// Whether the customer is redirected back with an HTTP POST.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub redirect_to_merchant_with_http_post: Option<bool>,
    /// Outgoing-webhook configuration (open shape). **May hold credentials.**
    #[serde(skip_serializing_if = "Option::is_none")]
    pub webhook_details: Option<Value>,
    /// Arbitrary key-value metadata.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub metadata: Option<Value>,
    /// Origins permitted to embed this profile's hosted checkout in an
    /// iframe. Each entry is a full origin (`scheme://host[:port]`, no path).
    /// Empty/absent defaults to same-origin only — strict clickjacking
    /// defense.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub iframe_allowed_origins: Option<Vec<String>>,
    /// Merchant connector account ID of the billing processor (e.g. Stripe
    /// Billing / PayPal) that owns this profile's native subscriptions.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub billing_processor_id: Option<String>,
    /// Custom format for generated payment ids (cloaking), e.g.
    /// `ORD-74219807`. Open shape — see the API reference.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub payment_id_format: Option<Value>,
    /// Whether the payment's description is passed on to the processor.
    /// Server default `false`: the processor sees no description unless the
    /// shop opts in.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub send_description_to_processor: Option<bool>,
    /// Whether the merchant's own metadata keys are passed on to the
    /// processor. Server default `false`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub send_metadata_to_processor: Option<bool>,
    /// The shop's own website. Setting it is supported; clearing it is not
    /// expressible here.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub shop_url: Option<String>,
    /// Whether the payment's order details are passed on to the processor.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub send_order_details_to_processor: Option<bool>,
    /// Whether the payment ID is passed on to the processor.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub send_payment_id_to_processor: Option<bool>,
    /// Whether card payments go through the shop's card vault: `"enable"` or
    /// `"skip"`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub is_external_vault_enabled: Option<String>,
    /// Custom format for generated product IDs, in the shape of
    /// `payment_id_format`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub product_id_format: Option<Value>,
    /// URL the buyer may use to leave an unpaid hosted checkout.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cancel_url: Option<String>,
    /// The shop's default checkout locale, as a BCP 47 tag.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub default_locale: Option<String>,
    /// Whether the checkout uses `default_locale` over the buyer's browser
    /// language.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub prefer_merchant_locale: Option<bool>,
    /// Any additional fields, merged verbatim.
    #[serde(flatten, skip_serializing_if = "serde_json::Map::is_empty")]
    pub extra: serde_json::Map<String, Value>,
}

impl std::fmt::Debug for ProfileCreateRequest {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ProfileCreateRequest")
            .field("profile_name", &self.profile_name)
            .field("return_url", &self.return_url)
            .field(
                "enable_payment_response_hash",
                &self.enable_payment_response_hash,
            )
            .field(
                "payment_response_hash_key",
                &self.payment_response_hash_key.as_ref().map(|_| REDACTED),
            )
            .field(
                "redirect_to_merchant_with_http_post",
                &self.redirect_to_merchant_with_http_post,
            )
            .field(
                "webhook_details",
                &self.webhook_details.as_ref().map(|_| REDACTED),
            )
            .field("metadata", &self.metadata)
            .field("iframe_allowed_origins", &self.iframe_allowed_origins)
            .field("billing_processor_id", &self.billing_processor_id)
            .field("payment_id_format", &self.payment_id_format)
            .field(
                "send_description_to_processor",
                &self.send_description_to_processor,
            )
            .field(
                "send_metadata_to_processor",
                &self.send_metadata_to_processor,
            )
            .field("shop_url", &self.shop_url)
            .field(
                "send_order_details_to_processor",
                &self.send_order_details_to_processor,
            )
            .field(
                "send_payment_id_to_processor",
                &self.send_payment_id_to_processor,
            )
            .field("is_external_vault_enabled", &self.is_external_vault_enabled)
            .field("product_id_format", &self.product_id_format)
            .field("cancel_url", &self.cancel_url)
            .field("default_locale", &self.default_locale)
            .field("prefer_merchant_locale", &self.prefer_merchant_locale)
            .field("extra", &self.extra)
            .finish()
    }
}

/// Names of `ProfileCreateRequest`'s fields, as they appear on the wire
/// (`extra` excluded).
const PROFILE_CREATE_REQUEST_NAMED: &[&str] = &[
    "profile_name",
    "return_url",
    "enable_payment_response_hash",
    "payment_response_hash_key",
    "redirect_to_merchant_with_http_post",
    "webhook_details",
    "metadata",
    "iframe_allowed_origins",
    "billing_processor_id",
    "payment_id_format",
    "send_description_to_processor",
    "send_metadata_to_processor",
    "shop_url",
    "send_order_details_to_processor",
    "send_payment_id_to_processor",
    "is_external_vault_enabled",
    "product_id_format",
    "cancel_url",
    "default_locale",
    "prefer_merchant_locale",
];

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

impl ProfileCreateRequest {
    /// An empty request; set the fields you need.
    pub fn new() -> Self {
        Self::default()
    }

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

    /// Set the URL customers are returned to after a payment.
    #[must_use]
    pub fn return_url(mut self, url: impl Into<String>) -> Self {
        self.return_url = Some(url.into());
        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 billing processor that owns this shop's native subscriptions.
    #[must_use]
    pub fn billing_processor_id(mut self, id: impl Into<String>) -> Self {
        self.billing_processor_id = Some(id.into());
        self
    }
}

/// Parameters for [`Profiles::update`].
///
/// `Debug` is hand-written for the same reason as [`ProfileCreateRequest`]:
/// the signing key and webhook details are redacted.
#[derive(Clone, Default, Serialize)]
pub struct ProfileUpdateRequest {
    /// Display name for the shop.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub profile_name: Option<String>,
    /// URL customers are returned to after a payment.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub return_url: Option<String>,
    /// Whether payment responses are signed.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub enable_payment_response_hash: Option<bool>,
    /// Signing key for payment response hashes. **Secret.**
    #[serde(skip_serializing_if = "Option::is_none")]
    pub payment_response_hash_key: Option<String>,
    /// Whether the customer is redirected back with an HTTP POST.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub redirect_to_merchant_with_http_post: Option<bool>,
    /// Outgoing-webhook configuration (open shape). **May hold credentials.**
    #[serde(skip_serializing_if = "Option::is_none")]
    pub webhook_details: Option<Value>,
    /// Arbitrary key-value metadata.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub metadata: Option<Value>,
    /// Hosted payment-link appearance configuration (open shape — see the API
    /// reference).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub payment_link_config: Option<Value>,
    /// Origins permitted to embed this profile's hosted checkout in an
    /// iframe. See [`ProfileCreateRequest::iframe_allowed_origins`].
    #[serde(skip_serializing_if = "Option::is_none")]
    pub iframe_allowed_origins: Option<Vec<String>>,
    /// Merchant connector account ID of the billing processor (e.g. Stripe
    /// Billing / PayPal) that owns this profile's native subscriptions.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub billing_processor_id: Option<String>,
    /// Custom format for generated payment ids (cloaking). Open shape — see
    /// the API reference.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub payment_id_format: Option<Value>,
    /// Whether the payment's description is passed on to the processor.
    /// Server default `false`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub send_description_to_processor: Option<bool>,
    /// Whether the merchant's own metadata keys are passed on to the
    /// processor. Server default `false`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub send_metadata_to_processor: Option<bool>,
    /// The shop's own website. Setting it is supported; clearing it is not
    /// expressible here.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub shop_url: Option<String>,
    /// Whether the payment's order details are passed on to the processor.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub send_order_details_to_processor: Option<bool>,
    /// Whether the payment ID is passed on to the processor.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub send_payment_id_to_processor: Option<bool>,
    /// Whether card payments go through the shop's card vault: `"enable"` or
    /// `"skip"`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub is_external_vault_enabled: Option<String>,
    /// Custom format for generated product IDs, in the shape of
    /// `payment_id_format`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub product_id_format: Option<Value>,
    /// URL the buyer may use to leave an unpaid hosted checkout.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cancel_url: Option<String>,
    /// The shop's default checkout locale, as a BCP 47 tag.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub default_locale: Option<String>,
    /// Whether the checkout uses `default_locale` over the buyer's browser
    /// language.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub prefer_merchant_locale: Option<bool>,
    /// Any additional fields, merged verbatim.
    #[serde(flatten, skip_serializing_if = "serde_json::Map::is_empty")]
    pub extra: serde_json::Map<String, Value>,
}

impl std::fmt::Debug for ProfileUpdateRequest {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ProfileUpdateRequest")
            .field("profile_name", &self.profile_name)
            .field("return_url", &self.return_url)
            .field(
                "enable_payment_response_hash",
                &self.enable_payment_response_hash,
            )
            .field(
                "payment_response_hash_key",
                &self.payment_response_hash_key.as_ref().map(|_| REDACTED),
            )
            .field(
                "redirect_to_merchant_with_http_post",
                &self.redirect_to_merchant_with_http_post,
            )
            .field(
                "webhook_details",
                &self.webhook_details.as_ref().map(|_| REDACTED),
            )
            .field("metadata", &self.metadata)
            .field("payment_link_config", &self.payment_link_config)
            .field("iframe_allowed_origins", &self.iframe_allowed_origins)
            .field("billing_processor_id", &self.billing_processor_id)
            .field("payment_id_format", &self.payment_id_format)
            .field(
                "send_description_to_processor",
                &self.send_description_to_processor,
            )
            .field(
                "send_metadata_to_processor",
                &self.send_metadata_to_processor,
            )
            .field("shop_url", &self.shop_url)
            .field(
                "send_order_details_to_processor",
                &self.send_order_details_to_processor,
            )
            .field(
                "send_payment_id_to_processor",
                &self.send_payment_id_to_processor,
            )
            .field("is_external_vault_enabled", &self.is_external_vault_enabled)
            .field("product_id_format", &self.product_id_format)
            .field("cancel_url", &self.cancel_url)
            .field("default_locale", &self.default_locale)
            .field("prefer_merchant_locale", &self.prefer_merchant_locale)
            .field("extra", &self.extra)
            .finish()
    }
}

/// Names of `ProfileUpdateRequest`'s fields, as they appear on the wire
/// (`extra` excluded).
const PROFILE_UPDATE_REQUEST_NAMED: &[&str] = &[
    "profile_name",
    "return_url",
    "enable_payment_response_hash",
    "payment_response_hash_key",
    "redirect_to_merchant_with_http_post",
    "webhook_details",
    "metadata",
    "payment_link_config",
    "iframe_allowed_origins",
    "billing_processor_id",
    "payment_id_format",
    "send_description_to_processor",
    "send_metadata_to_processor",
    "shop_url",
    "send_order_details_to_processor",
    "send_payment_id_to_processor",
    "is_external_vault_enabled",
    "product_id_format",
    "cancel_url",
    "default_locale",
    "prefer_merchant_locale",
];

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

impl ProfileUpdateRequest {
    /// An empty request; set the fields you need.
    pub fn new() -> Self {
        Self::default()
    }

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

    /// Set the URL customers are returned to after a payment.
    #[must_use]
    pub fn return_url(mut self, url: impl Into<String>) -> Self {
        self.return_url = Some(url.into());
        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 billing processor that owns this shop's native subscriptions.
    #[must_use]
    pub fn billing_processor_id(mut self, id: impl Into<String>) -> Self {
        self.billing_processor_id = Some(id.into());
        self
    }
}

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

    const PROFILE_JSON: &str = r#"{
        "profile_id": "pro_1",
        "merchant_id": "mer_1",
        "profile_name": "Shop",
        "enable_payment_response_hash": true,
        "redirect_to_merchant_with_http_post": false,
        "force_3ds_challenge": false
    }"#;

    fn full_create_request() -> ProfileCreateRequest {
        ProfileCreateRequest {
            profile_name: Some("Shop".to_string()),
            return_url: Some("https://shop.test/return".to_string()),
            enable_payment_response_hash: Some(true),
            payment_response_hash_key: Some("hashkey_supersecret".to_string()),
            redirect_to_merchant_with_http_post: Some(false),
            webhook_details: Some(json!({"webhook_password": "hunter2"})),
            metadata: Some(json!({"tier": "gold"})),
            iframe_allowed_origins: Some(vec!["https://shop.test".to_string()]),
            billing_processor_id: Some("mca_billing".to_string()),
            payment_id_format: Some(json!({"prefix": "ORD-"})),
            send_description_to_processor: Some(true),
            send_metadata_to_processor: Some(false),
            shop_url: Some("https://shop.test".to_string()),
            send_order_details_to_processor: Some(true),
            send_payment_id_to_processor: Some(false),
            is_external_vault_enabled: Some("enable".to_string()),
            product_id_format: Some(json!({"prefix": "PRD-"})),
            cancel_url: Some("https://shop.test/cart".to_string()),
            default_locale: Some("de".to_string()),
            prefer_merchant_locale: Some(true),
            extra: serde_json::Map::new(),
        }
    }

    fn full_update_request() -> ProfileUpdateRequest {
        ProfileUpdateRequest {
            profile_name: Some("Shop".to_string()),
            return_url: Some("https://shop.test/return".to_string()),
            enable_payment_response_hash: Some(true),
            payment_response_hash_key: Some("hashkey_supersecret".to_string()),
            redirect_to_merchant_with_http_post: Some(false),
            webhook_details: Some(json!({"webhook_password": "hunter2"})),
            metadata: Some(json!({"tier": "gold"})),
            payment_link_config: Some(json!({"theme": "dark"})),
            iframe_allowed_origins: Some(vec!["https://shop.test".to_string()]),
            billing_processor_id: Some("mca_billing".to_string()),
            payment_id_format: Some(json!({"prefix": "ORD-"})),
            send_description_to_processor: Some(true),
            send_metadata_to_processor: Some(false),
            shop_url: Some("https://shop.test".to_string()),
            send_order_details_to_processor: Some(true),
            send_payment_id_to_processor: Some(false),
            is_external_vault_enabled: Some("enable".to_string()),
            product_id_format: Some(json!({"prefix": "PRD-"})),
            cancel_url: Some("https://shop.test/cart".to_string()),
            default_locale: Some("de".to_string()),
            prefer_merchant_locale: Some(true),
            extra: serde_json::Map::new(),
        }
    }

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

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

    #[test]
    fn validate_rejects_colliding_extra_keys() {
        let mut create = ProfileCreateRequest::new().profile_name("Shop");
        create
            .extra
            .insert("return_url".to_string(), json!("https://evil.test"));
        match create.validate().unwrap_err() {
            DelopayError::InvalidRequest(msg) => assert!(msg.contains("return_url")),
            other => panic!("expected InvalidRequest, got {other:?}"),
        }

        let mut update = ProfileUpdateRequest::new();
        update
            .extra
            .insert("payment_link_config".to_string(), json!({}));
        assert!(matches!(
            update.validate().unwrap_err(),
            DelopayError::InvalidRequest(_)
        ));
    }

    /// The response-signing key and webhook credentials must never reach a log
    /// line.
    #[test]
    fn debug_redacts_the_signing_key_and_webhook_details() {
        let created = format!("{:?}", full_create_request());
        assert!(!created.contains("hashkey_supersecret"), "{created}");
        assert!(!created.contains("hunter2"), "{created}");
        assert!(
            created.contains("payment_response_hash_key: Some(\"[redacted]\")"),
            "{created}"
        );
        assert!(created.contains("Shop"), "{created}");

        let updated = format!("{:?}", full_update_request());
        assert!(!updated.contains("hashkey_supersecret"), "{updated}");
        assert!(!updated.contains("hunter2"), "{updated}");
        assert!(
            updated.contains("webhook_details: Some(\"[redacted]\")"),
            "{updated}"
        );
    }

    /// An unset secret must be distinguishable from a set one.
    #[test]
    fn debug_shows_none_for_unset_secrets() {
        let rendered = format!("{:?}", ProfileCreateRequest::new());
        assert!(
            rendered.contains("payment_response_hash_key: None"),
            "{rendered}"
        );
    }

    #[tokio::test]
    async fn create_and_list_hit_the_business_profile_path() {
        let (client, mock) = client_with(vec![Step::ok(PROFILE_JSON), Step::ok("[]")]);
        let profiles = client.profiles();
        let created = profiles
            .create("mer/1", &ProfileCreateRequest::new().profile_name("Shop"))
            .await
            .unwrap();
        assert_eq!(created.profile_id, "pro_1");
        assert_eq!(created.profile_name.as_deref(), Some("Shop"));
        assert!(profiles.list("mer_1").await.unwrap().is_empty());

        let seen = mock.seen.lock().unwrap();
        assert_eq!(
            (seen[0].method, seen[0].url.as_str()),
            ("POST", "https://api.test/account/mer%2F1/business-profile")
        );
        assert_eq!(seen[0].body_json()["profile_name"], "Shop");
        assert_eq!(
            (seen[1].method, seen[1].url.as_str()),
            ("GET", "https://api.test/account/mer_1/business-profile")
        );
    }

    #[tokio::test]
    async fn retrieve_update_and_delete_hit_the_profile_path() {
        let (client, mock) = client_with(vec![
            Step::ok(PROFILE_JSON),
            Step::ok(PROFILE_JSON),
            Step::ok(PROFILE_JSON),
        ]);
        let profiles = client.profiles();
        let retrieved = profiles.retrieve("mer_1", "pro/1").await.unwrap();
        assert_eq!(retrieved.merchant_id.as_deref(), Some("mer_1"));
        assert_eq!(retrieved.force_3ds_challenge, Some(false));
        profiles
            .update(
                "mer_1",
                "pro_1",
                &ProfileUpdateRequest::new().return_url("https://shop.test/r"),
            )
            .await
            .unwrap();
        profiles.delete("mer_1", "pro_1").await.unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(
            (seen[0].method, seen[0].url.as_str()),
            (
                "GET",
                "https://api.test/account/mer_1/business-profile/pro%2F1"
            )
        );
        assert_eq!(
            (seen[1].method, seen[1].url.as_str()),
            (
                "POST",
                "https://api.test/account/mer_1/business-profile/pro_1"
            )
        );
        assert_eq!(seen[1].body_json()["return_url"], "https://shop.test/r");
        assert_eq!(
            (seen[2].method, seen[2].url.as_str()),
            (
                "DELETE",
                "https://api.test/account/mer_1/business-profile/pro_1"
            )
        );
    }

    #[tokio::test]
    async fn archive_and_restore_put_the_archive_state() {
        let (client, mock) = client_with(vec![
            Step::ok(r#"{"profile_id":"pro_1","is_archived":true,"surprise_field":1}"#),
            Step::ok(r#"{"profile_id":"pro_1","is_archived":false}"#),
        ]);
        let profiles = client.profiles();
        let archived = profiles.archive("mer/1", "pro/1").await.unwrap();
        assert!(archived.is_archived);
        assert_eq!(archived.extra["surprise_field"], 1);
        let restored = profiles.restore("mer/1", "pro/1").await.unwrap();
        assert!(!restored.is_archived);

        let seen = mock.seen.lock().unwrap();
        for step in seen.iter() {
            assert_eq!(step.method, "PUT");
            assert_eq!(
                step.url,
                "https://api.test/account/mer%2F1/business-profile/pro%2F1/archive"
            );
        }
        assert_eq!(seen[0].body_json(), json!({"is_archived": true}));
        assert_eq!(seen[1].body_json(), json!({"is_archived": false}));
    }

    #[tokio::test]
    async fn list_archived_gets_the_archived_path() {
        let (client, mock) = client_with(vec![Step::ok(
            r#"[{"profile_id":"pro_1","profile_name":"Old Store","project_id":null,"is_archived":true,"surprise_field":"x"}]"#,
        )]);
        let shops = client.profiles().list_archived("mer/1").await.unwrap();
        assert_eq!(shops[0].profile_id, "pro_1");
        assert_eq!(shops[0].profile_name, "Old Store");
        assert!(shops[0].project_id.is_none());
        assert!(shops[0].is_archived);
        assert_eq!(shops[0].extra["surprise_field"], "x");

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "GET");
        assert_eq!(
            seen[0].url,
            "https://api.test/account/mer%2F1/business-profile/archived"
        );
    }

    #[tokio::test]
    async fn disable_and_enable_payments_put_the_payments_switch() {
        let (client, mock) = client_with(vec![
            Step::ok(r#"{"profile_id":"pro_1","payments_disabled":true,"surprise_field":1}"#),
            Step::ok(r#"{"profile_id":"pro_1","payments_disabled":false}"#),
        ]);
        let profiles = client.profiles();
        let off = profiles.disable_payments("mer_1", "pro/1").await.unwrap();
        assert!(off.payments_disabled);
        assert_eq!(off.extra["surprise_field"], 1);
        let on = profiles.enable_payments("mer_1", "pro/1").await.unwrap();
        assert!(!on.payments_disabled);

        let seen = mock.seen.lock().unwrap();
        for step in seen.iter() {
            assert_eq!(step.method, "PUT");
            assert_eq!(
                step.url,
                "https://api.test/account/mer_1/business-profile/pro%2F1/payments-switch"
            );
        }
        assert_eq!(seen[0].body_json(), json!({"payments_disabled": true}));
        assert_eq!(seen[1].body_json(), json!({"payments_disabled": false}));
    }

    #[tokio::test]
    async fn switch_vault_off_posts_without_a_body() {
        let (client, mock) = client_with(vec![Step::ok(
            r#"{"profile_id":"pro_1","vault_enabled":false,"surprise_field":1}"#,
        )]);
        let out = client
            .profiles()
            .switch_vault_off("mer_1", "pro/1")
            .await
            .unwrap();
        assert_eq!(out.profile_id, "pro_1");
        assert!(!out.vault_enabled);
        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/account/mer_1/business-profile/pro%2F1/vault/switch-off"
        );
        assert!(seen[0].body.is_none());
    }

    #[tokio::test]
    async fn the_two_toggles_post_to_their_distinct_paths() {
        let (client, mock) = client_with(vec![Step::ok(PROFILE_JSON), Step::ok(PROFILE_JSON)]);
        let profiles = client.profiles();
        let toggled = profiles
            .toggle_extended_card_info("mer_1", "pro_1")
            .await
            .unwrap();
        assert_eq!(toggled.profile_id, "pro_1");
        profiles
            .toggle_connector_agnostic_mit("mer_1", "pro_1")
            .await
            .unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(
            (seen[0].method, seen[0].url.as_str()),
            (
                "POST",
                "https://api.test/account/mer_1/business-profile/pro_1/toggle-extended-card-info"
            )
        );
        assert_eq!(
            (seen[1].method, seen[1].url.as_str()),
            (
                "POST",
                "https://api.test/account/mer_1/business-profile/pro_1/toggle-connector-agnostic-mit"
            )
        );
    }

    /// An archive, payments switch or vault switch-off 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 shop_switches_ignore_the_client_wide_idempotency_key() {
        let (client, mock) = client_with_retries(
            vec![
                Step::status(503, "{}"),
                Step::status(503, "{}"),
                Step::status(503, "{}"),
                Step::ok("{}"),
            ],
            2,
        );
        let profiles = client.with_idempotency_key("client-key").profiles();
        assert!(profiles.archive("mer_1", "pro_1").await.is_err());
        assert!(profiles.disable_payments("mer_1", "pro_1").await.is_err());
        assert!(profiles.switch_vault_off("mer_1", "pro_1").await.is_err());
        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen.len(), 3);
        assert!(seen.iter().all(|step| !step.had_idempotency_key()));
    }
}