delopay 0.20.0

Official Rust SDK for the DeloPay payments API
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
//! Buyer-side clients for a single hosted-checkout payment.
//!
//! These are the calls a checkout page makes on the shopper's behalf. They
//! authenticate with the two browser-safe credentials — the payment's
//! [`ClientSecret`] and the merchant's [`PublishableKey`] — and there is no
//! way to hand either client a [`crate::credentials::SecretKey`]: the
//! constructors do not accept one, so putting a secret key on a checkout page
//! is a compile error rather than an incident.
//!
//! Two types, because the two credentials unlock different routes:
//!
//! - [`PaymentLinkSession`] needs only the client secret. It covers the
//!   `/payment-link/{merchant}/{payment}/*` side channel — rail catalogs, the
//!   vault handshake, checkout telemetry — which authenticates with
//!   `Authorization: Bearer <client_secret>`.
//! - [`CheckoutSession`] adds the publishable key and, with it, the
//!   `/payments/*` and `/payment-methods` routes that actually read and
//!   confirm the payment. It exposes every [`PaymentLinkSession`] call too,
//!   so a page holding both credentials only needs this one.
//!
//! Splitting them is what removes the runtime "missing credential" error the
//! other SDKs have to raise: a call you cannot authenticate does not exist on
//! the type you built.
//!
//! # Credential isolation
//!
//! Each route carries **exactly one** credential. The bearer routes go
//! through a client with no API key at all — not one whose key is merely
//! unused — so a `/payment-link/*` request cannot pick up the publishable key
//! by accident, and the client secret never travels as an `api-key`.
//!
//! ```no_run
//! # use delopay::{CheckoutSession, PublishableKey};
//! # async fn run() -> delopay::Result<()> {
//! let session = CheckoutSession::new(
//!     "mer_123",
//!     "pay_456",
//!     PublishableKey::new("pk_snd_abc")?,
//!     "pay_456_secret_xyz",
//! );
//! let catalog = session.epayouts_methods("de").await?;
//! let payment = session.retrieve_payment().await?;
//! # let _ = (catalog, payment);
//! # Ok(())
//! # }
//! ```

use std::sync::Arc;

use serde::Serialize;

use crate::core::credentials::{ClientSecret, PublishableKey};
use crate::core::encoding::{encode_segment, to_json_vec};
use crate::core::error::{DelopayError, Result};
use crate::core::models::checkout::{
    CheckoutDataResponse, EpayoutsMethodsResponse, RecordCheckoutEventResponse,
    SubscriptionCheckoutResponse, SubscriptionMethodOptionsResponse,
    SubscriptionReturnStatusResponse, VaultCollectSessionResponse, VaultPaymentMethodResponse,
};
use crate::core::models::payment::{
    PaymentAbandonAttemptResponse, PaymentPostSessionTokensResponse, PaymentReopenAttemptResponse,
    PaymentResponse, ReplayIngestResponse,
};
use crate::core::models::payment_method::PaymentMethodListResponse;
use crate::core::models::subscription::SubscriptionResponse;
use crate::http::client::{ClientParts, DelopayBuilder, Inner};
use crate::http::transport::HttpMethod;
use crate::resources::ValidateRequest;
use crate::resources::payments::{PaymentConfirmRequest, PaymentUpdateRequest};

/// Options shared by both buyer-side clients: which environment to talk to,
/// and the usual transport knobs.
#[derive(Debug, Clone, Default)]
pub struct CheckoutSessionOptions {
    /// Override the API base URL, e.g. `/api` behind a same-origin proxy.
    pub base_url: Option<String>,
    /// Use the sandbox environment. Ignored when `base_url` is set.
    pub sandbox: bool,
    /// Per-request timeout.
    pub timeout: Option<std::time::Duration>,
    /// Maximum automatic retries for retriable requests.
    pub max_retries: Option<u32>,
}

impl CheckoutSessionOptions {
    /// Production defaults.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Talk to the sandbox environment.
    #[must_use]
    pub fn sandbox(mut self, sandbox: bool) -> Self {
        self.sandbox = sandbox;
        self
    }

    /// Send requests to this base URL instead of the environment default.
    #[must_use]
    pub fn base_url(mut self, base_url: impl Into<String>) -> Self {
        self.base_url = Some(base_url.into());
        self
    }

    /// Per-request timeout.
    #[must_use]
    pub fn timeout(mut self, timeout: std::time::Duration) -> Self {
        self.timeout = Some(timeout);
        self
    }

    /// Maximum automatic retries.
    #[must_use]
    pub fn max_retries(mut self, max_retries: u32) -> Self {
        self.max_retries = Some(max_retries);
        self
    }

    /// The transport and shared configuration these options describe.
    ///
    /// Built once and reused by both `Inner`s of a [`CheckoutSession`], so
    /// the two credentials share one connection pool.
    fn into_parts(self) -> ClientParts {
        // The builder wants a secret key; this one is deliberately empty and
        // is never installed on an `Inner` — the buyer-side clients supply
        // their own credential per half. Everything else (proxy resolution,
        // timeouts, base URL defaulting) is the builder's, not re-implemented.
        let mut builder = DelopayBuilder::for_checkout_session();
        if let Some(base_url) = self.base_url {
            builder = builder.base_url(base_url);
        }
        builder = builder.sandbox(self.sandbox);
        if let Some(timeout) = self.timeout {
            builder = builder.timeout(timeout);
        }
        if let Some(max_retries) = self.max_retries {
            builder = builder.max_retries(max_retries);
        }
        builder.into_parts()
    }
}

/// The client-secret half of a checkout: the `/payment-link/*` side channel.
///
/// Holds no API key at all — every call authenticates with
/// `Authorization: Bearer <client_secret>`.
#[derive(Debug, Clone)]
pub struct PaymentLinkSession {
    inner: Arc<Inner>,
    link_base: String,
    /// `{merchant_id}/{payment_id}`, each percent-encoded: the tail of the
    /// checkout-data and subscription-checkout paths.
    ids: String,
    client_secret: ClientSecret,
}

impl PaymentLinkSession {
    /// A session for one payment, authenticated by its client secret.
    pub fn new(
        merchant_id: &str,
        payment_id: &str,
        client_secret: impl Into<ClientSecret>,
    ) -> Self {
        Self::with_options(
            merchant_id,
            payment_id,
            client_secret,
            CheckoutSessionOptions::new(),
        )
    }

    /// [`new`](Self::new) with non-default transport options.
    pub fn with_options(
        merchant_id: &str,
        payment_id: &str,
        client_secret: impl Into<ClientSecret>,
        options: CheckoutSessionOptions,
    ) -> Self {
        Self::from_parts(
            &options.into_parts(),
            merchant_id,
            payment_id,
            client_secret.into(),
        )
    }

    fn from_parts(
        parts: &ClientParts,
        merchant_id: &str,
        payment_id: &str,
        client_secret: ClientSecret,
    ) -> Self {
        let ids = format!(
            "{}/{}",
            encode_segment(merchant_id),
            encode_segment(payment_id)
        );
        Self {
            // Empty key: this half must never present an `api-key`.
            inner: Arc::new(parts.inner_with_key(String::new())),
            link_base: format!("/payment-link/{ids}"),
            ids,
            client_secret,
        }
    }

    /// The `Authorization: Bearer <client_secret>` header these routes take.
    fn bearer(&self) -> String {
        format!("Bearer {}", self.client_secret.as_str())
    }

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

    /// [`send`](Self::send) with an optional `Accept-Language` header.
    async fn send_with_locale<T: serde::de::DeserializeOwned>(
        &self,
        method: HttpMethod,
        path: &str,
        body: Option<&[u8]>,
        query: &[(&str, String)],
        locale: Option<&str>,
    ) -> Result<T> {
        let authorization = self.bearer();
        let mut headers = vec![("authorization", authorization.as_str())];
        if let Some(locale) = locale {
            headers.push(("accept-language", locale));
        }
        self.inner
            .request_with_headers(method, path, body, query, None, &headers)
            .await
    }

    /// The hosted checkout's bootstrap payload for a one-time payment: the
    /// payable checkout, a status view once the payment settled, or the
    /// add-on step.
    ///
    /// Sent with **no credential at all**: a payment link bootstraps before
    /// any credential exists, so neither the client secret nor an API key
    /// travels on this call.
    ///
    /// `GET /payment-link/data/{merchant_id}/{payment_id}`
    pub async fn checkout_data(&self, params: &CheckoutDataParams) -> Result<CheckoutDataResponse> {
        let path = format!("/payment-link/data/{}", self.ids);
        let mut headers = Vec::new();
        if let Some(locale) = params.locale.as_deref() {
            headers.push(("accept-language", locale));
        }
        self.inner
            .request_with_headers(
                HttpMethod::Get,
                &path,
                None,
                &params.to_query(),
                None,
                &headers,
            )
            .await
    }

    /// The bootstrap payload for a subscription checkout. Build the session
    /// with the `sub_…` id in the payment-id slot and the subscription's
    /// client secret.
    ///
    /// `GET /subscriptions/data/{merchant_id}/{subscription_id}`
    pub async fn subscription_data(
        &self,
        params: &SubscriptionDataParams,
    ) -> Result<SubscriptionCheckoutResponse> {
        let path = format!("/subscriptions/data/{}", self.ids);
        let mut query = Vec::new();
        if let Some(theme) = params.theme.as_deref() {
            query.push(("theme", theme.to_string()));
        }
        self.send_with_locale(
            HttpMethod::Get,
            &path,
            None,
            &query,
            params.locale.as_deref(),
        )
        .await
    }

    /// The methods the buyer may pick for a subscription that waits for the
    /// choice (`method_choice_pending`), judged for the buyer.
    ///
    /// Call it from the buyer's browser: the sell-to country is read from the
    /// request's own connection. A cancelled subscription answers 400, and one
    /// that already bills on an account answers 409 (`DE_20`).
    ///
    /// `GET /subscriptions/method-options/{merchant_id}/{subscription_id}`
    pub async fn subscription_method_options(&self) -> Result<SubscriptionMethodOptionsResponse> {
        let path = format!("/subscriptions/method-options/{}", self.ids);
        self.send(HttpMethod::Get, &path, None, &[]).await
    }

    /// Bind a waiting subscription to the method the buyer picked and open
    /// its first cycle on that method's billing account.
    ///
    /// Picking the same method again answers the bound subscription. A
    /// subscription bound to another method already, or whose billing account
    /// changed meanwhile, answers 409 (`DE_20`); a method not offered to this
    /// buyer, or a cancelled subscription, answers 400.
    ///
    /// `POST /subscriptions/select-method/{merchant_id}/{subscription_id}`
    pub async fn select_subscription_method(
        &self,
        method: SubscriptionCheckoutMethod,
    ) -> Result<SubscriptionResponse> {
        let body = to_json_vec(&SelectSubscriptionMethodBody { method })?;
        let path = format!("/subscriptions/select-method/{}", self.ids);
        self.send(HttpMethod::Post, &path, Some(&body), &[]).await
    }

    /// The e-Payouts rail catalog for the buyer's country, plus every country
    /// the catalog can mint a method for.
    ///
    /// `country` is a lowercase ISO 3166-1 alpha-2 code.
    ///
    /// `GET /payment-link/{merchant_id}/{payment_id}/epayouts/methods`
    pub async fn epayouts_methods(&self, country: &str) -> Result<EpayoutsMethodsResponse> {
        let path = format!("{}/epayouts/methods", self.link_base);
        self.send(HttpMethod::Get, &path, None, &[("cc", country.to_string())])
            .await
    }

    /// Record a buyer-side checkout event on the payment's status timeline.
    ///
    /// Telemetry, so this **cannot fail the checkout**: a transport or server
    /// error resolves to `None` rather than an error, because a dropped
    /// analytics event must never become an error the buyer sees. `None` also
    /// covers a deduplicated event — the two are not distinguished, on
    /// purpose, since neither is actionable.
    ///
    /// `POST /payment-link/{merchant_id}/{payment_id}/checkout-events`
    pub async fn record_event(
        &self,
        event: &str,
        method: &str,
    ) -> Option<RecordCheckoutEventResponse> {
        let body = to_json_vec(&RecordCheckoutEventRequest { event, method }).ok()?;
        let path = format!("{}/checkout-events", self.link_base);
        self.send(HttpMethod::Post, &path, Some(&body), &[])
            .await
            .ok()
    }

    /// A short-lived VGS Collect session for browser-side card capture.
    ///
    /// A 404 — or a 400 carrying the "shop has no vault" code — means the
    /// shop has no vault configured. Any **other** error must not be read
    /// that way: falling back to an unprotected card pane because the vault
    /// refused is exactly what this endpoint's error contract exists to stop.
    ///
    /// `GET /payment-link/{merchant_id}/{payment_id}/vault/collect-session`
    pub async fn vault_collect_session(&self) -> Result<VaultCollectSessionResponse> {
        let path = format!("{}/vault/collect-session", self.link_base);
        self.send(HttpMethod::Get, &path, None, &[]).await
    }

    /// Register an aliased card as a payment method and mint the one-shot
    /// `payment_token` the confirm call spends.
    ///
    /// `POST /payment-link/{merchant_id}/{payment_id}/vault/payment-method`
    pub async fn register_vault_payment_method(
        &self,
        params: &VaultPaymentMethodRequest,
    ) -> Result<VaultPaymentMethodResponse> {
        let body = to_json_vec(params)?;
        let path = format!("{}/vault/payment-method", self.link_base);
        self.send(HttpMethod::Post, &path, Some(&body), &[]).await
    }
}

/// Buyer-side client for a single hosted-checkout payment, holding both
/// browser-safe credentials — the merchant's [`PublishableKey`] and the
/// payment's [`ClientSecret`].
///
/// Adds the publishable-key routes — read, update and confirm the payment,
/// list its payment methods — on top of every [`PaymentLinkSession`] call.
///
/// A [`crate::SecretKey`] cannot reach a checkout page through this type: the
/// constructors do not accept one, so the mistake is a compile error rather
/// than an incident.
///
/// Each route carries **exactly one** credential. The `/payment-link/*` half
/// runs on a client with no API key at all — not one whose key is merely
/// unused — so those requests cannot pick up the publishable key by
/// accident, and the client secret never travels as an `api-key`. Both
/// halves share one connection pool.
///
/// ```no_run
/// # use delopay::{CheckoutSession, PublishableKey};
/// # async fn run() -> delopay::Result<()> {
/// let session = CheckoutSession::new(
///     "mer_123",
///     "pay_456",
///     PublishableKey::new("pk_snd_abc")?,
///     "pay_456_secret_xyz",
/// );
/// let catalog = session.epayouts_methods("de").await?;
/// let payment = session.retrieve_payment().await?;
/// # let _ = (catalog, payment);
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone)]
pub struct CheckoutSession {
    link: PaymentLinkSession,
    /// Authenticates with the publishable key in the `api-key` header.
    pk_inner: Arc<Inner>,
    payment_path: String,
    client_secret: ClientSecret,
}

impl CheckoutSession {
    /// A session for one payment, holding the merchant's publishable key and
    /// the payment's client secret.
    ///
    /// Both come from the checkout payload (`pub_key` and `client_secret`).
    pub fn new(
        merchant_id: &str,
        payment_id: &str,
        publishable_key: PublishableKey,
        client_secret: impl Into<ClientSecret>,
    ) -> Self {
        Self::with_options(
            merchant_id,
            payment_id,
            publishable_key,
            client_secret,
            CheckoutSessionOptions::new(),
        )
    }

    /// [`new`](Self::new) with non-default transport options.
    pub fn with_options(
        merchant_id: &str,
        payment_id: &str,
        publishable_key: PublishableKey,
        client_secret: impl Into<ClientSecret>,
        options: CheckoutSessionOptions,
    ) -> Self {
        let parts = options.into_parts();
        let client_secret = client_secret.into();
        Self {
            link: PaymentLinkSession::from_parts(
                &parts,
                merchant_id,
                payment_id,
                client_secret.clone(),
            ),
            pk_inner: Arc::new(parts.inner_with_key(publishable_key.into_string())),
            payment_path: format!("/payments/{}", encode_segment(payment_id)),
            client_secret,
        }
    }

    /// The client-secret half, for the `/payment-link/*` calls. Every one of
    /// them is also available directly on this type.
    #[must_use]
    pub fn payment_link(&self) -> &PaymentLinkSession {
        &self.link
    }

    /// The payment's current state — status polling for redirect and popup
    /// rails.
    ///
    /// `GET /payments/{payment_id}`
    pub async fn retrieve_payment(&self) -> Result<PaymentResponse> {
        self.pk_inner
            .request(
                HttpMethod::Get,
                &self.payment_path,
                None,
                &[("client_secret", self.client_secret.as_str().to_string())],
                None,
            )
            .await
    }

    /// Update the payment before confirmation — persisting custom-field
    /// answers as `metadata`, for instance, on rails that never reach
    /// `/confirm`.
    ///
    /// The client secret is attached to the body automatically.
    ///
    /// `POST /payments/{payment_id}`
    pub async fn update_payment(&self, params: &PaymentUpdateRequest) -> Result<PaymentResponse> {
        let body = self.body_with_client_secret(params)?;
        self.pk_inner
            .request(HttpMethod::Post, &self.payment_path, Some(&body), &[], None)
            .await
    }

    /// Confirm the payment.
    ///
    /// The client secret is attached to the body automatically. Pass an
    /// idempotency key through [`confirm_payment_idempotent`] to make a retry
    /// safe — a bare confirm is deliberately **not** retried on a network
    /// error, since the server may already have charged the card.
    ///
    /// `POST /payments/{payment_id}/confirm`
    ///
    /// [`confirm_payment_idempotent`]: Self::confirm_payment_idempotent
    pub async fn confirm_payment(&self, params: &PaymentConfirmRequest) -> Result<PaymentResponse> {
        self.confirm_with_key(params, None).await
    }

    /// [`confirm_payment`](Self::confirm_payment) carrying an
    /// `Idempotency-Key`, so a retry cannot double-charge.
    pub async fn confirm_payment_idempotent(
        &self,
        params: &PaymentConfirmRequest,
        idempotency_key: &str,
    ) -> Result<PaymentResponse> {
        self.confirm_with_key(params, Some(idempotency_key)).await
    }

    async fn confirm_with_key(
        &self,
        params: &PaymentConfirmRequest,
        idempotency_key: Option<&str>,
    ) -> Result<PaymentResponse> {
        let body = self.body_with_client_secret(params)?;
        let path = format!("{}/confirm", self.payment_path);
        self.pk_inner
            .request(HttpMethod::Post, &path, Some(&body), &[], idempotency_key)
            .await
    }

    /// Abandon the attempt the buyer left open on a connector's hosted page —
    /// the payment sits in `requires_customer_action` — and open a fresh
    /// attempt awaiting a payment method, so the same payment can be confirmed
    /// again with another method or connector.
    ///
    /// Nothing has been authorised on the abandoned attempt: it is voided
    /// locally and kept in the attempt history. Idempotent — a payment already
    /// in `requires_payment_method` comes back unchanged, with no
    /// [`abandoned_attempt_id`](PaymentAbandonAttemptResponse::abandoned_attempt_id).
    ///
    /// This is what lets a checkout offer "choose another payment method" on
    /// the same payment rather than opening a new one.
    ///
    /// `POST /payments/{payment_id}/abandon-attempt`
    pub async fn abandon_attempt(&self) -> Result<PaymentAbandonAttemptResponse> {
        let body = self.body_with_client_secret(&EmptyCheckoutBody {})?;
        let path = format!("{}/abandon-attempt", self.payment_path);
        self.pk_inner
            .request(HttpMethod::Post, &path, Some(&body), &[], None)
            .await
    }

    /// Reopen a provider session the buyer switched away from, when they pick
    /// the same method again, instead of opening a second session at the
    /// provider.
    ///
    /// Pass an `attempt_id` from the checkout's `reopenable_attempts`. The
    /// attempt becomes the payment's active one again, and
    /// [`redirect_url`](PaymentReopenAttemptResponse::redirect_url) sends the
    /// buyer back to it. Refused with `IR_16` when the payment no longer
    /// awaits a method, a payment is under way on the checkout, or the session
    /// can no longer be reopened; open a new session as usual then.
    ///
    /// The client secret is attached to the body automatically.
    ///
    /// `POST /payments/{payment_id}/reopen-attempt`
    pub async fn reopen_attempt(&self, attempt_id: &str) -> Result<PaymentReopenAttemptResponse> {
        let body = self.body_with_client_secret(&ReopenAttemptBody { attempt_id })?;
        let path = format!("{}/reopen-attempt", self.payment_path);
        self.pk_inner
            .request(HttpMethod::Post, &path, Some(&body), &[], None)
            .await
    }

    /// Mint the processor-side session a browser SDK completes: the PayPal
    /// order its buttons or Card Fields attach the buyer's choice to.
    ///
    /// For Card Fields pass `payment_method: "card"` and the
    /// `merchant_connector_id` the checkout was rendered with; the order id
    /// comes back at `next_action.next_action_data.order_id`.
    ///
    /// The client secret is attached to the body automatically.
    ///
    /// `POST /payments/{payment_id}/post-session-tokens`
    pub async fn post_session_tokens(
        &self,
        params: &PostSessionTokensRequest,
    ) -> Result<PaymentPostSessionTokensResponse> {
        self.post_session_tokens_with_key(params, None).await
    }

    /// [`post_session_tokens`](Self::post_session_tokens) carrying an
    /// `Idempotency-Key`, so a retry cannot mint a second processor order.
    ///
    /// The route can create the order and then lose its response — a page that
    /// retries blind ends up with two PayPal orders for one payment, and the
    /// buyer attaches their choice to whichever the page still holds. Give each
    /// session creation its own stable key and re-send **that** key on a retry.
    pub async fn post_session_tokens_idempotent(
        &self,
        params: &PostSessionTokensRequest,
        idempotency_key: &str,
    ) -> Result<PaymentPostSessionTokensResponse> {
        self.post_session_tokens_with_key(params, Some(idempotency_key))
            .await
    }

    async fn post_session_tokens_with_key(
        &self,
        params: &PostSessionTokensRequest,
        idempotency_key: Option<&str>,
    ) -> Result<PaymentPostSessionTokensResponse> {
        let body = self.body_with_client_secret(params)?;
        let path = format!("{}/post-session-tokens", self.payment_path);
        self.pk_inner
            .request(HttpMethod::Post, &path, Some(&body), &[], idempotency_key)
            .await
    }

    /// Store one slice of the buyer's checkout recording.
    ///
    /// Slices are numbered by the recorder and stored under that number:
    /// re-sending a number already stored is reported as a
    /// [`duplicate`](ReplayIngestResponse::duplicate) and writes nothing, so a
    /// retry after a lost response is safe. Once
    /// [`full`](ReplayIngestResponse::full) comes back `true` the recording has
    /// reached its budget and further slices are refused — stop sending.
    ///
    /// The client secret is attached to the body automatically.
    ///
    /// `POST /payments/{payment_id}/replay/slice`
    pub async fn store_replay_slice(
        &self,
        params: &ReplayIngestRequest,
    ) -> Result<ReplayIngestResponse> {
        let body = self.body_with_client_secret(params)?;
        let path = format!("{}/replay/slice", self.payment_path);
        self.pk_inner
            .request(HttpMethod::Post, &path, Some(&body), &[], None)
            .await
    }

    /// The payment methods available for this payment.
    ///
    /// `country` is the highest-precedence geo hint, ahead of the billing
    /// address and IP geolocation.
    ///
    /// `GET /payment-methods`
    pub async fn list_payment_methods(
        &self,
        country: Option<&str>,
    ) -> Result<PaymentMethodListResponse> {
        let mut query = vec![("client_secret", self.client_secret.as_str().to_string())];
        if let Some(country) = country {
            query.push(("country", country.to_string()));
        }
        self.pk_inner
            .request(HttpMethod::Get, "/payment-methods", None, &query, None)
            .await
    }

    /// Validate `params`, serialize it, and merge the session's client secret
    /// into the resulting JSON object.
    ///
    /// The [`ValidateRequest`] bound is the point of putting the check here
    /// rather than at each call site: it is the same guard the secret-key
    /// paths run before serializing, and having it in one place means a
    /// future checkout route cannot forget it. Without it, an `extra` key
    /// colliding with a named field ships a JSON object with a literal
    /// duplicate key, which the server may resolve either way.
    ///
    /// The merge is done on the serialized value rather than by adding a
    /// field to the request structs: those are shared with the secret-key
    /// surface, where a client secret has no business being.
    ///
    /// The session's secret **overwrites** a `client_secret` the caller set
    /// on the request. A session is bound to one payment, so a second secret
    /// in the body is either the same value or a mistake, and sending the
    /// caller's would authenticate against a payment this session is not for.
    fn body_with_client_secret<T: Serialize + ValidateRequest>(
        &self,
        params: &T,
    ) -> Result<Vec<u8>> {
        params.validate()?;
        let mut value = serde_json::to_value(params)
            .map_err(|e| crate::core::error::DelopayError::Decode(e.to_string()))?;
        match value.as_object_mut() {
            Some(map) => {
                map.insert(
                    "client_secret".to_string(),
                    serde_json::Value::String(self.client_secret.as_str().to_string()),
                );
            }
            // Unreachable for the request structs this is called with, which
            // are all structs; erroring beats silently sending a body the
            // server would reject as unauthenticated.
            None => {
                return Err(crate::core::error::DelopayError::InvalidRequest(
                    "checkout request body must serialize to a JSON object".to_string(),
                ));
            }
        }
        to_json_vec(&value)
    }

    // --- `/payment-link/*` calls, delegated to the client-secret half ---

    /// See [`PaymentLinkSession::epayouts_methods`].
    pub async fn epayouts_methods(&self, country: &str) -> Result<EpayoutsMethodsResponse> {
        self.link.epayouts_methods(country).await
    }

    /// See [`PaymentLinkSession::record_event`].
    pub async fn record_event(
        &self,
        event: &str,
        method: &str,
    ) -> Option<RecordCheckoutEventResponse> {
        self.link.record_event(event, method).await
    }

    /// See [`PaymentLinkSession::vault_collect_session`].
    pub async fn vault_collect_session(&self) -> Result<VaultCollectSessionResponse> {
        self.link.vault_collect_session().await
    }

    /// See [`PaymentLinkSession::register_vault_payment_method`].
    pub async fn register_vault_payment_method(
        &self,
        params: &VaultPaymentMethodRequest,
    ) -> Result<VaultPaymentMethodResponse> {
        self.link.register_vault_payment_method(params).await
    }

    /// See [`PaymentLinkSession::checkout_data`].
    pub async fn checkout_data(&self, params: &CheckoutDataParams) -> Result<CheckoutDataResponse> {
        self.link.checkout_data(params).await
    }

    /// See [`PaymentLinkSession::subscription_data`].
    pub async fn subscription_data(
        &self,
        params: &SubscriptionDataParams,
    ) -> Result<SubscriptionCheckoutResponse> {
        self.link.subscription_data(params).await
    }

    /// See [`PaymentLinkSession::subscription_method_options`].
    pub async fn subscription_method_options(&self) -> Result<SubscriptionMethodOptionsResponse> {
        self.link.subscription_method_options().await
    }

    /// See [`PaymentLinkSession::select_subscription_method`].
    pub async fn select_subscription_method(
        &self,
        method: SubscriptionCheckoutMethod,
    ) -> Result<SubscriptionResponse> {
        self.link.select_subscription_method(method).await
    }
}

/// Reads the status a buyer coming back from the processor's checkout may
/// see, authenticated with the return token (`rt`) the return URL carried.
///
/// A separate type because that token is the only credential such a page
/// holds: it reads only this, for a day, and is never the client secret. No
/// API key travels on this call either.
#[derive(Debug, Clone)]
pub struct SubscriptionReturnSession {
    inner: Arc<Inner>,
    path: String,
}

impl SubscriptionReturnSession {
    /// A reader for one subscription's return status.
    pub fn new(merchant_id: &str, subscription_id: &str) -> Self {
        Self::with_options(merchant_id, subscription_id, CheckoutSessionOptions::new())
    }

    /// [`new`](Self::new) with non-default transport options.
    pub fn with_options(
        merchant_id: &str,
        subscription_id: &str,
        options: CheckoutSessionOptions,
    ) -> Self {
        Self::from_parts(&options.into_parts(), merchant_id, subscription_id)
    }

    fn from_parts(parts: &ClientParts, merchant_id: &str, subscription_id: &str) -> Self {
        Self {
            // Empty key: this call must never present an `api-key`.
            inner: Arc::new(parts.inner_with_key(String::new())),
            path: format!(
                "/subscriptions/return-status/{}/{}",
                encode_segment(merchant_id),
                encode_segment(subscription_id)
            ),
        }
    }

    /// The subscription's status, and whether the processor has reported it
    /// yet (`awaiting_processor`).
    ///
    /// `return_token` is the `rt` value of the return URL, sent as
    /// `Authorization: Bearer <rt>`. An empty token is refused before the
    /// request is sent.
    ///
    /// `GET /subscriptions/return-status/{merchant_id}/{subscription_id}`
    pub async fn status(&self, return_token: &str) -> Result<SubscriptionReturnStatusResponse> {
        if return_token.is_empty() {
            return Err(crate::core::error::DelopayError::InvalidRequest(
                "the return-status call needs the return token (rt) from the return URL"
                    .to_string(),
            ));
        }
        let authorization = format!("Bearer {return_token}");
        self.inner
            .request_with_headers(
                HttpMethod::Get,
                &self.path,
                None,
                &[],
                None,
                &[("authorization", authorization.as_str())],
            )
            .await
    }
}

/// Query and locale of [`PaymentLinkSession::checkout_data`].
#[derive(Debug, Clone, Default)]
pub struct CheckoutDataParams {
    /// Sent as `Accept-Language`, the only channel the checkout's locale
    /// resolution reads.
    pub locale: Option<String>,
    /// A named checkout variant.
    pub theme: Option<String>,
    /// Override of the buyer country the API otherwise resolves from the
    /// client IP, as an ISO 3166-1 alpha-2 code. It decides which payment
    /// methods the layout shows. Sent trimmed and uppercased; omitted when
    /// blank.
    pub country: Option<String>,
    /// A direct link to the card form (`card_only=true`): when the card form
    /// being prepared is the one the link names, its payment is created for
    /// cards alone.
    pub card_only: bool,
    /// The card form's connector. Sent only with `card_only`, trimmed;
    /// omitted when blank.
    pub card_provider: Option<String>,
    /// The card form's connector account. Sent only with `card_only`,
    /// trimmed; omitted when blank.
    pub card_account: Option<String>,
    /// Open one of the shop's checkout entries: the layout holds only that
    /// entry's methods, drawn in its named look. Trimmed; omitted when blank.
    pub entry: Option<String>,
}

impl CheckoutDataParams {
    /// No query and no locale.
    pub fn new() -> Self {
        Self::default()
    }

    /// Send this locale as `Accept-Language`.
    #[must_use]
    pub fn locale(mut self, locale: impl Into<String>) -> Self {
        self.locale = Some(locale.into());
        self
    }

    /// Render a named checkout variant.
    #[must_use]
    pub fn theme(mut self, theme: impl Into<String>) -> Self {
        self.theme = Some(theme.into());
        self
    }

    /// Override the buyer country.
    #[must_use]
    pub fn country(mut self, country: impl Into<String>) -> Self {
        self.country = Some(country.into());
        self
    }

    /// Open the card form directly.
    #[must_use]
    pub fn card_only(mut self, card_only: bool) -> Self {
        self.card_only = card_only;
        self
    }

    /// Name the card form's connector (with `card_only`).
    #[must_use]
    pub fn card_provider(mut self, card_provider: impl Into<String>) -> Self {
        self.card_provider = Some(card_provider.into());
        self
    }

    /// Name the card form's connector account (with `card_only`).
    #[must_use]
    pub fn card_account(mut self, card_account: impl Into<String>) -> Self {
        self.card_account = Some(card_account.into());
        self
    }

    /// Open one of the shop's checkout entries.
    #[must_use]
    pub fn entry(mut self, entry: impl Into<String>) -> Self {
        self.entry = Some(entry.into());
        self
    }

    fn to_query(&self) -> Vec<(&'static str, String)> {
        fn non_blank(value: Option<&str>) -> Option<String> {
            value
                .map(str::trim)
                .filter(|v| !v.is_empty())
                .map(str::to_string)
        }
        let mut query = Vec::new();
        if let Some(theme) = &self.theme {
            query.push(("theme", theme.clone()));
        }
        if let Some(country) = non_blank(self.country.as_deref()) {
            query.push(("country", country.to_uppercase()));
        }
        if self.card_only {
            query.push(("card_only", "true".to_string()));
            if let Some(provider) = non_blank(self.card_provider.as_deref()) {
                query.push(("card_provider", provider));
            }
            if let Some(account) = non_blank(self.card_account.as_deref()) {
                query.push(("card_account", account));
            }
        }
        if let Some(entry) = non_blank(self.entry.as_deref()) {
            query.push(("entry", entry));
        }
        query
    }
}

/// Query and locale of [`PaymentLinkSession::subscription_data`].
#[derive(Debug, Clone, Default)]
pub struct SubscriptionDataParams {
    /// Sent as `Accept-Language`.
    pub locale: Option<String>,
    /// A named checkout variant.
    pub theme: Option<String>,
}

impl SubscriptionDataParams {
    /// No query and no locale.
    pub fn new() -> Self {
        Self::default()
    }

    /// Send this locale as `Accept-Language`.
    #[must_use]
    pub fn locale(mut self, locale: impl Into<String>) -> Self {
        self.locale = Some(locale.into());
        self
    }

    /// Render a named checkout variant.
    #[must_use]
    pub fn theme(mut self, theme: impl Into<String>) -> Self {
        self.theme = Some(theme.into());
        self
    }
}

/// A payment method a buyer can pick in the hosted subscription checkout.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum SubscriptionCheckoutMethod {
    /// A card, billed by Stripe Billing.
    Card,
    /// PayPal.
    Paypal,
    /// The processor's own hosted page (Creem, Whop).
    ProcessorPage,
}

/// Body of [`PaymentLinkSession::select_subscription_method`].
#[derive(Debug, Serialize)]
struct SelectSubscriptionMethodBody {
    method: SubscriptionCheckoutMethod,
}

/// Body of [`CheckoutSession::reopen_attempt`], without the client secret the
/// session attaches.
#[derive(Debug, Serialize)]
struct ReopenAttemptBody<'a> {
    attempt_id: &'a str,
}

impl ValidateRequest for ReopenAttemptBody<'_> {
    fn validate(&self) -> Result<()> {
        Ok(())
    }
}

/// Body of [`PaymentLinkSession::record_event`].
#[derive(Debug, Serialize)]
struct RecordCheckoutEventRequest<'a> {
    event: &'a str,
    method: &'a str,
}

/// Body for [`PaymentLinkSession::register_vault_payment_method`].
///
/// The expiry travels in the clear by necessity: VGS never hands raw values
/// back, so only the card *number* exists as an alias.
#[derive(Debug, Clone, Serialize)]
pub struct VaultPaymentMethodRequest {
    /// The card-number alias from `createAliases` (must be card-shaped).
    pub card_number_alias: String,
    /// Expiry month, two digits.
    pub card_exp_month: String,
    /// Expiry year.
    pub card_exp_year: String,
    /// Name on the card.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub card_holder_name: Option<String>,
    /// Buyer-chosen nickname for the saved card.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub nick_name: Option<String>,
    /// Card network, when the page already knows it.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub card_network: Option<String>,
}

impl VaultPaymentMethodRequest {
    /// The three fields the vault always needs.
    #[must_use]
    pub fn new(
        card_number_alias: impl Into<String>,
        card_exp_month: impl Into<String>,
        card_exp_year: impl Into<String>,
    ) -> Self {
        Self {
            card_number_alias: card_number_alias.into(),
            card_exp_month: card_exp_month.into(),
            card_exp_year: card_exp_year.into(),
            card_holder_name: None,
            nick_name: None,
            card_network: None,
        }
    }

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

    /// Set the buyer-chosen nickname.
    #[must_use]
    pub fn nick_name(mut self, nick_name: impl Into<String>) -> Self {
        self.nick_name = Some(nick_name.into());
        self
    }

    /// Set the card network.
    #[must_use]
    pub fn card_network(mut self, card_network: impl Into<String>) -> Self {
        self.card_network = Some(card_network.into());
        self
    }
}

/// An empty checkout body: the client secret the session merges in is the
/// whole request.
#[derive(Debug, Serialize)]
struct EmptyCheckoutBody {}

impl ValidateRequest for EmptyCheckoutBody {
    fn validate(&self) -> Result<()> {
        Ok(())
    }
}

/// Body of [`CheckoutSession::post_session_tokens`], without the client secret
/// the session attaches.
#[derive(Debug, Clone, Serialize)]
pub struct PostSessionTokensRequest {
    /// Payment method family, e.g. `"card"` or `"wallet"`.
    pub payment_method: String,
    /// Payment method sub-type, e.g. `"paypal"` — or `"credit"` / `"debit"`
    /// for Card Fields.
    pub payment_method_type: String,
    /// The connector account the checkout was rendered with. Required for
    /// Card Fields: the router pins the session to that account.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub merchant_connector_id: Option<String>,
}

impl PostSessionTokensRequest {
    /// Mint a session for one payment method and sub-type.
    pub fn new(payment_method: impl Into<String>, payment_method_type: impl Into<String>) -> Self {
        Self {
            payment_method: payment_method.into(),
            payment_method_type: payment_method_type.into(),
            merchant_connector_id: None,
        }
    }

    /// Pin the session to the connector account the checkout was rendered
    /// with.
    #[must_use]
    pub fn merchant_connector_id(mut self, merchant_connector_id: impl Into<String>) -> Self {
        self.merchant_connector_id = Some(merchant_connector_id.into());
        self
    }
}

impl ValidateRequest for PostSessionTokensRequest {
    fn validate(&self) -> Result<()> {
        Ok(())
    }
}

/// Body of [`CheckoutSession::store_replay_slice`], without the client secret
/// the session attaches.
///
/// A slice carries its events **either** as JSON
/// ([`new`](Self::new)) **or** as one compressed string
/// ([`compressed`](Self::compressed)), never both.
#[derive(Debug, Clone, Serialize)]
pub struct ReplayIngestRequest {
    /// The recording session the slice belongs to, as the recorder minted it.
    pub session_id: String,
    /// The slice's number. Slices are stored under it, and re-sending a stored
    /// number is a no-op rather than a second copy.
    pub sequence: u64,
    /// The recorded events, in the recorder's own shape.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub events: Option<Vec<serde_json::Value>>,
    /// The JSON array of recorded events, gzip-compressed and then
    /// base64-encoded.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub compressed_events: Option<String>,
}

impl ReplayIngestRequest {
    /// One slice of `events`, numbered `sequence`, for recording `session_id`.
    pub fn new(
        session_id: impl Into<String>,
        sequence: u64,
        events: Vec<serde_json::Value>,
    ) -> Self {
        Self {
            session_id: session_id.into(),
            sequence,
            events: Some(events),
            compressed_events: None,
        }
    }

    /// One slice whose events are `compressed_events`: the JSON event array,
    /// gzip-compressed and base64-encoded by the caller.
    pub fn compressed(
        session_id: impl Into<String>,
        sequence: u64,
        compressed_events: impl Into<String>,
    ) -> Self {
        Self {
            session_id: session_id.into(),
            sequence,
            events: None,
            compressed_events: Some(compressed_events.into()),
        }
    }
}

impl ValidateRequest for ReplayIngestRequest {
    fn validate(&self) -> Result<()> {
        if self.events.is_some() == self.compressed_events.is_some() {
            return Err(DelopayError::InvalidRequest(
                "a replay slice carries exactly one of `events` and `compressed_events`".to_owned(),
            ));
        }
        Ok(())
    }
}

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

    const PAYMENT_JSON: &str = r#"{
        "payment_id": "pay_456", "merchant_id": "mer_123", "status": "requires_confirmation",
        "amount": 1999, "currency": "EUR"
    }"#;

    /// A `CheckoutSession` over a scripted mock, plus the mock. Mirrors
    /// `mock::client_with`, but builds the two `Inner`s the session needs
    /// over *one* transport, so header assertions see every call.
    fn session_with(steps: Vec<Step>) -> (CheckoutSession, Arc<MockTransport>) {
        let mock = Arc::new(MockTransport::new(steps));
        let parts = ClientParts::for_test(mock.clone(), "https://api.test");
        let client_secret = ClientSecret::new("pay_456_secret_xyz");
        let session = CheckoutSession {
            link: PaymentLinkSession::from_parts(
                &parts,
                "mer_123",
                "pay_456",
                client_secret.clone(),
            ),
            pk_inner: Arc::new(parts.inner_with_key("pk_snd_abc".to_string())),
            payment_path: "/payments/pay_456".to_string(),
            client_secret,
        };
        (session, mock)
    }

    #[tokio::test]
    async fn link_routes_send_a_bearer_and_no_api_key() {
        let (session, mock) = session_with(vec![Step::ok(
            r#"{"country":"de","currency":"EUR","methods":[],"supported_countries":["de"]}"#,
        )]);
        session.epayouts_methods("de").await.unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(
            seen[0].url,
            "https://api.test/payment-link/mer_123/pay_456/epayouts/methods?cc=de"
        );
        assert_eq!(
            seen[0].header("authorization"),
            Some("Bearer pay_456_secret_xyz")
        );
        // The isolation guarantee: this route must not also present the
        // publishable key. An `Inner` that sent an empty `api-key` header
        // would fail here too.
        assert_eq!(seen[0].header("api-key"), None);
    }

    /// Minting a session token can create a processor order and then lose its
    /// response, so the keyed variant has to reach the wire as an
    /// `Idempotency-Key`. Mutation: drop the key argument inside
    /// `post_session_tokens_with_key` — the header assertion fails, and a
    /// retry would mint a second PayPal order for one payment.
    #[tokio::test]
    async fn keyed_session_tokens_carry_the_idempotency_key() {
        let (session, mock) = session_with(vec![Step::ok(
            r#"{"payment_id":"pay_456","status":"requires_customer_action"}"#,
        )]);
        session
            .post_session_tokens_idempotent(
                &PostSessionTokensRequest::new("card", "credit").merchant_connector_id("mca_1"),
                "session-pay_456-1",
            )
            .await
            .unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(
            seen[0].url,
            "https://api.test/payments/pay_456/post-session-tokens"
        );
        assert_eq!(seen[0].header("idempotency-key"), Some("session-pay_456-1"));
        // The session attaches the client secret; the caller never sends it.
        assert_eq!(seen[0].body_json()["client_secret"], "pay_456_secret_xyz");
        assert_eq!(seen[0].body_json()["merchant_connector_id"], "mca_1");
    }

    /// The unkeyed variant stays unkeyed — a page that has not decided on a
    /// key must not silently inherit one. Mutation: make `post_session_tokens`
    /// mint a key of its own; the assertion fails.
    #[tokio::test]
    async fn unkeyed_session_tokens_send_no_idempotency_key() {
        let (session, mock) = session_with(vec![Step::ok(
            r#"{"payment_id":"pay_456","status":"requires_customer_action"}"#,
        )]);
        session
            .post_session_tokens(&PostSessionTokensRequest::new("wallet", "paypal"))
            .await
            .unwrap();

        assert!(!mock.seen.lock().unwrap()[0].had_idempotency_key());
    }

    #[tokio::test]
    async fn publishable_key_routes_send_the_key_and_no_bearer() {
        let (session, mock) = session_with(vec![Step::ok(PAYMENT_JSON)]);
        session.retrieve_payment().await.unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(
            seen[0].url,
            "https://api.test/payments/pay_456?client_secret=pay_456_secret_xyz"
        );
        assert_eq!(seen[0].header("api-key"), Some("pk_snd_abc"));
        // The client secret rides as a parameter here, never as a bearer —
        // and never as the api-key.
        assert_eq!(seen[0].header("authorization"), None);
    }

    #[tokio::test]
    async fn confirm_merges_the_client_secret_into_the_body() {
        let (session, mock) = session_with(vec![Step::ok(PAYMENT_JSON)]);
        let params = PaymentConfirmRequest {
            payment_method: Some("card".to_string()),
            ..Default::default()
        };
        session.confirm_payment(&params).await.unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(seen[0].url, "https://api.test/payments/pay_456/confirm");
        let body = seen[0].body_json();
        assert_eq!(body["client_secret"], "pay_456_secret_xyz");
        // The caller's own fields survive the merge.
        assert_eq!(body["payment_method"], "card");
        assert!(!seen[0].had_idempotency_key());
    }

    #[tokio::test]
    async fn the_idempotent_confirm_sends_a_key() {
        let (session, mock) = session_with(vec![Step::ok(PAYMENT_JSON)]);
        let params = PaymentConfirmRequest {
            payment_method: Some("card".to_string()),
            ..Default::default()
        };
        session
            .confirm_payment_idempotent(&params, "confirm-pay_456")
            .await
            .unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].header("idempotency-key"), Some("confirm-pay_456"));
    }

    #[tokio::test]
    async fn update_payment_carries_the_client_secret_too() {
        let (session, mock) = session_with(vec![Step::ok(PAYMENT_JSON)]);
        // `metadata` is a named field, so it goes in the field — putting it
        // in `extra` is exactly what the collision guard now rejects, and
        // there is a test below for that.
        let params = PaymentUpdateRequest {
            metadata: Some(serde_json::json!({"gift": "yes"})),
            ..Default::default()
        };
        session.update_payment(&params).await.unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(seen[0].url, "https://api.test/payments/pay_456");
        let body = seen[0].body_json();
        assert_eq!(body["client_secret"], "pay_456_secret_xyz");
        assert_eq!(body["metadata"]["gift"], "yes");
    }

    #[tokio::test]
    async fn the_checkout_paths_run_the_extra_key_collision_guard() {
        // A colliding `extra` key would otherwise serialize a JSON object
        // with a literal duplicate key, which the server may resolve either
        // way. The secret-key paths reject it; these must too.
        let (session, mock) = session_with(vec![]);

        let mut confirm = PaymentConfirmRequest::default();
        confirm
            .extra
            .insert("payment_method".to_string(), serde_json::json!("card"));
        match session.confirm_payment(&confirm).await.unwrap_err() {
            crate::DelopayError::InvalidRequest(msg) => {
                assert!(msg.contains("payment_method"), "{msg}");
            }
            other => panic!("expected InvalidRequest, got {other:?}"),
        }

        let mut update = PaymentUpdateRequest::default();
        update
            .extra
            .insert("amount".to_string(), serde_json::json!(1));
        match session.update_payment(&update).await.unwrap_err() {
            crate::DelopayError::InvalidRequest(msg) => assert!(msg.contains("amount"), "{msg}"),
            other => panic!("expected InvalidRequest, got {other:?}"),
        }

        // Both rejected before the wire, so the empty script is never hit.
        assert_eq!(mock.call_count(), 0);
    }

    #[tokio::test]
    async fn list_payment_methods_sends_the_secret_and_an_optional_country() {
        let (session, mock) = session_with(vec![
            Step::ok(r#"{"payment_methods":[]}"#),
            Step::ok(r#"{"payment_methods":[]}"#),
        ]);
        session.list_payment_methods(None).await.unwrap();
        session.list_payment_methods(Some("de")).await.unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(
            seen[0].url,
            "https://api.test/payment-methods?client_secret=pay_456_secret_xyz"
        );
        assert_eq!(
            seen[1].url,
            "https://api.test/payment-methods?client_secret=pay_456_secret_xyz&country=de"
        );
    }

    #[tokio::test]
    async fn record_event_swallows_a_server_error() {
        let (session, mock) = session_with(vec![Step::status(500, "boom")]);
        // Telemetry must not surface as an error the checkout has to handle.
        assert!(
            session
                .record_event("native_pane_selected", "apple_pay")
                .await
                .is_none()
        );
        // It was genuinely attempted — a version that returned `None` without
        // sending anything would pass a weaker assertion.
        assert_eq!(mock.call_count(), 1);
    }

    #[tokio::test]
    async fn record_event_returns_the_receipt_on_success() {
        let (session, mock) = session_with(vec![Step::ok(r#"{"recorded":true}"#)]);
        let receipt = session
            .record_event("native_pane_tab_opened", "klarna")
            .await
            .unwrap();
        assert!(receipt.recorded);

        let seen = mock.seen.lock().unwrap();
        assert_eq!(
            seen[0].url,
            "https://api.test/payment-link/mer_123/pay_456/checkout-events"
        );
        let body = seen[0].body_json();
        assert_eq!(body["event"], "native_pane_tab_opened");
        assert_eq!(body["method"], "klarna");
    }

    #[tokio::test]
    async fn the_vault_handshake_posts_only_the_set_fields() {
        let (session, mock) = session_with(vec![
            Step::ok(
                r#"{"vault_id":"tnt_1","environment":"sandbox","access_token":"tok",
                    "expires_in":900}"#,
            ),
            Step::ok(r#"{"last4":"4242","payment_token":"pt_1"}"#),
        ]);
        session.vault_collect_session().await.unwrap();
        session
            .register_vault_payment_method(&VaultPaymentMethodRequest::new("alias_1", "12", "2030"))
            .await
            .unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(
            seen[0].url,
            "https://api.test/payment-link/mer_123/pay_456/vault/collect-session"
        );
        assert_eq!(
            seen[1].url,
            "https://api.test/payment-link/mer_123/pay_456/vault/payment-method"
        );
        let body = seen[1].body_json();
        assert_eq!(body["card_number_alias"], "alias_1");
        assert!(body.get("nick_name").is_none());
    }

    const CHECKOUT_DATA_JSON: &str = r#"{
        "type": "checkout", "payment_id": "pay_456", "amount": "19.99", "currency": "EUR",
        "status": "requires_payment_method", "merchant_name": "Shop", "merchant_logo": "",
        "theme": "light", "sdk_layout": "tabs", "pub_key": "pk_snd_abc",
        "client_secret": "pay_456_secret_xyz", "session_expiry": "2026-11-03T10:00:00Z",
        "attempt_count": 0, "surprise_field": 7
    }"#;

    /// Mutations: attaching the bearer (or the publishable key) to this call,
    /// dropping the trim/uppercase on `country`, or sending `card_provider`
    /// with a blank value — each fails an assertion here.
    #[tokio::test]
    async fn checkout_data_sends_no_credential_and_normalises_the_query() {
        let (session, mock) = session_with(vec![Step::ok(CHECKOUT_DATA_JSON)]);
        let params = CheckoutDataParams::new()
            .locale("de-DE")
            .theme("dark")
            .country(" de ")
            .card_only(true)
            .card_provider(" stripe ")
            .card_account("  ")
            .entry(" e1 ");
        let data = session.checkout_data(&params).await.unwrap();
        assert_eq!(data.kind, "checkout");
        assert_eq!(data.payment_id, "pay_456");
        assert_eq!(data.amount, "19.99");
        assert_eq!(data.client_secret.as_deref(), Some("pay_456_secret_xyz"));
        assert_eq!(data.extra["surprise_field"], 7);
        // The payload carries the client secret: `Debug` must not.
        assert!(!format!("{data:?}").contains("pay_456_secret_xyz"));

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "GET");
        assert_eq!(
            seen[0].url,
            "https://api.test/payment-link/data/mer_123/pay_456\
             ?theme=dark&country=DE&card_only=true&card_provider=stripe&entry=e1"
        );
        assert_eq!(seen[0].header("accept-language"), Some("de-DE"));
        assert_eq!(seen[0].header("authorization"), None);
        assert_eq!(seen[0].header("api-key"), None);
    }

    /// The card form's connector and account mean nothing without
    /// `card_only`, so they stay off the wire. Mutation: push them outside
    /// the `card_only` branch — the URL gains a query and this fails.
    #[tokio::test]
    async fn checkout_data_omits_the_card_form_names_without_card_only() {
        let (session, mock) = session_with(vec![Step::ok(CHECKOUT_DATA_JSON)]);
        let params = CheckoutDataParams::new()
            .card_provider("stripe")
            .card_account("mca_1");
        session.checkout_data(&params).await.unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(
            seen[0].url,
            "https://api.test/payment-link/data/mer_123/pay_456"
        );
        assert_eq!(seen[0].header("accept-language"), None);
    }

    /// The amount is a decimal string in every shape of the payload. A
    /// numeric fixture hid that once. Mutation: type `amount` as `i64` again,
    /// and both decodes fail.
    #[tokio::test]
    async fn checkout_data_decodes_the_status_and_addon_choice_shapes() {
        let (session, _mock) = session_with(vec![
            Step::ok(
                r#"{"type":"status","payment_id":"pay_456","amount":"38.02","currency":"EUR",
                    "merchant_logo":"","merchant_name":"Shop","created":"2026-11-01T00:00:00Z",
                    "status":"succeeded","redirect":false,"theme":"light",
                    "replay_masking_rules":[],"sdk_layout":"tabs","pub_key":null,
                    "client_secret":null,"session_expiry":null,"surprise_field":1}"#,
            ),
            Step::ok(
                r#"{"type":"addon_choice","payment_id":"pay_456","amount":"38.02",
                    "currency":"EUR","client_secret":"pay_456_secret_xyz",
                    "pub_key":"pk_snd_abc","session_expiry":"2026-11-03T10:00:00Z",
                    "product":{"name":"Plan"},"groups":[],"selection":[],
                    "merchant_name":"Shop","merchant_logo":"","theme":"light",
                    "replay_masking_rules":[],"sdk_layout":"tabs"}"#,
            ),
        ]);
        let status = session
            .checkout_data(&CheckoutDataParams::new())
            .await
            .unwrap();
        assert_eq!(status.kind, "status");
        assert_eq!(status.amount, "38.02");
        assert_eq!(status.status.as_deref(), Some("succeeded"));
        assert_eq!(status.client_secret, None);
        assert_eq!(status.extra["redirect"], false);
        assert_eq!(status.extra["surprise_field"], 1);

        let addons = session
            .checkout_data(&CheckoutDataParams::new())
            .await
            .unwrap();
        assert_eq!(addons.kind, "addon_choice");
        assert_eq!(addons.amount, "38.02");
        assert_eq!(addons.status, None);
        assert_eq!(addons.extra["product"]["name"], "Plan");
        assert!(!format!("{addons:?}").contains("pay_456_secret_xyz"));
    }

    #[tokio::test]
    async fn subscription_data_sends_the_bearer_locale_and_theme() {
        let (session, mock) = session_with(vec![Step::ok(
            r#"{"type":"subscription","subscription_id":"sub_1","status":"active",
                "profile_id":"pro_1","pub_key":"pk_snd_abc","client_secret":"sub_1_secret",
                "connector_client_secret":"pi_secret","amount":990,"currency":"EUR",
                "amount_source":"invoice","method_choice_pending":false,
                "merchant_name":"Shop","theme":"light","sdk_layout":"tabs",
                "surprise_field":true}"#,
        )]);
        let params = SubscriptionDataParams::new().locale("fr").theme("dark");
        let data = session.subscription_data(&params).await.unwrap();
        assert_eq!(data.kind, "subscription");
        assert_eq!(data.subscription_id, "sub_1");
        assert!(!data.method_choice_pending);
        assert_eq!(data.extra["surprise_field"], true);
        let rendered = format!("{data:?}");
        assert!(!rendered.contains("sub_1_secret"), "{rendered}");
        assert!(!rendered.contains("pi_secret"), "{rendered}");

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "GET");
        assert_eq!(
            seen[0].url,
            "https://api.test/subscriptions/data/mer_123/pay_456?theme=dark"
        );
        assert_eq!(
            seen[0].header("authorization"),
            Some("Bearer pay_456_secret_xyz")
        );
        assert_eq!(seen[0].header("accept-language"), Some("fr"));
        assert_eq!(seen[0].header("api-key"), None);
    }

    #[tokio::test]
    async fn subscription_method_options_reads_with_the_bearer() {
        let (session, mock) = session_with(vec![Step::ok(
            r#"{"subscription_id":"sub_1","options":[{"method":"card",
                "billing_connector":"stripe_billing"}],"buyer_country":"DE",
                "surprise_field":1}"#,
        )]);
        let out = session.subscription_method_options().await.unwrap();
        assert_eq!(out.options[0].method, "card");
        assert_eq!(out.options[0].billing_connector, "stripe_billing");
        assert_eq!(out.no_method_reason, None);
        assert_eq!(out.buyer_country, "DE");
        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/subscriptions/method-options/mer_123/pay_456"
        );
        assert_eq!(
            seen[0].header("authorization"),
            Some("Bearer pay_456_secret_xyz")
        );
    }

    #[tokio::test]
    async fn select_subscription_method_posts_the_method() {
        let (session, mock) = session_with(vec![Step::ok(
            r#"{"id":"sub_1","status":"pending","surprise_field":"x"}"#,
        )]);
        let sub = session
            .select_subscription_method(SubscriptionCheckoutMethod::ProcessorPage)
            .await
            .unwrap();
        assert_eq!(sub.id, "sub_1");
        assert_eq!(sub.extra["surprise_field"], "x");

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(
            seen[0].url,
            "https://api.test/subscriptions/select-method/mer_123/pay_456"
        );
        assert_eq!(
            seen[0].body_json(),
            serde_json::json!({"method": "processor_page"})
        );
        assert_eq!(
            seen[0].header("authorization"),
            Some("Bearer pay_456_secret_xyz")
        );
        assert!(!seen[0].had_idempotency_key());
    }

    #[tokio::test]
    async fn reopen_attempt_posts_the_attempt_with_the_client_secret() {
        let (session, mock) = session_with(vec![Step::ok(
            r#"{"payment_id":"pay_456","status":"requires_customer_action",
                "attempt_id":"att_1","redirect_url":"https://psp.example/r",
                "surprise_field":2}"#,
        )]);
        let out = session.reopen_attempt("att_1").await.unwrap();
        assert_eq!(out.attempt_id, "att_1");
        assert_eq!(out.redirect_url, "https://psp.example/r");
        assert_eq!(out.extra["surprise_field"], 2);

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(
            seen[0].url,
            "https://api.test/payments/pay_456/reopen-attempt"
        );
        assert_eq!(
            seen[0].body_json(),
            serde_json::json!({"attempt_id": "att_1", "client_secret": "pay_456_secret_xyz"})
        );
        assert_eq!(seen[0].header("api-key"), Some("pk_snd_abc"));
        assert_eq!(seen[0].header("authorization"), None);
        assert!(!seen[0].had_idempotency_key());
    }

    /// The return token is the only credential on this call. Mutations:
    /// sending the token as an `api-key`, or encoding only one id — the
    /// header or URL assertion fails.
    #[tokio::test]
    async fn the_return_status_sends_the_return_token_as_the_bearer() {
        let mock = Arc::new(MockTransport::new(vec![Step::ok(
            r#"{"subscription_id":"sub_1","status":"active","awaiting_processor":true,
                "surprise_field":0}"#,
        )]));
        let parts = ClientParts::for_test(mock.clone(), "https://api.test");
        let reader = SubscriptionReturnSession::from_parts(&parts, "mer/1", "sub_1");
        let out = reader.status("rt_abc").await.unwrap();
        assert!(out.awaiting_processor);
        assert_eq!(out.extra["surprise_field"], 0);

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "GET");
        assert_eq!(
            seen[0].url,
            "https://api.test/subscriptions/return-status/mer%2F1/sub_1"
        );
        assert_eq!(seen[0].header("authorization"), Some("Bearer rt_abc"));
        assert_eq!(seen[0].header("api-key"), None);
    }

    #[tokio::test]
    async fn the_return_status_refuses_an_empty_token_before_sending() {
        let mock = Arc::new(MockTransport::new(vec![]));
        let parts = ClientParts::for_test(mock.clone(), "https://api.test");
        let reader = SubscriptionReturnSession::from_parts(&parts, "mer_1", "sub_1");
        match reader.status("").await.unwrap_err() {
            crate::DelopayError::InvalidRequest(msg) => assert!(msg.contains("return token")),
            other => panic!("expected InvalidRequest, got {other:?}"),
        }
        assert_eq!(mock.call_count(), 0);
    }

    #[tokio::test]
    async fn store_replay_slice_sends_one_event_form() {
        let (session, mock) = session_with(vec![
            Step::ok(r#"{"sequence":0,"duplicate":false,"full":false}"#),
            Step::ok(r#"{"sequence":1,"duplicate":false,"full":true}"#),
        ]);
        session
            .store_replay_slice(&ReplayIngestRequest::new(
                "rs_1",
                0,
                vec![serde_json::json!({"type": 2})],
            ))
            .await
            .unwrap();
        let out = session
            .store_replay_slice(&ReplayIngestRequest::compressed("rs_1", 1, "H4sIAAAA"))
            .await
            .unwrap();
        assert!(out.full);

        let seen = mock.seen.lock().unwrap();
        assert_eq!(
            seen[0].url,
            "https://api.test/payments/pay_456/replay/slice"
        );
        let first = seen[0].body_json();
        assert_eq!(first["events"], serde_json::json!([{"type": 2}]));
        assert!(first.get("compressed_events").is_none());
        let second = seen[1].body_json();
        assert_eq!(second["compressed_events"], "H4sIAAAA");
        assert!(second.get("events").is_none());
        assert_eq!(second["client_secret"], "pay_456_secret_xyz");
    }

    /// Both forms, or neither, is refused before sending. Mutation: return
    /// `Ok(())` from `ReplayIngestRequest::validate` — the call count is 2.
    #[tokio::test]
    async fn a_replay_slice_with_both_or_no_event_forms_is_refused() {
        let (session, mock) = session_with(vec![]);
        let mut both = ReplayIngestRequest::new("rs_1", 0, Vec::new());
        both.compressed_events = Some("H4sIAAAA".to_string());
        assert!(session.store_replay_slice(&both).await.is_err());
        let mut neither = ReplayIngestRequest::compressed("rs_1", 0, "x");
        neither.compressed_events = None;
        assert!(session.store_replay_slice(&neither).await.is_err());
        assert_eq!(mock.call_count(), 0);
    }

    #[tokio::test]
    async fn the_link_base_percent_encodes_both_ids() {
        let mock = Arc::new(MockTransport::new(vec![Step::ok(
            r#"{"country":"de","currency":"EUR","methods":[],"supported_countries":[]}"#,
        )]));
        let parts = ClientParts::for_test(mock.clone(), "https://api.test");
        let link =
            PaymentLinkSession::from_parts(&parts, "mer/1", "pay/2", ClientSecret::new("cs"));
        link.epayouts_methods("de").await.unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(
            seen[0].url,
            "https://api.test/payment-link/mer%2F1/pay%2F2/epayouts/methods?cc=de"
        );
    }
}