delopay 0.3.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
//! The `billing` resource: prepaid platform-fee balances — top-ups, card
//! setup, auto-recharge, the balance ledger, and per-shop allocations.
//!
//! Delopay deducts a platform fee from the merchant's prepaid balance on every
//! successful payment. These endpoints fund and monitor that balance.
//!
//! `BillingSetupResponse` carries a Stripe SetupIntent client secret and has a
//! hand-written `Debug` that redacts it.

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::billing::{
    AllocationListResponse, AllocationResponse, AllocationTransferResponse, BillingProfileResponse,
    BillingSetupResponse, BlockedAttemptListResponse, LedgerResponse, TopupResponse,
};
use crate::http::client::Inner;
use crate::http::transport::HttpMethod;
use crate::resources::ValidateRequest;

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

/// The path prefix every billing endpoint hangs off, with the merchant ID
/// percent-encoded.
fn billing_path(merchant_id: &str) -> String {
    format!("/billing/{}", encode_segment(merchant_id))
}

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

    /// Per-shop balance allocation management for host merchants.
    pub fn allocations(&self) -> BillingAllocations {
        BillingAllocations::new(self.inner.clone())
    }

    /// Retrieve a merchant's billing profile (balance, status, auto-recharge
    /// configuration).
    pub async fn profile(&self, merchant_id: &str) -> Result<BillingProfileResponse> {
        let path = billing_path(merchant_id);
        self.inner
            .request(HttpMethod::Get, &path, None, &[], None)
            .await
    }

    /// Start a Stripe SetupIntent flow to collect a payment card for
    /// auto-recharge. The response carries the client secret needed to render
    /// the card element.
    pub async fn setup(
        &self,
        merchant_id: &str,
        params: Option<&BillingSetupRequest>,
    ) -> Result<BillingSetupResponse> {
        let body = match params {
            Some(p) => {
                p.validate()?;
                Some(to_json_vec(p)?)
            }
            None => None,
        };
        let path = format!("{}/setup", billing_path(merchant_id));
        self.inner
            .request(HttpMethod::Post, &path, body.as_deref(), &[], None)
            .await
    }

    /// Confirm card setup after the Stripe SetupIntent completes on the
    /// frontend. Returns the updated billing profile.
    pub async fn complete_setup(
        &self,
        merchant_id: &str,
        params: &BillingCompleteSetupRequest,
    ) -> Result<BillingProfileResponse> {
        let body = to_json_vec(params)?;
        let path = format!("{}/setup/complete", billing_path(merchant_id));
        self.inner
            .request(HttpMethod::Post, &path, Some(&body), &[], None)
            .await
    }

    /// Manually top up a merchant's prepaid balance by charging their saved
    /// card.
    pub async fn topup(&self, merchant_id: &str, params: &TopupRequest) -> Result<TopupResponse> {
        let body = to_json_vec(params)?;
        let path = format!("{}/topup", billing_path(merchant_id));
        self.inner
            .request(HttpMethod::Post, &path, Some(&body), &[], None)
            .await
    }

    /// List the balance ledger (credits and debits) for a merchant.
    pub async fn list_ledger(
        &self,
        merchant_id: &str,
        params: Option<&LedgerListParams>,
    ) -> Result<LedgerResponse> {
        let query = params.map(LedgerListParams::to_query).unwrap_or_default();
        let path = format!("{}/ledger", billing_path(merchant_id));
        self.inner
            .request(HttpMethod::Get, &path, None, &query, None)
            .await
    }

    /// List payment attempts rejected by the billing suspension gate (account
    /// suspended, setup incomplete, or shop allocation suspended).
    ///
    /// These attempts never created a payment, so they do not appear in the
    /// payments list — this is the only way to retrieve them.
    pub async fn list_blocked_attempts(
        &self,
        merchant_id: &str,
        params: Option<&BlockedAttemptListParams>,
    ) -> Result<BlockedAttemptListResponse> {
        let query = params
            .map(BlockedAttemptListParams::to_query)
            .unwrap_or_default();
        let path = format!("{}/blocked-attempts", billing_path(merchant_id));
        self.inner
            .request(HttpMethod::Get, &path, None, &query, None)
            .await
    }

    /// Update auto-recharge configuration (threshold, top-up amount, enabled
    /// flag). Returns the updated billing profile.
    pub async fn update_auto_recharge(
        &self,
        merchant_id: &str,
        params: &AutoRechargeUpdateRequest,
    ) -> Result<BillingProfileResponse> {
        params.validate()?;
        let body = to_json_vec(params)?;
        let path = format!("{}/auto-recharge", billing_path(merchant_id));
        self.inner
            .request(HttpMethod::Patch, &path, Some(&body), &[], None)
            .await
    }
}

/// Per-shop prepaid balance allocations transferred from the host merchant
/// treasury, obtained via [`Billing::allocations`].
#[derive(Debug, Clone)]
pub struct BillingAllocations {
    inner: Arc<Inner>,
}

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

    /// Transfer funds from the host merchant treasury into a shop's
    /// allocation.
    pub async fn transfer_in(
        &self,
        merchant_id: &str,
        params: &AllocationTransferRequest,
    ) -> Result<AllocationTransferResponse> {
        let body = to_json_vec(params)?;
        let path = format!("{}/allocations/transfer-in", billing_path(merchant_id));
        self.inner
            .request(HttpMethod::Post, &path, Some(&body), &[], None)
            .await
    }

    /// Transfer funds from a shop's allocation back to the host merchant
    /// treasury.
    pub async fn transfer_out(
        &self,
        merchant_id: &str,
        params: &AllocationTransferRequest,
    ) -> Result<AllocationTransferResponse> {
        let body = to_json_vec(params)?;
        let path = format!("{}/allocations/transfer-out", billing_path(merchant_id));
        self.inner
            .request(HttpMethod::Post, &path, Some(&body), &[], None)
            .await
    }

    /// List all shop balance allocations for a merchant.
    pub async fn list(&self, merchant_id: &str) -> Result<AllocationListResponse> {
        let path = format!("{}/allocations", billing_path(merchant_id));
        self.inner
            .request(HttpMethod::Get, &path, None, &[], None)
            .await
    }

    /// Retrieve the balance allocation for one shop (business profile).
    pub async fn retrieve(
        &self,
        merchant_id: &str,
        profile_id: &str,
    ) -> Result<AllocationResponse> {
        let path = format!(
            "{}/allocations/{}",
            billing_path(merchant_id),
            encode_segment(profile_id)
        );
        self.inner
            .request(HttpMethod::Get, &path, None, &[], None)
            .await
    }
}

/// Parameters for [`Billing::setup`].
#[derive(Debug, Clone, Default, Serialize)]
pub struct BillingSetupRequest {
    /// Currency the prepaid balance is denominated in (e.g. `"USD"`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub balance_currency: Option<String>,
    /// Any additional fields, merged verbatim.
    #[serde(flatten, skip_serializing_if = "serde_json::Map::is_empty")]
    pub extra: serde_json::Map<String, Value>,
}

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

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

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

    /// Set the balance currency.
    pub fn balance_currency(mut self, currency: impl Into<String>) -> Self {
        self.balance_currency = Some(currency.into());
        self
    }
}

/// Parameters for [`Billing::complete_setup`].
#[derive(Debug, Clone, Default, Serialize)]
pub struct BillingCompleteSetupRequest {
    /// The Stripe SetupIntent ID to confirm.
    pub setup_intent_id: String,
}

impl BillingCompleteSetupRequest {
    /// A request confirming the given Stripe SetupIntent.
    pub fn new(setup_intent_id: impl Into<String>) -> Self {
        Self {
            setup_intent_id: setup_intent_id.into(),
        }
    }
}

/// Parameters for [`Billing::topup`].
#[derive(Debug, Clone, Default, Serialize)]
pub struct TopupRequest {
    /// Amount to charge, in minor units.
    pub amount: i64,
    /// Client-supplied idempotency key, sent **in the body** (not as the
    /// `Idempotency-Key` header). When set, the server passes it to Stripe on
    /// the PaymentIntent create so a retry with the same key collapses into a
    /// single charge. Generate a fresh UUID per logical attempt and reuse it
    /// across retries of that attempt.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub idempotency_key: Option<String>,
}

impl TopupRequest {
    /// A top-up of `amount` minor units.
    pub fn new(amount: i64) -> Self {
        Self {
            amount,
            idempotency_key: None,
        }
    }

    /// Set the body-level idempotency key.
    pub fn idempotency_key(mut self, key: impl Into<String>) -> Self {
        self.idempotency_key = Some(key.into());
        self
    }
}

/// Parameters for [`BillingAllocations::transfer_in`] and
/// [`BillingAllocations::transfer_out`].
#[derive(Debug, Clone, Default, Serialize)]
pub struct AllocationTransferRequest {
    /// The shop (business profile) whose allocation is credited or debited.
    pub profile_id: String,
    /// Amount to move, in minor units.
    pub amount: i64,
    /// Client-supplied idempotency key, sent **in the body** (not as the
    /// `Idempotency-Key` header). When set, the server derives a deterministic
    /// ledger row ID from it, so a retry collides on the ledger's unique index
    /// and is treated as a success-replay rather than a fresh transfer.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub idempotency_key: Option<String>,
}

impl AllocationTransferRequest {
    /// A transfer of `amount` minor units against the given shop.
    pub fn new(profile_id: impl Into<String>, amount: i64) -> Self {
        Self {
            profile_id: profile_id.into(),
            amount,
            idempotency_key: None,
        }
    }

    /// Set the body-level idempotency key.
    pub fn idempotency_key(mut self, key: impl Into<String>) -> Self {
        self.idempotency_key = Some(key.into());
        self
    }
}

/// Parameters for [`Billing::update_auto_recharge`].
#[derive(Debug, Clone, Default, Serialize)]
pub struct AutoRechargeUpdateRequest {
    /// Whether auto-recharge is enabled.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub enabled: Option<bool>,
    /// Balance (minor units) at or below which a recharge is triggered.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub threshold_amount: Option<i64>,
    /// Amount (minor units) to charge when a recharge triggers.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub recharge_amount: Option<i64>,
    /// Any additional fields, merged verbatim.
    #[serde(flatten, skip_serializing_if = "serde_json::Map::is_empty")]
    pub extra: serde_json::Map<String, Value>,
}

/// Names of `AutoRechargeUpdateRequest`'s fields as they appear on the wire
/// (`extra` excluded).
const AUTO_RECHARGE_UPDATE_REQUEST_NAMED: &[&str] =
    &["enabled", "threshold_amount", "recharge_amount"];

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

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

    /// Enable or disable auto-recharge.
    pub fn enabled(mut self, enabled: bool) -> Self {
        self.enabled = Some(enabled);
        self
    }

    /// Set the trigger threshold and the recharge amount, both in minor units.
    pub fn amounts(mut self, threshold_amount: i64, recharge_amount: i64) -> Self {
        self.threshold_amount = Some(threshold_amount);
        self.recharge_amount = Some(recharge_amount);
        self
    }
}

/// Filter / pagination parameters for [`Billing::list_ledger`].
#[derive(Debug, Clone, Default)]
pub struct LedgerListParams {
    /// Maximum number of entries to return.
    pub limit: Option<i64>,
    /// Number of entries to skip.
    pub offset: Option<i64>,
    /// Only entries attributed to this shop (business profile).
    pub profile_id: Option<String>,
}

impl LedgerListParams {
    fn to_query(&self) -> Vec<(&'static str, String)> {
        let mut q = Vec::new();
        if let Some(v) = self.limit {
            q.push(("limit", v.to_string()));
        }
        if let Some(v) = self.offset {
            q.push(("offset", v.to_string()));
        }
        if let Some(v) = &self.profile_id {
            q.push(("profile_id", v.clone()));
        }
        q
    }
}

/// Filter / pagination parameters for [`Billing::list_blocked_attempts`].
#[derive(Debug, Clone, Default)]
pub struct BlockedAttemptListParams {
    /// Maximum number of entries to return.
    pub limit: Option<i64>,
    /// Number of entries to skip.
    pub offset: Option<i64>,
    /// Only attempts against this shop (business profile).
    pub profile_id: Option<String>,
    /// Only attempts with this reason: `"billing_suspended"`,
    /// `"billing_setup_incomplete"`, or `"allocation_suspended"`.
    pub block_reason: Option<String>,
    /// ISO 8601 timestamp; only attempts at or after this time.
    pub created_after: Option<String>,
    /// ISO 8601 timestamp; only attempts at or before this time.
    pub created_before: Option<String>,
}

impl BlockedAttemptListParams {
    fn to_query(&self) -> Vec<(&'static str, String)> {
        let mut q = Vec::new();
        if let Some(v) = self.limit {
            q.push(("limit", v.to_string()));
        }
        if let Some(v) = self.offset {
            q.push(("offset", v.to_string()));
        }
        if let Some(v) = &self.profile_id {
            q.push(("profile_id", v.clone()));
        }
        if let Some(v) = &self.block_reason {
            q.push(("block_reason", v.clone()));
        }
        if let Some(v) = &self.created_after {
            q.push(("created_after", v.clone()));
        }
        if let Some(v) = &self.created_before {
            q.push(("created_before", v.clone()));
        }
        q
    }
}

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

    const PROFILE_JSON: &str = r#"{
        "id": "bp_1",
        "merchant_id": "merch_1",
        "has_payment_method": true,
        "balance_amount": 1000,
        "balance_currency": "USD",
        "billing_status": "active",
        "auto_recharge": {"enabled": true, "threshold_amount": 1000, "recharge_amount": 20000},
        "hard_floor_amount": 0,
        "consecutive_recharge_failures": 0,
        "is_trusted": false,
        "created_at": "2026-01-01T00:00:00Z",
        "modified_at": "2026-01-02T00:00:00Z"
    }"#;

    const SETUP_JSON: &str = r#"{
        "billing_profile_id": "bp_1",
        "merchant_id": "merch_1",
        "stripe_customer_id": "cus_1",
        "setup_intent_id": "seti_1",
        "setup_intent_client_secret": "seti_1_secret_supersecretvalue",
        "billing_status": "setup_incomplete"
    }"#;

    const TOPUP_JSON: &str =
        r#"{"payment_intent_id":"pi_1","status":"succeeded","amount":5000,"currency":"USD"}"#;

    const ALLOCATION_JSON: &str = r#"{
        "id": "alc_1",
        "merchant_id": "merch_1",
        "profile_id": "pro_1",
        "balance_amount": 250,
        "balance_currency": "USD",
        "allocation_status": "active"
    }"#;

    const TRANSFER_JSON: &str = r#"{
        "allocation_id": "alc_1",
        "profile_id": "pro_1",
        "allocation_balance": 250,
        "host_balance": 9750,
        "ledger_entry_id": "led_1"
    }"#;

    #[tokio::test]
    async fn profile_gets_the_billing_root_and_encodes_the_merchant_id() {
        let (client, mock) = client_with(vec![Step::ok(PROFILE_JSON)]);
        let profile = client.billing().profile("merch/1").await.unwrap();
        assert_eq!(profile.balance_amount, 1000);
        assert!(profile.auto_recharge.enabled);

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

    #[tokio::test]
    async fn setup_posts_params_when_given() {
        let (client, mock) = client_with(vec![Step::ok(SETUP_JSON)]);
        let params = BillingSetupRequest::new().balance_currency("USD");
        let setup = client
            .billing()
            .setup("merch_1", Some(&params))
            .await
            .unwrap();
        assert_eq!(
            setup.setup_intent_client_secret,
            "seti_1_secret_supersecretvalue"
        );

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(seen[0].url, "https://api.test/billing/merch_1/setup");
        assert_eq!(seen[0].body_json()["balance_currency"], "USD");
    }

    #[tokio::test]
    async fn setup_sends_no_body_when_params_are_absent() {
        // Companion to the test above: an impl that always serialized some
        // body (e.g. `{}`) would still pass that one, but fails here.
        let (client, mock) = client_with(vec![Step::ok(SETUP_JSON)]);
        client.billing().setup("merch_1", None).await.unwrap();

        let seen = mock.seen.lock().unwrap();
        assert!(seen[0].body.is_none(), "setup(None) must send no body");
    }

    #[tokio::test]
    async fn complete_setup_posts_the_setup_intent_id() {
        let (client, mock) = client_with(vec![Step::ok(PROFILE_JSON)]);
        client
            .billing()
            .complete_setup("merch_1", &BillingCompleteSetupRequest::new("seti_1"))
            .await
            .unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(
            seen[0].url,
            "https://api.test/billing/merch_1/setup/complete"
        );
        assert_eq!(seen[0].body_json()["setup_intent_id"], "seti_1");
    }

    #[tokio::test]
    async fn topup_posts_amount_and_body_level_idempotency_key() {
        let (client, mock) = client_with(vec![Step::ok(TOPUP_JSON)]);
        let params = TopupRequest::new(5000).idempotency_key("uuid-1");
        let topup = client.billing().topup("merch_1", &params).await.unwrap();
        assert_eq!(topup.amount, 5000);
        assert_eq!(topup.payment_intent_id, "pi_1");

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(seen[0].url, "https://api.test/billing/merch_1/topup");
        let body = seen[0].body_json();
        assert_eq!(body["amount"], 5000);
        assert_eq!(body["idempotency_key"], "uuid-1");
        // The key is a *body* field here; it must not become the header.
        assert!(!seen[0].had_idempotency_key());
    }

    #[tokio::test]
    async fn topup_omits_the_idempotency_key_when_unset() {
        let (client, mock) = client_with(vec![Step::ok(TOPUP_JSON)]);
        client
            .billing()
            .topup("merch_1", &TopupRequest::new(1))
            .await
            .unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].body_json(), json!({"amount": 1}));
    }

    #[tokio::test]
    async fn list_ledger_serializes_its_filters() {
        let (client, mock) = client_with(vec![Step::ok(
            r#"{"entries":[{
                "id":"led_1","entry_type":"fee","amount":-250,"currency":"USD",
                "reference_kind":"payment","reference_id":"pay_1","balance_after":9750
            }],"total_count":1}"#,
        )]);
        let params = LedgerListParams {
            limit: Some(25),
            offset: Some(50),
            profile_id: Some("pro_1".to_string()),
        };
        let ledger = client
            .billing()
            .list_ledger("merch_1", Some(&params))
            .await
            .unwrap();
        assert_eq!(ledger.total_count, Some(1));
        assert_eq!(ledger.entries[0].amount, -250);

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "GET");
        assert_eq!(
            seen[0].url,
            "https://api.test/billing/merch_1/ledger?limit=25&offset=50&profile_id=pro_1"
        );
    }

    #[tokio::test]
    async fn list_blocked_attempts_serializes_every_filter() {
        let (client, mock) = client_with(vec![Step::ok(
            r#"{"entries":[{
                "id":"blk_1","merchant_id":"merch_1","payment_id":"pay_1",
                "block_reason":"billing_suspended"
            }]}"#,
        )]);
        let params = BlockedAttemptListParams {
            limit: Some(10),
            offset: Some(0),
            profile_id: Some("pro_1".to_string()),
            block_reason: Some("billing_suspended".to_string()),
            created_after: Some("2026-01-01T00:00:00Z".to_string()),
            created_before: Some("2026-02-01T00:00:00Z".to_string()),
        };
        let blocked = client
            .billing()
            .list_blocked_attempts("merch_1", Some(&params))
            .await
            .unwrap();
        assert_eq!(blocked.entries[0].block_reason, "billing_suspended");

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "GET");
        assert_eq!(
            seen[0].url,
            "https://api.test/billing/merch_1/blocked-attempts\
             ?limit=10&offset=0&profile_id=pro_1&block_reason=billing_suspended\
             &created_after=2026-01-01T00:00:00Z&created_before=2026-02-01T00:00:00Z"
        );
    }

    #[tokio::test]
    async fn list_blocked_attempts_sends_no_query_without_params() {
        let (client, mock) = client_with(vec![Step::ok(r#"{"entries":[]}"#)]);
        client
            .billing()
            .list_blocked_attempts("merch_1", None)
            .await
            .unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(
            seen[0].url,
            "https://api.test/billing/merch_1/blocked-attempts"
        );
    }

    #[tokio::test]
    async fn update_auto_recharge_patches_the_auto_recharge_path() {
        let (client, mock) = client_with(vec![Step::ok(PROFILE_JSON)]);
        let params = AutoRechargeUpdateRequest::new()
            .enabled(true)
            .amounts(1_000, 20_000);
        client
            .billing()
            .update_auto_recharge("merch_1", &params)
            .await
            .unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "PATCH");
        assert_eq!(
            seen[0].url,
            "https://api.test/billing/merch_1/auto-recharge"
        );
        let body = seen[0].body_json();
        assert_eq!(body["enabled"], true);
        assert_eq!(body["threshold_amount"], 1_000);
        assert_eq!(body["recharge_amount"], 20_000);
    }

    #[tokio::test]
    async fn allocation_transfers_post_to_their_own_paths() {
        let (client, mock) = client_with(vec![Step::ok(TRANSFER_JSON), Step::ok(TRANSFER_JSON)]);
        let allocations = client.billing().allocations();
        let params = AllocationTransferRequest::new("pro_1", 250).idempotency_key("uuid-2");
        let moved = allocations.transfer_in("merch_1", &params).await.unwrap();
        assert_eq!(moved.allocation_balance, 250);
        assert_eq!(moved.host_balance, 9750);
        allocations.transfer_out("merch_1", &params).await.unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(
            seen[0].url,
            "https://api.test/billing/merch_1/allocations/transfer-in"
        );
        let body = seen[0].body_json();
        assert_eq!(body["profile_id"], "pro_1");
        assert_eq!(body["amount"], 250);
        assert_eq!(body["idempotency_key"], "uuid-2");

        assert_eq!(seen[1].method, "POST");
        assert_eq!(
            seen[1].url,
            "https://api.test/billing/merch_1/allocations/transfer-out"
        );
    }

    #[tokio::test]
    async fn allocations_list_and_retrieve_hit_their_paths() {
        let (client, mock) = client_with(vec![
            Step::ok(&format!(r#"{{"allocations":[{ALLOCATION_JSON}]}}"#)),
            Step::ok(ALLOCATION_JSON),
        ]);
        let allocations = client.billing().allocations();
        let listed = allocations.list("merch_1").await.unwrap();
        assert_eq!(listed.allocations[0].profile_id, "pro_1");
        let one = allocations.retrieve("merch_1", "pro/1").await.unwrap();
        assert_eq!(one.balance_amount, 250);

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

    /// Drift guard: catches a new field added to `BillingSetupRequest` without
    /// a matching update to `BILLING_SETUP_REQUEST_NAMED`.
    #[test]
    fn billing_setup_request_named_fields_are_complete() {
        let req = BillingSetupRequest {
            balance_currency: Some("USD".to_string()),
            extra: serde_json::Map::new(),
        };
        let value = serde_json::to_value(req).unwrap();
        for key in value.as_object().expect("serializes to an object").keys() {
            assert!(
                BILLING_SETUP_REQUEST_NAMED.contains(&key.as_str()),
                "BILLING_SETUP_REQUEST_NAMED is missing wire key `{key}`"
            );
        }
    }

    /// Drift guard for `AUTO_RECHARGE_UPDATE_REQUEST_NAMED`.
    #[test]
    fn auto_recharge_update_request_named_fields_are_complete() {
        let req = AutoRechargeUpdateRequest {
            enabled: Some(true),
            threshold_amount: Some(1),
            recharge_amount: Some(2),
            extra: serde_json::Map::new(),
        };
        let value = serde_json::to_value(req).unwrap();
        for key in value.as_object().expect("serializes to an object").keys() {
            assert!(
                AUTO_RECHARGE_UPDATE_REQUEST_NAMED.contains(&key.as_str()),
                "AUTO_RECHARGE_UPDATE_REQUEST_NAMED is missing wire key `{key}`"
            );
        }
    }

    #[test]
    fn billing_setup_validate_rejects_colliding_extra_key() {
        let mut req = BillingSetupRequest::new();
        req.extra
            .insert("balance_currency".to_string(), json!("EUR"));
        assert!(matches!(
            req.validate().unwrap_err(),
            DelopayError::InvalidRequest(_)
        ));
    }

    #[test]
    fn auto_recharge_validate_rejects_colliding_extra_key() {
        let mut req = AutoRechargeUpdateRequest::new();
        req.extra.insert("enabled".to_string(), json!(false));
        assert!(matches!(
            req.validate().unwrap_err(),
            DelopayError::InvalidRequest(_)
        ));
    }

    #[tokio::test]
    async fn setup_rejects_a_colliding_extra_key_before_sending() {
        let (client, mock) = client_with(vec![Step::ok(SETUP_JSON)]);
        let mut params = BillingSetupRequest::new();
        params
            .extra
            .insert("balance_currency".to_string(), json!("EUR"));
        let err = client
            .billing()
            .setup("merch_1", Some(&params))
            .await
            .unwrap_err();
        assert!(matches!(err, DelopayError::InvalidRequest(_)));
        assert!(
            mock.seen.lock().unwrap().is_empty(),
            "an invalid request must not reach the transport"
        );
    }
}