delopay 0.2.1

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
//! The `subscriptions` resource: recurring billing through a connected
//! billing processor (Stripe Billing, PayPal, …).
//!
//! Subscription endpoints are **profile-scoped**: the backend needs an
//! `x-profile-id` header to resolve the shop / billing processor and rejects
//! calls without one (`IR_04`). Scope the resource once with
//! [`Subscriptions::with_profile_id`]:
//!
//! ```no_run
//! # use delopay::Delopay;
//! # async fn run(client: Delopay) -> delopay::Result<()> {
//! let subscriptions = client.subscriptions().with_profile_id("pro_your_shop");
//! let sub = subscriptions.retrieve("sub_123").await?;
//! # Ok(())
//! # }
//! ```

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::common::{Address, AuthenticationType, CaptureMethod, SetupFutureUsage};
use crate::core::models::subscription::{
    CancelSubscriptionResponse, ConfirmSubscriptionResponse, PauseSubscriptionResponse,
    ResumeSubscriptionResponse, SubscriptionEstimateResponse, SubscriptionItem,
    SubscriptionResponse,
};
use crate::http::client::Inner;
use crate::http::transport::HttpMethod;
use crate::resources::ValidateRequest;

/// The `subscriptions` resource, obtained via [`crate::Delopay::subscriptions`].
///
/// See the [module docs](self) for the required profile scoping.
#[derive(Debug, Clone)]
pub struct Subscriptions {
    inner: Arc<Inner>,
    profile_id: Option<String>,
}

impl Subscriptions {
    pub(crate) fn new(inner: Arc<Inner>) -> Self {
        Self {
            inner,
            profile_id: None,
        }
    }

    /// Scope every call from this resource to one shop (business profile) by
    /// sending its ID as the `x-profile-id` header.
    #[must_use]
    pub fn with_profile_id(mut self, profile_id: impl Into<String>) -> Self {
        self.profile_id = Some(profile_id.into());
        self
    }

    /// The scoping headers for this resource, if a profile was set.
    fn headers(&self) -> Vec<(&str, &str)> {
        match &self.profile_id {
            Some(id) => vec![("x-profile-id", id.as_str())],
            None => Vec::new(),
        }
    }

    async fn send<T: serde::de::DeserializeOwned>(
        &self,
        method: HttpMethod,
        path: &str,
        body: Option<&[u8]>,
        query: &[(&str, String)],
    ) -> Result<T> {
        self.inner
            .request_with_headers(method, path, body, query, None, &self.headers())
            .await
    }

    /// Create and immediately confirm a subscription.
    ///
    /// For billing processors that require buyer approval (e.g. PayPal), the
    /// response carries a
    /// [`redirect_url`](ConfirmSubscriptionResponse::redirect_url) the
    /// customer must be sent to.
    pub async fn create_and_confirm(
        &self,
        params: &CreateAndConfirmSubscriptionRequest,
    ) -> Result<ConfirmSubscriptionResponse> {
        params.validate()?;
        let body = to_json_vec(params)?;
        self.send(HttpMethod::Post, "/subscriptions", Some(&body), &[])
            .await
    }

    /// Create a subscription without confirming it.
    pub async fn create(&self, params: &CreateSubscriptionRequest) -> Result<SubscriptionResponse> {
        params.validate()?;
        let body = to_json_vec(params)?;
        self.send(HttpMethod::Post, "/subscriptions/create", Some(&body), &[])
            .await
    }

    /// Retrieve a subscription by ID.
    pub async fn retrieve(&self, subscription_id: &str) -> Result<SubscriptionResponse> {
        let path = format!("/subscriptions/{}", encode_segment(subscription_id));
        self.send(HttpMethod::Get, &path, None, &[]).await
    }

    /// Confirm a previously created subscription. Like
    /// [`create_and_confirm`](Self::create_and_confirm), the response may
    /// carry a `redirect_url` for processors that require buyer approval.
    pub async fn confirm(
        &self,
        subscription_id: &str,
        params: &ConfirmSubscriptionRequest,
    ) -> Result<ConfirmSubscriptionResponse> {
        let path = format!("/subscriptions/{}/confirm", encode_segment(subscription_id));
        let body = to_json_vec(params)?;
        self.send(HttpMethod::Post, &path, Some(&body), &[]).await
    }

    /// Change a subscription's plan/price.
    pub async fn update(
        &self,
        subscription_id: &str,
        params: &UpdateSubscriptionRequest,
    ) -> Result<SubscriptionResponse> {
        let path = format!("/subscriptions/{}/update", encode_segment(subscription_id));
        let body = to_json_vec(params)?;
        self.send(HttpMethod::Put, &path, Some(&body), &[]).await
    }

    /// List the profile's subscriptions.
    pub async fn list(
        &self,
        params: Option<&SubscriptionListParams>,
    ) -> Result<Vec<SubscriptionResponse>> {
        let query = params
            .map(SubscriptionListParams::to_query)
            .unwrap_or_default();
        self.send(HttpMethod::Get, "/subscriptions/list", None, &query)
            .await
    }

    /// Estimate the cost of a subscription before creating it.
    pub async fn estimate(
        &self,
        params: &SubscriptionEstimateParams,
    ) -> Result<SubscriptionEstimateResponse> {
        self.send(
            HttpMethod::Get,
            "/subscriptions/estimate",
            None,
            &params.to_query(),
        )
        .await
    }

    /// List purchasable subscription items (plans or addons).
    pub async fn items(&self, params: &SubscriptionItemsParams) -> Result<Vec<SubscriptionItem>> {
        self.send(
            HttpMethod::Get,
            "/subscriptions/items",
            None,
            &params.to_query(),
        )
        .await
    }

    /// Pause a subscription.
    pub async fn pause(
        &self,
        subscription_id: &str,
        params: Option<&PauseSubscriptionRequest>,
    ) -> Result<PauseSubscriptionResponse> {
        let path = format!("/subscriptions/{}/pause", encode_segment(subscription_id));
        let body = Self::body_or_empty_object(params)?;
        self.send(HttpMethod::Post, &path, Some(&body), &[]).await
    }

    /// Resume a paused subscription.
    pub async fn resume(
        &self,
        subscription_id: &str,
        params: Option<&ResumeSubscriptionRequest>,
    ) -> Result<ResumeSubscriptionResponse> {
        let path = format!("/subscriptions/{}/resume", encode_segment(subscription_id));
        let body = Self::body_or_empty_object(params)?;
        self.send(HttpMethod::Post, &path, Some(&body), &[]).await
    }

    /// Cancel a subscription.
    pub async fn cancel(
        &self,
        subscription_id: &str,
        params: Option<&CancelSubscriptionRequest>,
    ) -> Result<CancelSubscriptionResponse> {
        let path = format!("/subscriptions/{}/cancel", encode_segment(subscription_id));
        let body = Self::body_or_empty_object(params)?;
        self.send(HttpMethod::Post, &path, Some(&body), &[]).await
    }

    /// Serialize `params`, defaulting to `{}` when absent: the backend
    /// rejects a bodyless POST on these endpoints ("Unsupported content
    /// type"), so the request must always carry a JSON body.
    fn body_or_empty_object<T: Serialize>(params: Option<&T>) -> Result<Vec<u8>> {
        match params {
            Some(p) => to_json_vec(p),
            None => Ok(b"{}".to_vec()),
        }
    }
}

/// Payment options for [`Subscriptions::create`].
#[derive(Debug, Clone, Default, Serialize)]
pub struct CreateSubscriptionPaymentDetails {
    /// URL the customer is returned to after completing the purchase.
    pub return_url: String,
    /// How the saved payment method may be used for future cycles.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub setup_future_usage: Option<SetupFutureUsage>,
    /// How and when funds are captured.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub capture_method: Option<CaptureMethod>,
    /// Whether to request 3-D Secure.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub authentication_type: Option<AuthenticationType>,
    /// Payment type hint — see the API reference.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub payment_type: Option<String>,
}

/// Parameters for [`Subscriptions::create`].
#[derive(Debug, Clone, Default, Serialize)]
pub struct CreateSubscriptionRequest {
    /// Price to bill (from [`Subscriptions::items`]).
    pub item_price_id: String,
    /// Customer to subscribe.
    pub customer_id: String,
    /// Payment options for the first charge.
    pub payment_details: CreateSubscriptionPaymentDetails,
    /// Your own reference for this subscription.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub merchant_reference_id: Option<String>,
    /// Plan the price belongs to.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub plan_id: Option<String>,
    /// Coupon to apply.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub coupon_code: Option<String>,
    /// Billing address.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub billing: Option<Address>,
    /// Shipping address.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub shipping: Option<Address>,
    /// Any additional create fields not modeled above are merged in verbatim.
    #[serde(flatten, skip_serializing_if = "serde_json::Map::is_empty")]
    pub extra: serde_json::Map<String, Value>,
}

/// Names of `CreateSubscriptionRequest`'s fields as they appear on the wire
/// (`extra` excluded). See `PAYMENT_CREATE_REQUEST_NAMED` in `payments.rs`
/// for why this list lives next to the struct.
const CREATE_SUBSCRIPTION_REQUEST_NAMED: &[&str] = &[
    "item_price_id",
    "customer_id",
    "payment_details",
    "merchant_reference_id",
    "plan_id",
    "coupon_code",
    "billing",
    "shipping",
];

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

/// Payment options for [`Subscriptions::create_and_confirm`].
#[derive(Debug, Clone, Default, Serialize)]
pub struct SubscriptionPaymentDetails {
    /// Payment method family, e.g. `"card"`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub payment_method: Option<String>,
    /// Payment method sub-type, e.g. `"credit"`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub payment_method_type: Option<String>,
    /// Payment method data (open shape — see the API reference).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub payment_method_data: Option<Value>,
    /// How the saved payment method may be used for future cycles.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub setup_future_usage: Option<SetupFutureUsage>,
    /// Customer acceptance record for the mandate (open shape).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub customer_acceptance: Option<Value>,
    /// URL the customer is returned to after completing the purchase.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub return_url: Option<String>,
    /// How and when funds are captured.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub capture_method: Option<CaptureMethod>,
    /// Whether to request 3-D Secure.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub authentication_type: Option<AuthenticationType>,
    /// Payment type hint — see the API reference.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub payment_type: Option<String>,
    /// Saved payment method to charge.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub payment_method_id: Option<String>,
}

/// Parameters for [`Subscriptions::create_and_confirm`].
#[derive(Debug, Clone, Default, Serialize)]
pub struct CreateAndConfirmSubscriptionRequest {
    /// Price to bill (from [`Subscriptions::items`]).
    pub item_price_id: String,
    /// Customer to subscribe.
    pub customer_id: String,
    /// Payment options for the first charge.
    pub payment_details: SubscriptionPaymentDetails,
    /// Plan the price belongs to.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub plan_id: Option<String>,
    /// Coupon to apply.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub coupon_code: Option<String>,
    /// Billing address.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub billing: Option<Address>,
    /// Shipping address.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub shipping: Option<Address>,
    /// Your own reference for this subscription.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub merchant_reference_id: Option<String>,
    /// Any additional fields not modeled above are merged in verbatim.
    #[serde(flatten, skip_serializing_if = "serde_json::Map::is_empty")]
    pub extra: serde_json::Map<String, Value>,
}

/// Names of `CreateAndConfirmSubscriptionRequest`'s fields as they appear on
/// the wire (`extra` excluded).
const CREATE_AND_CONFIRM_SUBSCRIPTION_REQUEST_NAMED: &[&str] = &[
    "item_price_id",
    "customer_id",
    "payment_details",
    "plan_id",
    "coupon_code",
    "billing",
    "shipping",
    "merchant_reference_id",
];

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

/// Payment options for [`Subscriptions::confirm`].
#[derive(Debug, Clone, Default, Serialize)]
pub struct ConfirmSubscriptionPaymentDetails {
    /// Payment method family, e.g. `"card"`.
    pub payment_method: String,
    /// Payment method sub-type, e.g. `"credit"`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub payment_method_type: Option<String>,
    /// Payment method data (open shape — see the API reference).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub payment_method_data: Option<Value>,
    /// Customer acceptance record for the mandate (open shape).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub customer_acceptance: Option<Value>,
    /// Billing address.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub billing: Option<Address>,
    /// Shipping address.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub shipping: Option<Address>,
    /// Payment type hint — see the API reference.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub payment_type: Option<String>,
    /// Token of a saved payment method to charge.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub payment_token: Option<String>,
}

/// Parameters for [`Subscriptions::confirm`].
#[derive(Debug, Clone, Default, Serialize)]
pub struct ConfirmSubscriptionRequest {
    /// Payment options for the confirming charge.
    pub payment_details: ConfirmSubscriptionPaymentDetails,
    /// Client secret minted at create time; required for client-side confirm.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub client_secret: Option<String>,
}

/// Parameters for [`Subscriptions::update`].
#[derive(Debug, Clone, Default, Serialize)]
pub struct UpdateSubscriptionRequest {
    /// Plan to move the subscription to.
    pub plan_id: String,
    /// Price within that plan.
    pub item_price_id: String,
}

/// Parameters for [`Subscriptions::pause`].
#[derive(Debug, Clone, Default, Serialize)]
pub struct PauseSubscriptionRequest {
    /// When to pause: `"immediately"`, `"end_of_term"`, or `"specific_date"`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub pause_option: Option<String>,
    /// ISO 8601 timestamp; honoured when `pause_option` is `"specific_date"`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub pause_at: Option<String>,
}

/// Parameters for [`Subscriptions::resume`].
#[derive(Debug, Clone, Default, Serialize)]
pub struct ResumeSubscriptionRequest {
    /// When to resume: `"immediately"` or `"specific_date"`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub resume_option: Option<String>,
    /// ISO 8601 timestamp; honoured when `resume_option` is `"specific_date"`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub resume_date: Option<String>,
    /// What to do with charges accrued while paused:
    /// `"invoice_immediately"` or `"add_to_unbilled_charges"`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub charges_handling: Option<String>,
    /// What to do with unpaid invoices: `"no_action"` or
    /// `"schedule_payment_collection"`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub unpaid_invoices_handling: Option<String>,
}

/// Parameters for [`Subscriptions::cancel`].
#[derive(Debug, Clone, Default, Serialize)]
pub struct CancelSubscriptionRequest {
    /// When to cancel: `"immediately"`, `"end_of_term"`, or `"specific_date"`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cancel_option: Option<String>,
    /// ISO 8601 timestamp; honoured when `cancel_option` is `"specific_date"`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cancel_at: Option<String>,
    /// What to do with unbilled charges: `"invoice"` or `"delete"`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub unbilled_charges_option: Option<String>,
    /// Credit handling for the current term: `"none"`, `"prorate"`, or
    /// `"full"`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub credit_option_for_current_term_charges: Option<String>,
    /// Receivables handling: `"no_action"`, `"schedule_payment_collection"`,
    /// or `"write_off"`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub account_receivables_handling: Option<String>,
    /// Refundable-credit handling: `"no_action"` or `"schedule_refund"`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub refundable_credits_handling: Option<String>,
    /// Your reason code for the cancellation.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cancel_reason_code: Option<String>,
}

/// Pagination parameters for [`Subscriptions::list`].
#[derive(Debug, Clone, Default)]
pub struct SubscriptionListParams {
    /// Maximum number of subscriptions to return.
    pub limit: Option<i64>,
    /// Number of subscriptions to skip.
    pub offset: Option<i64>,
}

impl SubscriptionListParams {
    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()));
        }
        q
    }
}

/// Query parameters for [`Subscriptions::items`].
#[derive(Debug, Clone, Default)]
pub struct SubscriptionItemsParams {
    /// Item kind to list: `"plan"` or `"addon"`. Required by the API.
    pub item_type: String,
    /// Client secret, for client-side listing.
    pub client_secret: Option<String>,
    /// Maximum number of items to return.
    pub limit: Option<i64>,
    /// Number of items to skip.
    pub offset: Option<i64>,
}

impl SubscriptionItemsParams {
    /// Parameters listing items of the given kind (`"plan"` or `"addon"`).
    pub fn new(item_type: impl Into<String>) -> Self {
        Self {
            item_type: item_type.into(),
            ..Default::default()
        }
    }

    fn to_query(&self) -> Vec<(&'static str, String)> {
        let mut q = vec![("item_type", self.item_type.clone())];
        if let Some(v) = &self.client_secret {
            q.push(("client_secret", v.clone()));
        }
        if let Some(v) = self.limit {
            q.push(("limit", v.to_string()));
        }
        if let Some(v) = self.offset {
            q.push(("offset", v.to_string()));
        }
        q
    }
}

/// Query parameters for [`Subscriptions::estimate`].
#[derive(Debug, Clone, Default)]
pub struct SubscriptionEstimateParams {
    /// Price to estimate. Required by the API.
    pub item_price_id: String,
    /// Plan the price belongs to.
    pub plan_id: Option<String>,
    /// Coupon to apply to the estimate.
    pub coupon_code: Option<String>,
}

impl SubscriptionEstimateParams {
    /// Parameters estimating the given price.
    pub fn new(item_price_id: impl Into<String>) -> Self {
        Self {
            item_price_id: item_price_id.into(),
            ..Default::default()
        }
    }

    fn to_query(&self) -> Vec<(&'static str, String)> {
        let mut q = vec![("item_price_id", self.item_price_id.clone())];
        if let Some(v) = &self.plan_id {
            q.push(("plan_id", v.clone()));
        }
        if let Some(v) = &self.coupon_code {
            q.push(("coupon_code", v.clone()));
        }
        q
    }
}

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

    const SUB_JSON: &str = r#"{"id": "sub_1", "status": "active"}"#;
    const CONFIRM_JSON: &str = r#"{
        "id": "sub_1", "status": "pending",
        "redirect_url": "https://paypal.test/approve"
    }"#;

    fn create_and_confirm_request() -> CreateAndConfirmSubscriptionRequest {
        CreateAndConfirmSubscriptionRequest {
            item_price_id: "price_1".to_string(),
            customer_id: "cus_1".to_string(),
            payment_details: SubscriptionPaymentDetails {
                payment_method: Some("card".to_string()),
                ..Default::default()
            },
            ..Default::default()
        }
    }

    #[tokio::test]
    async fn sends_x_profile_id_header_when_scoped() {
        // The backend rejects unscoped subscription calls (IR_04); a mutation
        // dropping the header push makes this fail.
        let (client, mock) = client_with(vec![Step::ok(SUB_JSON)]);
        client
            .subscriptions()
            .with_profile_id("pro_1")
            .retrieve("sub_1")
            .await
            .unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].header("x-profile-id"), Some("pro_1"));
    }

    #[tokio::test]
    async fn omits_the_profile_header_when_unscoped() {
        // Companion to the test above: without it, an impl that always sent
        // some x-profile-id value would still pass.
        let (client, mock) = client_with(vec![Step::ok(SUB_JSON)]);
        client.subscriptions().retrieve("sub_1").await.unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].header("x-profile-id"), None);
    }

    #[tokio::test]
    async fn create_and_confirm_posts_to_subscriptions_root() {
        let (client, mock) = client_with(vec![Step::ok(CONFIRM_JSON)]);
        let out = client
            .subscriptions()
            .with_profile_id("pro_1")
            .create_and_confirm(&create_and_confirm_request())
            .await
            .unwrap();
        assert_eq!(
            out.redirect_url.as_deref(),
            Some("https://paypal.test/approve")
        );

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(seen[0].url, "https://api.test/subscriptions");
        let body = seen[0].body_json();
        assert_eq!(body["item_price_id"], "price_1");
        assert_eq!(body["payment_details"]["payment_method"], "card");
    }

    #[tokio::test]
    async fn update_puts_to_the_update_path() {
        let (client, mock) = client_with(vec![Step::ok(SUB_JSON)]);
        let req = UpdateSubscriptionRequest {
            plan_id: "plan_2".to_string(),
            item_price_id: "price_2".to_string(),
        };
        client.subscriptions().update("sub_1", &req).await.unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "PUT");
        assert_eq!(seen[0].url, "https://api.test/subscriptions/sub_1/update");
    }

    #[tokio::test]
    async fn pause_resume_cancel_send_an_empty_object_body_by_default() {
        // The backend rejects a bodyless POST on these endpoints
        // ("Unsupported content type"), so `None` params must still produce
        // a `{}` body — a mutation sending no body fails here.
        let (client, mock) = client_with(vec![
            Step::ok(r#"{"id":"sub_1","status":"paused"}"#),
            Step::ok(r#"{"id":"sub_1","status":"active"}"#),
            Step::ok(r#"{"id":"sub_1","status":"cancelled"}"#),
        ]);
        let subs = client.subscriptions();
        subs.pause("sub_1", None).await.unwrap();
        subs.resume("sub_1", None).await.unwrap();
        subs.cancel("sub_1", None).await.unwrap();

        let seen = mock.seen.lock().unwrap();
        let paths = [
            "https://api.test/subscriptions/sub_1/pause",
            "https://api.test/subscriptions/sub_1/resume",
            "https://api.test/subscriptions/sub_1/cancel",
        ];
        for (i, path) in paths.iter().enumerate() {
            assert_eq!(seen[i].url, *path);
            assert_eq!(
                seen[i].body_json(),
                json!({}),
                "call {i} must carry an empty JSON object body"
            );
        }
    }

    #[tokio::test]
    async fn cancel_serializes_scheduling_options() {
        let (client, mock) = client_with(vec![Step::ok(r#"{"id":"sub_1","status":"cancelled"}"#)]);
        let req = CancelSubscriptionRequest {
            cancel_option: Some("end_of_term".to_string()),
            cancel_reason_code: Some("too_expensive".to_string()),
            ..Default::default()
        };
        client
            .subscriptions()
            .cancel("sub_1", Some(&req))
            .await
            .unwrap();

        let seen = mock.seen.lock().unwrap();
        let body = seen[0].body_json();
        assert_eq!(body["cancel_option"], "end_of_term");
        assert_eq!(body["cancel_reason_code"], "too_expensive");
    }

    #[tokio::test]
    async fn read_endpoints_serialize_their_queries() {
        let (client, mock) = client_with(vec![
            Step::ok("[]"),
            Step::ok(r#"{"amount":999,"currency":"EUR","line_items":[]}"#),
            Step::ok("[]"),
        ]);
        let subs = client.subscriptions();
        subs.list(Some(&SubscriptionListParams {
            limit: Some(10),
            offset: Some(20),
        }))
        .await
        .unwrap();
        subs.estimate(&SubscriptionEstimateParams::new("price_1"))
            .await
            .unwrap();
        subs.items(&SubscriptionItemsParams::new("plan"))
            .await
            .unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(
            seen[0].url,
            "https://api.test/subscriptions/list?limit=10&offset=20"
        );
        assert_eq!(
            seen[1].url,
            "https://api.test/subscriptions/estimate?item_price_id=price_1"
        );
        assert_eq!(
            seen[2].url,
            "https://api.test/subscriptions/items?item_type=plan"
        );
    }

    /// Drift guard for `CREATE_SUBSCRIPTION_REQUEST_NAMED`.
    #[test]
    fn create_request_named_fields_are_complete() {
        let req = CreateSubscriptionRequest {
            item_price_id: "price_1".to_string(),
            customer_id: "cus_1".to_string(),
            payment_details: CreateSubscriptionPaymentDetails {
                return_url: "https://example.com/r".to_string(),
                setup_future_usage: Some(SetupFutureUsage::OffSession),
                capture_method: Some(CaptureMethod::Automatic),
                authentication_type: Some(AuthenticationType::NoThreeDs),
                payment_type: Some("recurring".to_string()),
            },
            merchant_reference_id: Some("ref_1".to_string()),
            plan_id: Some("plan_1".to_string()),
            coupon_code: Some("SAVE10".to_string()),
            billing: Some(Address::default()),
            shipping: Some(Address::default()),
            extra: serde_json::Map::new(),
        };
        let value = serde_json::to_value(req).unwrap();
        for key in value.as_object().unwrap().keys() {
            assert!(
                CREATE_SUBSCRIPTION_REQUEST_NAMED.contains(&key.as_str()),
                "CREATE_SUBSCRIPTION_REQUEST_NAMED is missing wire key `{key}`"
            );
        }
    }

    /// Drift guard for `CREATE_AND_CONFIRM_SUBSCRIPTION_REQUEST_NAMED`.
    #[test]
    fn create_and_confirm_request_named_fields_are_complete() {
        let req = CreateAndConfirmSubscriptionRequest {
            plan_id: Some("plan_1".to_string()),
            coupon_code: Some("SAVE10".to_string()),
            billing: Some(Address::default()),
            shipping: Some(Address::default()),
            merchant_reference_id: Some("ref_1".to_string()),
            ..create_and_confirm_request()
        };
        let value = serde_json::to_value(req).unwrap();
        for key in value.as_object().unwrap().keys() {
            assert!(
                CREATE_AND_CONFIRM_SUBSCRIPTION_REQUEST_NAMED.contains(&key.as_str()),
                "CREATE_AND_CONFIRM_SUBSCRIPTION_REQUEST_NAMED is missing wire key `{key}`"
            );
        }
    }

    #[test]
    fn create_validate_rejects_colliding_extra_key() {
        let mut req = CreateSubscriptionRequest::default();
        req.extra.insert("customer_id".to_string(), json!("cus_2"));
        assert!(matches!(
            req.validate().unwrap_err(),
            DelopayError::InvalidRequest(_)
        ));
    }
}