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
//! The `checkout_recovery` resource: emails that bring the buyer of an
//! unfinished checkout back to a payable checkout, and the reactivation of an
//! expired checkout.
//!
//! A shop's automatic reminders are its `checkout_recovery.rule` setting.
//! This resource reads a checkout's recovery, previews and sends a message by
//! hand, stops a checkout's reminders, previews whom a rule would remind, and
//! reactivates an expired checkout.
//!
//! Reading needs the payment read grant; sending, stopping and testing need
//! the payment write grant. A shop-scoped caller acts on its own shop only.
//! Refusals are `IR_16` (400) with `error.data.reason`.

use std::fmt;
use std::sync::Arc;

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

use crate::core::encoding::{encode_segment, to_json_vec};
use crate::core::error::Result;
use crate::core::models::checkout_recovery::{
    CandidatePreviewResponse, CheckoutReactivation, CheckoutReactivationPreview,
    CheckoutRecoveryStatus, CheckoutReminder, CheckoutReminderList, ManualEmailPreview,
    TestEmailResponse,
};
use crate::http::client::Inner;
use crate::http::transport::HttpMethod;

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

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

    /// A checkout's recovery: whether and when the rule reminds it, every
    /// reason it does not, every message about it, and where its link goes.
    /// Any payment of the checkout may be named.
    /// `GET /checkout-recovery/payments/{payment_id}`
    pub async fn retrieve(&self, payment_id: &str) -> Result<CheckoutRecoveryStatus> {
        self.inner
            .request(HttpMethod::Get, &payment_path(payment_id), None, &[], None)
            .await
    }

    /// No automatic reminder about this checkout from now on.
    /// `POST /checkout-recovery/payments/{payment_id}/stop`
    pub async fn stop(&self, payment_id: &str) -> Result<CheckoutRecoveryStatus> {
        let path = format!("{}/stop", payment_path(payment_id));
        self.inner
            .request_body_keyed_with_query(HttpMethod::Post, &path, None, &[], None)
            .await
    }

    /// Undo [`stop`](Self::stop).
    /// `POST /checkout-recovery/payments/{payment_id}/resume`
    pub async fn resume(&self, payment_id: &str) -> Result<CheckoutRecoveryStatus> {
        let path = format!("{}/resume", payment_path(payment_id));
        self.inner
            .request_body_keyed_with_query(HttpMethod::Post, &path, None, &[], None)
            .await
    }

    /// Whether the checkout can be reactivated now, why not when it cannot,
    /// and what it would continue. Changes nothing.
    /// `GET /checkout-recovery/payments/{payment_id}/reactivation`
    pub async fn preview_reactivation(
        &self,
        payment_id: &str,
    ) -> Result<CheckoutReactivationPreview> {
        let path = format!("{}/reactivation", payment_path(payment_id));
        self.inner
            .request(HttpMethod::Get, &path, None, &[], None)
            .await
    }

    /// Continue an expired, unpaid checkout on a new payment for the same
    /// order, amount and currency. The payment it replaces is closed first, so
    /// the two can never both be charged; nothing is charged and nothing is
    /// sent to the buyer. A repeated request answers with the same checkout
    /// (`already_active`).
    /// `POST /checkout-recovery/payments/{payment_id}/reactivate`
    ///
    /// Refused (`IR_16`) while the checkout is paid, being paid, awaiting
    /// capture or authentication, cancelled or still open, or when no payment
    /// method could pay it.
    pub async fn reactivate(
        &self,
        payment_id: &str,
        params: &ReactivateCheckoutRequest,
    ) -> Result<CheckoutReactivation> {
        let path = format!("{}/reactivate", payment_path(payment_id));
        let body = to_json_vec(params)?;
        self.inner
            .request_body_keyed_with_query(HttpMethod::Post, &path, Some(&body), &[], None)
            .await
    }

    /// A message by hand as it would be sent now: recipient, sender, text,
    /// link and destination, and why it would be refused. Nothing is sent.
    /// `POST /checkout-recovery/payments/{payment_id}/email/preview`
    pub async fn preview_email(
        &self,
        payment_id: &str,
        params: &ManualEmailRequest,
    ) -> Result<ManualEmailPreview> {
        let path = format!("{}/email/preview", payment_path(payment_id));
        let body = to_json_vec(params)?;
        self.inner
            .request_body_keyed_with_query(HttpMethod::Post, &path, Some(&body), &[], None)
            .await
    }

    /// Send a message by hand, once per `idempotency_key`, composed again from
    /// the checkout as it is now.
    /// `POST /checkout-recovery/payments/{payment_id}/email`
    ///
    /// The API requires `idempotency_key` to send. The key is also sent as the
    /// `Idempotency-Key` header, so a network error or `5xx` is retried under
    /// it when retries are enabled; without a key the request is never
    /// retried. Refused when the checkout was paid or is being paid, was
    /// cancelled, the buyer unsubscribed, or no payment method could pay it.
    pub async fn send_email(
        &self,
        payment_id: &str,
        params: &ManualEmailRequest,
    ) -> Result<CheckoutReminder> {
        let path = format!("{}/email", payment_path(payment_id));
        let body = to_json_vec(params)?;
        self.inner
            .request_body_keyed(
                HttpMethod::Post,
                &path,
                Some(&body),
                params.idempotency_key.as_deref(),
            )
            .await
    }

    /// Messages to buyers, newest first.
    /// `GET /checkout-recovery/reminders`
    pub async fn list_reminders(
        &self,
        params: Option<&CheckoutReminderListParams>,
    ) -> Result<CheckoutReminderList> {
        let mut query = Vec::new();
        if let Some(params) = params {
            if let Some(profile_id) = &params.profile_id {
                query.push(("profile_id", profile_id.clone()));
            }
            if let Some(limit) = params.limit {
                query.push(("limit", limit.to_string()));
            }
            if let Some(offset) = params.offset {
                query.push(("offset", offset.to_string()));
            }
        }
        self.inner
            .request(
                HttpMethod::Get,
                "/checkout-recovery/reminders",
                None,
                &query,
                None,
            )
            .await
    }

    /// The shop's recent checkouts judged under a rule (the stored one, or the
    /// one given) as if switched on, with every reason. Nothing is sent.
    /// `POST /checkout-recovery/candidates`
    pub async fn preview_candidates(
        &self,
        params: &CandidatePreviewRequest,
    ) -> Result<CandidatePreviewResponse> {
        let body = to_json_vec(params)?;
        self.inner
            .request_body_keyed_with_query(
                HttpMethod::Post,
                "/checkout-recovery/candidates",
                Some(&body),
                &[],
                None,
            )
            .await
    }

    /// A reminder with sample values, to the signed-in user's own address.
    /// Dashboard sessions only.
    /// `POST /checkout-recovery/test-email`
    pub async fn send_test_email(&self, params: &TestEmailRequest) -> Result<TestEmailResponse> {
        let body = to_json_vec(params)?;
        self.inner
            .request_body_keyed_with_query(
                HttpMethod::Post,
                "/checkout-recovery/test-email",
                Some(&body),
                &[],
                None,
            )
            .await
    }
}

/// `/checkout-recovery/payments/{payment_id}`, percent-encoded.
fn payment_path(payment_id: &str) -> String {
    format!("/checkout-recovery/payments/{}", encode_segment(payment_id))
}

/// What a checkout message says.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum ReminderScenario {
    /// The buyer left the checkout unfinished.
    UnfinishedCheckout,
    /// The buyer's payment failed.
    PaymentFailed,
    /// A payment method the buyer wanted is offered again.
    MethodRestored,
}

/// Body of [`CheckoutRecovery::reactivate`].
///
/// The API refuses unknown fields here, so there is no `extra` map.
#[derive(Debug, Clone, Default, Serialize)]
pub struct ReactivateCheckoutRequest {
    /// How long the reactivated checkout takes payments, in seconds, between
    /// the preview's `min_validity_seconds` and `max_validity_seconds`. The
    /// original validity when absent.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub validity_seconds: Option<u32>,
}

impl ReactivateCheckoutRequest {
    /// Reactivate with the original validity.
    pub fn new() -> Self {
        Self::default()
    }

    /// Take payments for this many seconds.
    #[must_use]
    pub fn validity_seconds(mut self, validity_seconds: u32) -> Self {
        self.validity_seconds = Some(validity_seconds);
        self
    }
}

/// Body of [`CheckoutRecovery::preview_email`] and
/// [`CheckoutRecovery::send_email`].
///
/// The API refuses unknown fields here, so there is no `extra` map. `Debug`
/// is hand-written: `recipient` is redacted.
#[derive(Clone, Serialize)]
pub struct ManualEmailRequest {
    /// What the message says.
    pub scenario: ReminderScenario,
    /// Send to this address instead of the payment's buyer address.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub recipient: Option<String>,
    /// Write it in this language (`en`, `de`, `fr`, `es`, `it`, `nl`, `pt`,
    /// `pl`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub language: Option<String>,
    /// This subject instead of the shop's, with the same placeholders. Set
    /// with `body`, or neither.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub subject: Option<String>,
    /// This body instead of the shop's, with the same placeholders. Set with
    /// `subject`, or neither.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub body: Option<String>,
    /// Required to send, and sends once: a repeated request with the same key
    /// answers with the message it sent. 8 to 64 letters, digits, `-` or `_`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub idempotency_key: Option<String>,
}

impl fmt::Debug for ManualEmailRequest {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ManualEmailRequest")
            .field("scenario", &self.scenario)
            .field("recipient", &self.recipient.as_ref().map(|_| "<redacted>"))
            .field("language", &self.language)
            .field("subject", &self.subject)
            .field("body", &self.body)
            .field("idempotency_key", &self.idempotency_key)
            .finish()
    }
}

impl ManualEmailRequest {
    /// A message saying `scenario`, to the payment's buyer, in the shop's
    /// text.
    pub fn new(scenario: ReminderScenario) -> Self {
        Self {
            scenario,
            recipient: None,
            language: None,
            subject: None,
            body: None,
            idempotency_key: None,
        }
    }

    /// Send to this address instead of the buyer's.
    #[must_use]
    pub fn recipient(mut self, recipient: impl Into<String>) -> Self {
        self.recipient = Some(recipient.into());
        self
    }

    /// Write it in this language.
    #[must_use]
    pub fn language(mut self, language: impl Into<String>) -> Self {
        self.language = Some(language.into());
        self
    }

    /// Use this subject and body instead of the shop's.
    #[must_use]
    pub fn text(mut self, subject: impl Into<String>, body: impl Into<String>) -> Self {
        self.subject = Some(subject.into());
        self.body = Some(body.into());
        self
    }

    /// The key that makes [`CheckoutRecovery::send_email`] send once.
    #[must_use]
    pub fn idempotency_key(mut self, idempotency_key: impl Into<String>) -> Self {
        self.idempotency_key = Some(idempotency_key.into());
        self
    }
}

/// Query of [`CheckoutRecovery::list_reminders`].
#[derive(Debug, Clone, Default)]
pub struct CheckoutReminderListParams {
    /// Only this shop's messages. A shop user always reads their own shop's.
    pub profile_id: Option<String>,
    /// At most 100; 25 when absent.
    pub limit: Option<u32>,
    /// Messages to skip.
    pub offset: Option<u32>,
}

impl CheckoutReminderListParams {
    /// Every message the caller may read, first page.
    pub fn new() -> Self {
        Self::default()
    }

    /// Only this shop's messages.
    #[must_use]
    pub fn profile_id(mut self, profile_id: impl Into<String>) -> Self {
        self.profile_id = Some(profile_id.into());
        self
    }

    /// At most this many messages.
    #[must_use]
    pub fn limit(mut self, limit: u32) -> Self {
        self.limit = Some(limit);
        self
    }

    /// Skip this many messages.
    #[must_use]
    pub fn offset(mut self, offset: u32) -> Self {
        self.offset = Some(offset);
        self
    }
}

/// Body of [`CheckoutRecovery::preview_candidates`].
///
/// The API refuses unknown fields here, so there is no `extra` map.
#[derive(Debug, Clone, Default, Serialize)]
pub struct CandidatePreviewRequest {
    /// The shop. A shop user always previews their own shop.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub profile_id: Option<String>,
    /// A rule to judge with instead of the shop's stored one, in the shape of
    /// the `checkout_recovery.rule` setting; judged as if switched on.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub rule: Option<Value>,
    /// At most 200; 50 when absent.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub limit: Option<u32>,
}

impl CandidatePreviewRequest {
    /// Judge the caller's shop under its stored rule.
    pub fn new() -> Self {
        Self::default()
    }

    /// Judge this shop's checkouts.
    #[must_use]
    pub fn profile_id(mut self, profile_id: impl Into<String>) -> Self {
        self.profile_id = Some(profile_id.into());
        self
    }

    /// Judge under this rule instead of the stored one.
    #[must_use]
    pub fn rule(mut self, rule: Value) -> Self {
        self.rule = Some(rule);
        self
    }

    /// Judge at most this many checkouts.
    #[must_use]
    pub fn limit(mut self, limit: u32) -> Self {
        self.limit = Some(limit);
        self
    }
}

/// Body of [`CheckoutRecovery::send_test_email`].
///
/// The API refuses unknown fields here, so there is no `extra` map.
#[derive(Debug, Clone, Serialize)]
pub struct TestEmailRequest {
    /// The shop whose sender and texts to use.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub profile_id: Option<String>,
    /// What the message says.
    pub scenario: ReminderScenario,
    /// Write it in this language.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub language: Option<String>,
    /// An unsaved subject to test instead of the shop's. Set with `body`, or
    /// neither.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub subject: Option<String>,
    /// An unsaved body to test instead of the shop's. Set with `subject`, or
    /// neither.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub body: Option<String>,
}

impl TestEmailRequest {
    /// A test message saying `scenario`, in the shop's text.
    pub fn new(scenario: ReminderScenario) -> Self {
        Self {
            profile_id: None,
            scenario,
            language: None,
            subject: None,
            body: None,
        }
    }

    /// Use this shop's sender and texts.
    #[must_use]
    pub fn profile_id(mut self, profile_id: impl Into<String>) -> Self {
        self.profile_id = Some(profile_id.into());
        self
    }

    /// Write it in this language.
    #[must_use]
    pub fn language(mut self, language: impl Into<String>) -> Self {
        self.language = Some(language.into());
        self
    }

    /// Test this subject and body instead of the shop's.
    #[must_use]
    pub fn text(mut self, subject: impl Into<String>, body: impl Into<String>) -> Self {
        self.subject = Some(subject.into());
        self.body = Some(body.into());
        self
    }
}

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

    const REMINDER_JSON: &str = r#"{
        "id": "rem_1",
        "payment_id": "pay_1",
        "profile_id": "pro_1",
        "origin": "manual",
        "scenario": "unfinished_checkout",
        "status": "sent",
        "recipient": "j***@buyer.example",
        "test_mode": false,
        "attempts": 1,
        "created_at": "2026-01-01T00:00:00Z",
        "modified_at": "2026-01-01T00:00:01Z",
        "sent_at": "2026-01-01T00:00:01Z",
        "surprise_field": "r"
    }"#;

    fn status_json() -> String {
        format!(
            r#"{{
            "payment_id": "pay_1",
            "current_payment_id": "pay_2",
            "profile_id": "pro_1",
            "rule_enabled": true,
            "automatic": "excluded",
            "reasons": ["stopped"],
            "reminders_sent": 1,
            "max_reminders": 3,
            "stopped": true,
            "stopped_by": "usr_1",
            "recipient_unsubscribed": false,
            "destination": "new_checkout",
            "reminders": [{REMINDER_JSON}],
            "surprise_field": 1
        }}"#
        )
    }

    #[tokio::test]
    async fn retrieve_gets_the_payment_path_encoded() {
        let (client, mock) = client_with(vec![Step::ok(&status_json())]);
        let out = client.checkout_recovery().retrieve("pay/1").await.unwrap();
        assert_eq!(out.current_payment_id, "pay_2");
        assert_eq!(out.reasons, ["stopped"]);
        assert_eq!(out.max_reminders, 3);
        assert_eq!(out.reminders[0].id, "rem_1");
        assert_eq!(out.reminders[0].extra["surprise_field"], "r");
        assert_eq!(out.extra["surprise_field"], 1);

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

    #[tokio::test]
    async fn stop_posts_without_a_body() {
        let (client, mock) = client_with(vec![Step::ok(&status_json())]);
        let out = client.checkout_recovery().stop("pay_1").await.unwrap();
        assert!(out.stopped);

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(
            seen[0].url,
            "https://api.test/checkout-recovery/payments/pay_1/stop"
        );
        assert!(seen[0].body.is_none());
    }

    #[tokio::test]
    async fn resume_posts_without_a_body() {
        let (client, mock) = client_with(vec![Step::ok(&status_json())]);
        client.checkout_recovery().resume("pay_1").await.unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(
            seen[0].url,
            "https://api.test/checkout-recovery/payments/pay_1/resume"
        );
        assert!(seen[0].body.is_none());
    }

    #[tokio::test]
    async fn preview_reactivation_gets_the_reactivation_path() {
        let (client, mock) = client_with(vec![Step::ok(
            r#"{"payment_id":"pay_1","current_payment_id":"pay_1","profile_id":"pro_1",
                "status":"requires_payment_method","available":false,"blocked":"checkout_still_open",
                "amount":1999,"currency":"EUR","checkout_expired":false,
                "default_validity_seconds":900,"min_validity_seconds":300,"max_validity_seconds":86400,
                "reactivations":[{"payment_id":"pay_0","previous_payment_id":"pay_00",
                "reactivated_by":"usr_1","reactivated_at":"2026-01-01T00:00:00Z"}],
                "surprise_field":true}"#,
        )]);
        let out = client
            .checkout_recovery()
            .preview_reactivation("pay_1")
            .await
            .unwrap();
        assert!(!out.available);
        assert_eq!(out.blocked.as_deref(), Some("checkout_still_open"));
        assert_eq!(out.max_validity_seconds, 86400);
        assert_eq!(out.reactivations[0].reactivated_by, "usr_1");
        assert_eq!(out.extra["surprise_field"], true);

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "GET");
        assert_eq!(
            seen[0].url,
            "https://api.test/checkout-recovery/payments/pay_1/reactivation"
        );
    }

    const REACTIVATION_JSON: &str = r#"{"payment_id":"pay_1","previous_payment_id":"pay_1",
        "current_payment_id":"pay_2","checkout_url":"https://checkout.test/x",
        "already_active":false,"surprise_field":3}"#;

    #[tokio::test]
    async fn reactivate_posts_the_validity() {
        let (client, mock) = client_with(vec![Step::ok(REACTIVATION_JSON)]);
        let out = client
            .checkout_recovery()
            .reactivate(
                "pay_1",
                &ReactivateCheckoutRequest::new().validity_seconds(3600),
            )
            .await
            .unwrap();
        assert_eq!(out.current_payment_id, "pay_2");
        assert!(!out.already_active);
        assert_eq!(out.extra["surprise_field"], 3);

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(
            seen[0].url,
            "https://api.test/checkout-recovery/payments/pay_1/reactivate"
        );
        assert_eq!(seen[0].body_json(), json!({"validity_seconds": 3600}));
    }

    #[tokio::test]
    async fn reactivate_with_defaults_sends_an_empty_object() {
        let (client, mock) = client_with(vec![Step::ok(REACTIVATION_JSON)]);
        client
            .checkout_recovery()
            .reactivate("pay_1", &ReactivateCheckoutRequest::new())
            .await
            .unwrap();
        assert_eq!(mock.seen.lock().unwrap()[0].body_json(), json!({}));
    }

    #[tokio::test]
    async fn preview_email_posts_the_message_without_a_key_header() {
        let (client, mock) = client_with(vec![Step::ok(
            r#"{"scenario":"payment_failed","recipient":"ada@buyer.example","from_name":"Shop",
                "language":"de","subject":"S","text_body":"T","html_body":"<p>T</p>",
                "link":"https://checkout.test/x","destination":"open_checkout","surprise_field":1}"#,
        )]);
        let params = ManualEmailRequest::new(ReminderScenario::PaymentFailed)
            .language("de")
            .text("S", "T");
        let out = client
            .checkout_recovery()
            .preview_email("pay_1", &params)
            .await
            .unwrap();
        assert_eq!(out.language, "de");
        assert_eq!(out.destination, "open_checkout");
        assert_eq!(out.extra["surprise_field"], 1);

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(
            seen[0].url,
            "https://api.test/checkout-recovery/payments/pay_1/email/preview"
        );
        assert_eq!(
            seen[0].body_json(),
            json!({"scenario": "payment_failed", "language": "de", "subject": "S", "body": "T"})
        );
        assert!(!seen[0].had_idempotency_key());
    }

    #[tokio::test]
    async fn send_email_carries_the_body_key_as_the_idempotency_header() {
        let (client, mock) = client_with(vec![Step::ok(REMINDER_JSON)]);
        let params = ManualEmailRequest::new(ReminderScenario::UnfinishedCheckout)
            .idempotency_key("send-0001");
        let out = client
            .checkout_recovery()
            .send_email("pay/1", &params)
            .await
            .unwrap();
        assert_eq!(out.status, "sent");
        assert_eq!(out.extra["surprise_field"], "r");

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(
            seen[0].url,
            "https://api.test/checkout-recovery/payments/pay%2F1/email"
        );
        assert_eq!(
            seen[0].body_json(),
            json!({"scenario": "unfinished_checkout", "idempotency_key": "send-0001"})
        );
        assert_eq!(seen[0].header("idempotency-key"), Some("send-0001"));
    }

    #[tokio::test]
    async fn send_email_is_retried_after_a_5xx_under_the_same_key() {
        let (client, mock) = client_with_retries(
            vec![
                Step::status(500, r#"{"error":{"message":"boom"}}"#),
                Step::ok(REMINDER_JSON),
            ],
            2,
        );
        let params = ManualEmailRequest::new(ReminderScenario::UnfinishedCheckout)
            .idempotency_key("send-0001");
        client
            .checkout_recovery()
            .send_email("pay_1", &params)
            .await
            .unwrap();
        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen.len(), 2);
        assert_eq!(seen[1].header("idempotency-key"), Some("send-0001"));
    }

    #[tokio::test]
    async fn send_email_without_a_key_is_not_retried_after_a_5xx() {
        let (client, mock) = client_with_retries(
            vec![
                Step::status(500, r#"{"error":{"message":"boom"}}"#),
                Step::ok(REMINDER_JSON),
            ],
            2,
        );
        let out = client
            .checkout_recovery()
            .send_email(
                "pay_1",
                &ManualEmailRequest::new(ReminderScenario::UnfinishedCheckout),
            )
            .await;
        assert!(out.is_err());
        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen.len(), 1);
        assert!(!seen[0].had_idempotency_key());
    }

    #[tokio::test]
    async fn list_reminders_sends_the_page_query() {
        let (client, mock) = client_with(vec![Step::ok(&format!(
            r#"{{"data":[{REMINDER_JSON}],"surprise_field":"l"}}"#
        ))]);
        let params = CheckoutReminderListParams::new()
            .profile_id("pro_1")
            .limit(10)
            .offset(20);
        let out = client
            .checkout_recovery()
            .list_reminders(Some(&params))
            .await
            .unwrap();
        assert_eq!(out.data[0].scenario, "unfinished_checkout");
        assert_eq!(out.extra["surprise_field"], "l");

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "GET");
        assert_eq!(
            seen[0].url,
            "https://api.test/checkout-recovery/reminders?profile_id=pro_1&limit=10&offset=20"
        );
    }

    #[tokio::test]
    async fn list_reminders_without_params_sends_no_query() {
        let (client, mock) = client_with(vec![Step::ok(r#"{"data":[]}"#)]);
        client
            .checkout_recovery()
            .list_reminders(None)
            .await
            .unwrap();
        assert_eq!(
            mock.seen.lock().unwrap()[0].url,
            "https://api.test/checkout-recovery/reminders"
        );
    }

    #[tokio::test]
    async fn preview_candidates_posts_the_rule() {
        let (client, mock) = client_with(vec![Step::ok(
            r#"{"evaluated":2,"eligible":1,"purchase_history_complete":true,
                "candidates":[{"payment_id":"pay_1","current_payment_id":"pay_1",
                "created_at":"2026-01-01T00:00:00Z","amount":100,"test_mode":false,
                "automatic":"due","reasons":[]}],"surprise_field":1}"#,
        )]);
        let params = CandidatePreviewRequest::new()
            .profile_id("pro_1")
            .rule(json!({"enabled": true}))
            .limit(5);
        let out = client
            .checkout_recovery()
            .preview_candidates(&params)
            .await
            .unwrap();
        assert_eq!(out.evaluated, 2);
        assert_eq!(out.candidates[0].automatic, "due");
        assert_eq!(out.extra["surprise_field"], 1);

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(seen[0].url, "https://api.test/checkout-recovery/candidates");
        assert_eq!(
            seen[0].body_json(),
            json!({"profile_id": "pro_1", "rule": {"enabled": true}, "limit": 5})
        );
    }

    #[tokio::test]
    async fn send_test_email_posts_the_scenario() {
        let (client, mock) = client_with(vec![Step::ok(
            r#"{"recipient":"me@team.example","sent":true,"surprise_field":1}"#,
        )]);
        let params = TestEmailRequest::new(ReminderScenario::MethodRestored).profile_id("pro_1");
        let out = client
            .checkout_recovery()
            .send_test_email(&params)
            .await
            .unwrap();
        assert!(out.sent);
        assert_eq!(out.extra["surprise_field"], 1);

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(seen[0].url, "https://api.test/checkout-recovery/test-email");
        assert_eq!(
            seen[0].body_json(),
            json!({"profile_id": "pro_1", "scenario": "method_restored"})
        );
    }

    #[test]
    fn manual_email_request_debug_redacts_the_recipient() {
        let req = ManualEmailRequest::new(ReminderScenario::UnfinishedCheckout)
            .recipient("ada@buyer.example");
        let printed = format!("{req:?}");
        assert!(!printed.contains("buyer.example"), "{printed}");
        assert!(printed.contains("<redacted>"));
    }

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

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

    /// Mutation: switch the call site back to `request(.., None)` — the
    /// client-wide key is sent and the 503 replayed, so both assertions fail.
    #[tokio::test]
    async fn new_writes_do_not_inherit_the_client_key() {
        let (client, mock) = keyed_client_over_503s();
        assert!(client.checkout_recovery().stop("pay_1").await.is_err());
        assert_sent_once_unkeyed(&mock);

        let (client, mock) = keyed_client_over_503s();
        let params = TestEmailRequest::new(ReminderScenario::UnfinishedCheckout);
        assert!(
            client
                .checkout_recovery()
                .send_test_email(&params)
                .await
                .is_err()
        );
        assert_sent_once_unkeyed(&mock);
    }

    /// `send_email` deduplicates on the key in its body, so only that key is
    /// sent: without one, the client-wide key must not stand in for it.
    /// Mutation: route `send_email` through `request(.., None)` — the client
    /// key goes out and the 503 is replayed.
    #[tokio::test]
    async fn send_email_without_a_body_key_ignores_the_client_key() {
        let (client, mock) = keyed_client_over_503s();
        let params = ManualEmailRequest::new(ReminderScenario::UnfinishedCheckout);
        assert!(
            client
                .checkout_recovery()
                .send_email("pay_1", &params)
                .await
                .is_err()
        );
        assert_sent_once_unkeyed(&mock);
    }

    /// The exception: a body key is sent as the header even on a client with
    /// its own key, and each 503 is replayed under it. The script holds one
    /// step per attempt the 2-retry budget allows: 503, 503, then success.
    /// Mutation: route `send_email` through `request_body_keyed_with_query(.., None)` — no key goes
    /// out, the first 503 ends the call, and every assertion here fails.
    #[tokio::test]
    async fn send_email_with_a_body_key_sends_it_over_the_client_key_and_retries() {
        let (client, mock) = crate::http::mock::client_with_retries(
            vec![
                Step::status(503, "{}"),
                Step::status(503, "{}"),
                Step::ok(REMINDER_JSON),
            ],
            2,
        );
        let client = client.with_idempotency_key("client-wide-key");
        let params = ManualEmailRequest::new(ReminderScenario::UnfinishedCheckout)
            .idempotency_key("send-0002");
        let out = client
            .checkout_recovery()
            .send_email("pay_1", &params)
            .await;
        assert!(out.is_ok(), "{out:?}");

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen.len(), 3);
        for attempt in seen.iter() {
            assert_eq!(attempt.header("idempotency-key"), Some("send-0002"));
        }
    }
}