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
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
//! The `customers` resource.

use std::sync::Arc;

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

use crate::core::encoding::{encode_segment, to_json_vec};
use crate::core::error::{DelopayError, Result};
use crate::core::models::buyer_portal::{
    BuyerInvoiceLink, BuyerPortalLinkPage, BuyerPortalLinkRestrictions,
};
use crate::core::models::common::ListResponse;
use crate::core::models::customer::{
    CustomerResponse, CustomerShopBulkPlacementResponse, CustomerShopPlacementResponse,
};
use crate::core::models::customer_identity::{
    CustomerIdentityHistoryResponse, CustomerIdentityImportPreviewResponse,
    CustomerIdentityImportResponse,
};
use crate::core::models::mandate::MandateResponse;
use crate::http::client::Inner;
use crate::http::transport::HttpMethod;
use crate::resources::ValidateRequest;

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

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

    /// Name the shop (business profile) for the shop-scoped `*_by_profile`
    /// methods, sent as the `x-profile-id` header. Needed only with a
    /// merchant-wide API key; a key bound to one shop names its shop itself.
    ///
    /// Only the `*_by_profile` methods send it. The merchant-level methods
    /// ([`create`](Self::create), [`retrieve`](Self::retrieve),
    /// [`list`](Self::list) and the rest) never do: the API refuses those for
    /// any call that names a shop.
    #[must_use]
    pub fn with_profile_id(mut self, profile_id: impl Into<String>) -> Self {
        self.profile_id = Some(profile_id.into());
        self
    }

    /// The shop header for the `*_by_profile` methods, if a shop was named.
    fn profile_headers(&self) -> Vec<(&str, &str)> {
        match &self.profile_id {
            Some(id) => vec![("x-profile-id", id.as_str())],
            None => Vec::new(),
        }
    }

    /// Create a customer.
    pub async fn create(&self, params: &CustomerCreateRequest) -> Result<CustomerResponse> {
        params.validate()?;
        let body = to_json_vec(params)?;
        self.inner
            .request(HttpMethod::Post, "/customers", Some(&body), &[], None)
            .await
    }

    /// Retrieve a customer by ID.
    pub async fn retrieve(&self, customer_id: &str) -> Result<CustomerResponse> {
        let path = format!("/customers/{}", encode_segment(customer_id));
        self.inner
            .request(HttpMethod::Get, &path, None, &[], None)
            .await
    }

    /// Update a customer.
    pub async fn update(
        &self,
        customer_id: &str,
        params: &CustomerCreateRequest,
    ) -> Result<CustomerResponse> {
        params.validate()?;
        let path = format!("/customers/{}", encode_segment(customer_id));
        let body = to_json_vec(params)?;
        self.inner
            .request(HttpMethod::Post, &path, Some(&body), &[], None)
            .await
    }

    /// Delete a customer.
    pub async fn delete(&self, customer_id: &str) -> Result<CustomerResponse> {
        let path = format!("/customers/{}", encode_segment(customer_id));
        self.inner
            .request(HttpMethod::Delete, &path, None, &[], None)
            .await
    }

    /// List customers, optionally filtered by ID, a search text, shop
    /// (`profile_id`) or project (`project_id`). The time window
    /// (`start_time`, `end_time`) applies to the with-count lists only.
    pub async fn list(&self, params: Option<&CustomerListParams>) -> Result<Vec<CustomerResponse>> {
        let query = params.map(CustomerListParams::to_query).unwrap_or_default();
        self.inner
            .request(HttpMethod::Get, "/customers/list", None, &query, None)
            .await
    }

    /// List customers with the total count: the envelope is `data` plus
    /// `total_count`. Same filters as [`list`](Self::list), plus the
    /// `start_time` / `end_time` window.
    pub async fn list_with_count(
        &self,
        params: Option<&CustomerListParams>,
    ) -> Result<ListResponse<CustomerResponse>> {
        let query = params.map(CustomerListParams::to_query).unwrap_or_default();
        self.inner
            .request(
                HttpMethod::Get,
                "/customers/list-with-count",
                None,
                &query,
                None,
            )
            .await
    }

    /// List customers scoped to the shop (business profile) the credential
    /// belongs to. Same filters as [`list`](Self::list); a `profile_id` /
    /// `project_id` outside that scope is rejected by the API.
    pub async fn list_by_profile(
        &self,
        params: Option<&CustomerListParams>,
    ) -> Result<Vec<CustomerResponse>> {
        let query = params.map(CustomerListParams::to_query).unwrap_or_default();
        self.inner
            .request_with_headers(
                HttpMethod::Get,
                "/customers/profile/list",
                None,
                &query,
                None,
                &self.profile_headers(),
            )
            .await
    }

    /// Profile-scoped variant of [`list_with_count`](Self::list_with_count).
    pub async fn list_by_profile_with_count(
        &self,
        params: Option<&CustomerListParams>,
    ) -> Result<ListResponse<CustomerResponse>> {
        let query = params.map(CustomerListParams::to_query).unwrap_or_default();
        self.inner
            .request_with_headers(
                HttpMethod::Get,
                "/customers/profile/list-with-count",
                None,
                &query,
                None,
                &self.profile_headers(),
            )
            .await
    }
    /// Retrieve one customer of the shop (business profile) the credential is
    /// bound to (`GET /customers/profile/{customer_id}`).
    ///
    /// The shop-scoped twin of [`retrieve`](Self::retrieve), which addresses the
    /// merchant-wide route: a shop team member can list their own shop's
    /// customers but not open one through that, so every row of the list led to
    /// a 403.
    ///
    /// A customer belonging to a sibling shop answers `CustomerNotFound` — the
    /// same answer as a customer that does not exist, deliberately, so one shop
    /// cannot enumerate another's customer ids by reading the difference.
    pub async fn retrieve_by_profile(&self, customer_id: &str) -> Result<CustomerResponse> {
        let path = format!("/customers/profile/{}", encode_segment(customer_id));
        self.inner
            .request_with_headers(
                HttpMethod::Get,
                &path,
                None,
                &[],
                None,
                &self.profile_headers(),
            )
            .await
    }

    /// Create a customer for the shop (business profile) the credential is
    /// bound to (`POST /customers/profile`).
    ///
    /// For an API key bound to one shop, or a merchant-wide key with the shop
    /// named by [`with_profile_id`](Self::with_profile_id). The customer belongs
    /// to that shop at once, so the same key finds it with
    /// [`retrieve_by_profile`](Self::retrieve_by_profile) and
    /// [`list_by_profile`](Self::list_by_profile) straight away.
    /// [`create`](Self::create) refuses a shop-bound key.
    ///
    /// `customer_id` cannot be chosen here: the API refuses a request that sets
    /// it, because customer ids are unique across the merchant account. Read the
    /// assigned id from the response.
    ///
    /// Not retried after a `5xx` or a lost response, even with a client-wide
    /// idempotency key: the API does not deduplicate this create, so a retry
    /// could make a second customer. A `429` is still retried, since the
    /// request never reached the handler.
    pub async fn create_by_profile(
        &self,
        params: &CustomerCreateRequest,
    ) -> Result<CustomerResponse> {
        params.validate()?;
        let body = to_json_vec(params)?;
        self.inner
            .request_body_keyed_with_query_and_headers(
                HttpMethod::Post,
                "/customers/profile",
                Some(&body),
                &[],
                &self.profile_headers(),
                None,
            )
            .await
    }

    /// Update a customer of the shop the credential is bound to
    /// (`POST /customers/profile/{customer_id}`): one the shop created, placed
    /// in the shop, or one that has paid there. A sibling shop's customer
    /// answers `CustomerNotFound`, like an unknown one.
    pub async fn update_by_profile(
        &self,
        customer_id: &str,
        params: &CustomerCreateRequest,
    ) -> Result<CustomerResponse> {
        params.validate()?;
        let path = format!("/customers/profile/{}", encode_segment(customer_id));
        let body = to_json_vec(params)?;
        self.inner
            .request_with_headers(
                HttpMethod::Post,
                &path,
                Some(&body),
                &[],
                None,
                &self.profile_headers(),
            )
            .await
    }

    /// List one customer's mandates, scoped to the shop the credential is bound
    /// to (`GET /customers/profile/{customer_id}/mandates`) — the shop-scoped
    /// twin of [`list_mandates`](Self::list_mandates).
    pub async fn list_mandates_by_profile(
        &self,
        customer_id: &str,
    ) -> Result<Vec<MandateResponse>> {
        let path = format!(
            "/customers/profile/{}/mandates",
            encode_segment(customer_id)
        );
        self.inner
            .request_with_headers(
                HttpMethod::Get,
                &path,
                None,
                &[],
                None,
                &self.profile_headers(),
            )
            .await
    }

    /// Place an existing customer in a shop of the merchant
    /// (`POST /customers/{customer_id}/shops`), so that shop's keys and team
    /// find the customer before any payment. The customer keeps the shops they
    /// belong to. Needs a merchant-wide key; a key bound to one shop is
    /// refused. An unknown customer answers `CustomerNotFound`.
    pub async fn place_in_shop(
        &self,
        customer_id: &str,
        profile_id: &str,
    ) -> Result<CustomerShopPlacementResponse> {
        let path = format!("/customers/{}/shops", encode_segment(customer_id));
        let body = to_json_vec(&serde_json::json!({ "profile_id": profile_id }))?;
        self.inner
            .request(HttpMethod::Post, &path, Some(&body), &[], None)
            .await
    }

    /// Place up to 500 existing customers in one shop of the merchant
    /// (`POST /customers/shops/place`). The answer lists every distinct
    /// customer in request order with `placed`, `already_in_shop` or
    /// `not_found`. Needs a merchant-wide key.
    pub async fn place_many_in_shop(
        &self,
        profile_id: &str,
        customer_ids: &[&str],
    ) -> Result<CustomerShopBulkPlacementResponse> {
        let body = to_json_vec(&serde_json::json!({
            "profile_id": profile_id,
            "customer_ids": customer_ids,
        }))?;
        self.inner
            .request(
                HttpMethod::Post,
                "/customers/shops/place",
                Some(&body),
                &[],
                None,
            )
            .await
    }

    /// List the mandates held against a customer.
    pub async fn list_mandates(&self, customer_id: &str) -> Result<Vec<MandateResponse>> {
        let path = format!("/customers/{}/mandates", encode_segment(customer_id));
        self.inner
            .request(HttpMethod::Get, &path, None, &[], None)
            .await
    }

    /// Check identity import rows (email addresses, names, handles) and say
    /// what an import would do with each. Writes nothing.
    ///
    /// Merchant-wide API keys only: a shop-scoped key is refused (403,
    /// `IR_22`). The API may hold a merchant to fewer rows than 1,000 (422,
    /// `IR_06`). No rows, more than 1,000, a time without its UTC offset and
    /// a body over [`MAX_IDENTITY_IMPORT_REQUEST_BYTES`] are refused before
    /// anything is sent.
    pub async fn preview_identity_import(
        &self,
        params: &CustomerIdentityImportPreviewRequest,
    ) -> Result<CustomerIdentityImportPreviewResponse> {
        check_rows(&params.rows)?;
        let body = to_json_vec(params)?;
        check_body(&body, MAX_IDENTITY_IMPORT_REQUEST_BYTES)?;
        self.inner
            .request(
                HttpMethod::Post,
                "/customers/identity-history/import/preview",
                Some(&body),
                &[],
                None,
            )
            .await
    }

    /// Record identity import rows in the customers' identity history, apart
    /// from their current details.
    ///
    /// Idempotent per `idempotency_key`: a request repeated under the same key
    /// answers the first run (`replayed: true`) and writes nothing, and the
    /// same key with different rows is refused (400, `IR_38`). A network error
    /// or `5xx` is retried under the unchanged key when retries are enabled,
    /// so a retry can never record the rows twice.
    ///
    /// Merchant-wide API keys only (403, `IR_22` otherwise). The API may hold
    /// a merchant to fewer rows than 1,000 (422, `IR_06`) and to a number of
    /// imports a minute (429, `IR_52`, with `Retry-After`, which the client
    /// honours when retries are enabled). Checked before sending, as for
    /// [`preview_identity_import`](Self::preview_identity_import), and the key
    /// too.
    pub async fn import_identity_history(
        &self,
        params: &CustomerIdentityImportRequest,
    ) -> Result<CustomerIdentityImportResponse> {
        check_rows(&params.rows)?;
        let key = require_import_key(&params.idempotency_key)?;
        let body = to_json_vec(params)?;
        check_body(&body, MAX_IDENTITY_IMPORT_REQUEST_BYTES)?;
        self.inner
            .request_body_keyed(
                HttpMethod::Post,
                "/customers/identity-history/import",
                Some(&body),
                Some(key),
            )
            .await
    }

    /// Read an identity import back: its rows and the history entries they
    /// map to, for reconciling a run before deleting your own copy.
    ///
    /// Merchant-wide API keys only (403, `IR_22` otherwise). A run of another
    /// merchant, or none, answers 404 (`IR_37`).
    pub async fn retrieve_identity_import(
        &self,
        run_id: &str,
    ) -> Result<CustomerIdentityImportResponse> {
        let path = format!(
            "/customers/identity-history/import/{}",
            encode_segment(run_id)
        );
        self.inner
            .request(HttpMethod::Get, &path, None, &[], None)
            .await
    }

    /// The identity history of up to 1,000 customers.
    ///
    /// Merchant-wide API keys only (403, `IR_22` otherwise). The API may hold
    /// a merchant to fewer customers than 1,000 (422, `IR_06`). No ids, more
    /// than 1,000 and a body over [`MAX_IDENTITY_HISTORY_REQUEST_BYTES`] are
    /// refused before anything is sent.
    pub async fn list_identity_history(
        &self,
        params: &CustomerIdentityHistoryRequest,
    ) -> Result<CustomerIdentityHistoryResponse> {
        if params.customer_ids.is_empty() || params.customer_ids.len() > MAX_IDENTITY_CUSTOMERS {
            return Err(DelopayError::InvalidRequest(format!(
                "`customer_ids` must hold 1 to {MAX_IDENTITY_CUSTOMERS} ids"
            )));
        }
        let body = to_json_vec(params)?;
        check_body(&body, MAX_IDENTITY_HISTORY_REQUEST_BYTES)?;
        self.inner
            .request(
                HttpMethod::Post,
                "/customers/identity-history/list",
                Some(&body),
                &[],
                None,
            )
            .await
    }

    /// Search the merchant's identity history for email addresses, names and
    /// handles containing a text of at least three characters. The text
    /// travels in the body, never in the URL.
    ///
    /// Merchant-wide API keys only (403, `IR_22` otherwise). A `limit`
    /// outside 1 to 100, a `query` over
    /// [`MAX_IDENTITY_SEARCH_QUERY_CHARS`] characters and a `cursor` without
    /// `group_by_customer` are refused before anything is sent. The API counts
    /// the three characters after folding case, width and whitespace, so a
    /// shorter query, and a cursor it did not issue for this query, are
    /// refused there (422, `IR_06`).
    pub async fn search_identity_history(
        &self,
        params: &CustomerIdentityHistorySearchRequest,
    ) -> Result<CustomerIdentityHistoryResponse> {
        if let Some(limit) = params.limit
            && !(1..=MAX_IDENTITY_SEARCH_RESULTS).contains(&limit)
        {
            return Err(DelopayError::InvalidRequest(format!(
                "`limit` must be 1 to {MAX_IDENTITY_SEARCH_RESULTS}"
            )));
        }
        if params.query.chars().count() > MAX_IDENTITY_SEARCH_QUERY_CHARS {
            return Err(DelopayError::InvalidRequest(format!(
                "`query` must hold at most {MAX_IDENTITY_SEARCH_QUERY_CHARS} characters"
            )));
        }
        if params.cursor.is_some() && !params.group_by_customer {
            return Err(DelopayError::InvalidRequest(
                "`cursor` pages a search by customer; set `group_by_customer`".to_owned(),
            ));
        }
        let body = to_json_vec(params)?;
        self.inner
            .request(
                HttpMethod::Post,
                "/customers/identity-history/search",
                Some(&body),
                &[],
                None,
            )
            .await
    }
}

impl Customers {
    /// Issue a shop-scoped customer portal link for this customer.
    /// Subscription changes stay off unless the request's
    /// `allow_subscription_changes` is set.
    ///
    /// The returned [`BuyerInvoiceLink::url`] is a credential: share it only
    /// with the intended buyer.
    ///
    /// `POST /customers/{customer_id}/portal-links`
    pub async fn create_portal_link(
        &self,
        customer_id: &str,
        params: &BuyerInvoiceLinkRequest,
    ) -> Result<BuyerInvoiceLink> {
        params.validate()?;
        let path = portal_links_path(customer_id);
        let body = to_json_vec(params)?;
        self.inner
            .request_body_keyed(HttpMethod::Post, &path, Some(&body), None)
            .await
    }

    /// The customer's active portal links in the caller's scope, without
    /// their URLs.
    ///
    /// `GET /customers/{customer_id}/portal-links`
    pub async fn list_portal_links(
        &self,
        customer_id: &str,
        params: Option<&BuyerPortalLinkListParams>,
    ) -> Result<BuyerPortalLinkPage> {
        let path = portal_links_path(customer_id);
        let query = params
            .map(BuyerPortalLinkListParams::to_query)
            .unwrap_or_default();
        self.inner
            .request(HttpMethod::Get, &path, None, &query, None)
            .await
    }

    /// Revoke a portal link. A link outside the caller's scope, or none,
    /// answers 404.
    ///
    /// `DELETE /customers/{customer_id}/portal-links/{link_id}`
    pub async fn revoke_portal_link(&self, customer_id: &str, link_id: &str) -> Result<()> {
        let path = format!(
            "{}/{}",
            portal_links_path(customer_id),
            encode_segment(link_id)
        );
        // Any success body, empty or JSON, is accepted and dropped.
        self.inner
            .request_body_keyed::<serde::de::IgnoredAny>(HttpMethod::Delete, &path, None, None)
            .await
            .map(|_| ())
    }
}

/// `/customers/{customer_id}/portal-links`, percent-encoded.
fn portal_links_path(customer_id: &str) -> String {
    format!("/customers/{}/portal-links", encode_segment(customer_id))
}

/// Body of [`Customers::create_portal_link`].
#[derive(Debug, Clone, Default, Serialize)]
pub struct BuyerInvoiceLinkRequest {
    /// The shop the link is for. A shop-scoped caller must name its own
    /// shop; a merchant-level caller may leave it out.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub profile_id: Option<String>,
    /// Include the customer's own subscription self-service. Needs
    /// subscription write access.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub allow_subscription_changes: Option<bool>,
    /// Ceilings over the shop's current portal permissions. Leaving it out
    /// keeps the shop's permissions; it never enables a forbidden action.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub restrictions: Option<BuyerPortalLinkRestrictions>,
    /// The link's lifetime in seconds: five minutes to thirty days, seven
    /// days by default.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub expires_in_seconds: Option<u32>,
    /// Any additional fields, merged verbatim.
    #[serde(flatten, skip_serializing_if = "serde_json::Map::is_empty")]
    pub extra: serde_json::Map<String, Value>,
}

impl BuyerInvoiceLinkRequest {
    /// A link with the shop's own permissions and the default lifetime.
    pub fn new() -> Self {
        Self::default()
    }

    /// The shop the link is for.
    #[must_use]
    pub fn profile_id(mut self, profile_id: impl Into<String>) -> Self {
        self.profile_id = Some(profile_id.into());
        self
    }

    /// Include subscription self-service.
    #[must_use]
    pub fn allow_subscription_changes(mut self, allow: bool) -> Self {
        self.allow_subscription_changes = Some(allow);
        self
    }

    /// Narrow the shop's portal permissions for this link.
    #[must_use]
    pub fn restrictions(mut self, restrictions: BuyerPortalLinkRestrictions) -> Self {
        self.restrictions = Some(restrictions);
        self
    }

    /// The link's lifetime in seconds.
    #[must_use]
    pub fn expires_in_seconds(mut self, seconds: u32) -> Self {
        self.expires_in_seconds = Some(seconds);
        self
    }
}

/// Names of `BuyerInvoiceLinkRequest`'s fields as they appear on the wire
/// (`extra` excluded).
const BUYER_INVOICE_LINK_REQUEST_NAMED: &[&str] = &[
    "profile_id",
    "allow_subscription_changes",
    "restrictions",
    "expires_in_seconds",
];

/// Names of `BuyerPortalLinkRestrictions`'s fields as they appear on the
/// wire (`extra` excluded).
const BUYER_PORTAL_LINK_RESTRICTIONS_NAMED: &[&str] = &[
    "subscription_changes",
    "subscription_actions",
    "profile_changes",
    "email_policy",
    "refund_requests",
    "refund_requests_for_renewals",
];

/// Names of `BuyerPortalSubscriptionPermissions`'s fields as they appear on
/// the wire (`extra` excluded).
const BUYER_PORTAL_SUBSCRIPTION_PERMISSIONS_NAMED: &[&str] = &[
    "pause",
    "resume",
    "cancel_at_period_end",
    "cancel_immediately",
    "change_plan",
];

fn reject_colliding_extra(
    extra: &serde_json::Map<String, Value>,
    named: &[&str],
    type_name: &str,
) -> Result<()> {
    for key in extra.keys() {
        if named.contains(&key.as_str()) {
            return Err(DelopayError::InvalidRequest(format!(
                "`extra` key `{key}` collides with a named field on {type_name}"
            )));
        }
    }
    Ok(())
}

impl ValidateRequest for BuyerInvoiceLinkRequest {
    fn validate(&self) -> Result<()> {
        reject_colliding_extra(
            &self.extra,
            BUYER_INVOICE_LINK_REQUEST_NAMED,
            "BuyerInvoiceLinkRequest",
        )?;
        if let Some(restrictions) = &self.restrictions {
            reject_colliding_extra(
                &restrictions.extra,
                BUYER_PORTAL_LINK_RESTRICTIONS_NAMED,
                "BuyerPortalLinkRestrictions",
            )?;
            if let Some(actions) = &restrictions.subscription_actions {
                reject_colliding_extra(
                    &actions.extra,
                    BUYER_PORTAL_SUBSCRIPTION_PERMISSIONS_NAMED,
                    "BuyerPortalSubscriptionPermissions",
                )?;
            }
        }
        Ok(())
    }
}

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

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

/// The most rows one identity import or preview may carry.
pub const MAX_IDENTITY_IMPORT_ROWS: usize = 1000;

/// The most customers one identity history read may name.
pub const MAX_IDENTITY_CUSTOMERS: usize = 1000;

/// The most entries one identity search returns.
pub const MAX_IDENTITY_SEARCH_RESULTS: u32 = 100;

/// The longest identity search text, in characters.
pub const MAX_IDENTITY_SEARCH_QUERY_CHARS: usize = 256;

/// The largest JSON body an identity import or preview may send: 1,000 rows
/// at 7 KiB each, plus 16 KiB for the key and the envelope. A larger body is
/// refused before it is sent; the API would answer 413.
pub const MAX_IDENTITY_IMPORT_REQUEST_BYTES: usize = 1000 * 7 * 1024 + 16 * 1024;

/// The largest JSON body an identity history read may send. A larger body is
/// refused before it is sent; the API would answer 413.
pub const MAX_IDENTITY_HISTORY_REQUEST_BYTES: usize = 128 * 1024;

const MAX_IDEMPOTENCY_KEY_CHARS: usize = 255;

fn check_rows(rows: &[CustomerIdentityImportRow]) -> Result<()> {
    if rows.is_empty() || rows.len() > MAX_IDENTITY_IMPORT_ROWS {
        return Err(DelopayError::InvalidRequest(format!(
            "`rows` must hold 1 to {MAX_IDENTITY_IMPORT_ROWS} rows"
        )));
    }
    for (index, row) in rows.iter().enumerate() {
        for (name, value) in [
            ("first_seen_at", &row.first_seen_at),
            ("last_seen_at", &row.last_seen_at),
        ] {
            if value
                .as_deref()
                .is_some_and(|value| !names_its_offset(value))
            {
                return Err(DelopayError::InvalidRequest(format!(
                    "`rows[{index}].{name}` must be an ISO 8601 date and time with its UTC \
                     offset, such as `2026-10-31T12:00:00Z`"
                )));
            }
        }
    }
    Ok(())
}

/// Whether an ISO 8601 date and time states its UTC offset (`Z`, `+01:00`).
/// The API reads these times with their offset and refuses the whole request
/// (400) for one without it.
fn names_its_offset(value: &str) -> bool {
    let Some((_, time)) = value.split_once(['T', 't']) else {
        return false;
    };
    if time.ends_with(['Z', 'z']) {
        return true;
    }
    time.rfind(['+', '-']).is_some_and(|at| {
        at > 0
            && time.get(at + 1..).is_some_and(|offset| {
                !offset.is_empty() && offset.chars().all(|c| c.is_ascii_digit() || c == ':')
            })
    })
}

fn check_body(body: &[u8], limit: usize) -> Result<()> {
    if body.len() > limit {
        return Err(DelopayError::InvalidRequest(format!(
            "the request body is {} bytes, over the {limit} bytes the API accepts",
            body.len()
        )));
    }
    Ok(())
}

/// The import key, checked as the API checks it, so a key the API refuses is
/// never sent and a valid one is the same on every retry.
fn require_import_key(key: &str) -> Result<&str> {
    if key.trim().is_empty()
        || key.chars().count() > MAX_IDEMPOTENCY_KEY_CHARS
        || key.chars().any(char::is_control)
    {
        return Err(DelopayError::InvalidRequest(format!(
            "`idempotency_key` must hold 1 to {MAX_IDEMPOTENCY_KEY_CHARS} printable characters"
        )));
    }
    Ok(key)
}

/// One value to import for one customer.
#[derive(Clone, Serialize)]
pub struct CustomerIdentityImportRow {
    /// The customer the value belongs to. It need not exist as a customer
    /// yet; the value is recorded under the id.
    pub customer_id: String,
    /// `email`, `name` or `handle`.
    pub kind: String,
    /// The value as you hold it. It is stored encrypted.
    pub value: String,
    /// Your own reference for this row, unique in your export. Importing the
    /// same reference again changes nothing.
    pub external_ref: String,
    /// Where you learnt the value: lowercase letters, digits, `_`, `-` and
    /// `.`, up to 64 characters.
    pub source_label: String,
    /// When the value was first seen, if you know it: an ISO 8601 date and
    /// time with its UTC offset (`2026-10-31T12:00:00Z`). Leave it out
    /// otherwise; no other date is filled in.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub first_seen_at: Option<String>,
    /// When the value was last seen, if you know it, as `first_seen_at`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub last_seen_at: Option<String>,
}

impl std::fmt::Debug for CustomerIdentityImportRow {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("CustomerIdentityImportRow")
            .field("customer_id", &self.customer_id)
            .field("kind", &self.kind)
            .field("value", &"<redacted>")
            .field("external_ref", &self.external_ref)
            .field("source_label", &self.source_label)
            .field("first_seen_at", &self.first_seen_at)
            .field("last_seen_at", &self.last_seen_at)
            .finish()
    }
}

/// Body of [`Customers::preview_identity_import`].
#[derive(Debug, Clone, Serialize)]
pub struct CustomerIdentityImportPreviewRequest {
    /// 1 to 1,000 rows.
    pub rows: Vec<CustomerIdentityImportRow>,
}

/// Body of [`Customers::import_identity_history`].
#[derive(Debug, Clone, Serialize)]
pub struct CustomerIdentityImportRequest {
    /// Your key for this request, unique per request, up to 255 printable
    /// characters. Keep it when you retry the same rows.
    pub idempotency_key: String,
    /// 1 to 1,000 rows.
    pub rows: Vec<CustomerIdentityImportRow>,
}

/// Body of [`Customers::list_identity_history`].
#[derive(Debug, Clone, Serialize)]
pub struct CustomerIdentityHistoryRequest {
    /// 1 to 1,000 customer ids.
    pub customer_ids: Vec<String>,
}

/// Body of [`Customers::search_identity_history`].
#[derive(Clone, Serialize)]
pub struct CustomerIdentityHistorySearchRequest {
    /// At least three characters, compared ignoring case, width and repeated
    /// whitespace, anywhere inside an email address, name or handle.
    pub query: String,
    /// The most entries to return, 1 to 100. 20 by default. With
    /// [`group_by_customer`](Self::group_by_customer), the most customers.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub limit: Option<u32>,
    /// Answer by customer: each matching customer once in `customers`, with
    /// every matching value, `limit` counting customers, plus
    /// `total_customers` and `next_cursor`. `entries` is then empty.
    #[serde(skip_serializing_if = "std::ops::Not::not")]
    pub group_by_customer: bool,
    /// With [`group_by_customer`](Self::group_by_customer): the previous
    /// page's `next_cursor`, for the customers after it.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cursor: Option<String>,
}

impl CustomerIdentityHistorySearchRequest {
    /// A search for `query` answered by entry, 20 at most.
    pub fn new(query: impl Into<String>) -> Self {
        Self {
            query: query.into(),
            limit: None,
            group_by_customer: false,
            cursor: None,
        }
    }
}

impl std::fmt::Debug for CustomerIdentityHistorySearchRequest {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("CustomerIdentityHistorySearchRequest")
            .field("query", &"<redacted>")
            .field("limit", &self.limit)
            .field("group_by_customer", &self.group_by_customer)
            .field("cursor", &self.cursor.as_ref().map(|_| "<cursor>"))
            .finish()
    }
}

/// Filter / pagination parameters for [`Customers::list`],
/// [`Customers::list_with_count`] and their profile-scoped variants
/// [`Customers::list_by_profile`] and [`Customers::list_by_profile_with_count`].
#[derive(Debug, Clone, Default)]
pub struct CustomerListParams {
    /// Maximum number of customers to return.
    pub limit: Option<i64>,
    /// Number of customers to skip.
    pub offset: Option<i64>,
    /// Only the customer with this ID.
    pub customer_id: Option<String>,
    /// Case-insensitive prefix search over customer ID, name and email; each
    /// term needs at least 3 characters.
    pub search: Option<String>,
    /// Only the customer with exactly this email address, ignoring case. How
    /// an integration finds an existing customer before it creates one, also
    /// with a key bound to one shop. Combines with the other filters.
    pub email: Option<String>,
    /// With-count lists only: customers created at or after this ISO 8601
    /// time.
    pub start_time: Option<String>,
    /// With-count lists only: customers created at or before this ISO 8601
    /// time.
    pub end_time: Option<String>,
    /// Only customers who have transacted in this shop (business profile).
    pub profile_id: Option<String>,
    /// Only customers who have transacted in one of these shops. Unions with
    /// [`profile_id`](Self::profile_id) and [`project_id`](Self::project_id) —
    /// a customer matches if they transacted in any of the resolved shops.
    ///
    /// Every id must belong to the calling merchant, otherwise the request is
    /// rejected with `AccessForbidden`.
    pub profile_ids: Vec<String>,
    /// Only customers who have transacted in this project (all its shops).
    pub project_id: Option<String>,
}

impl CustomerListParams {
    fn to_query(&self) -> Vec<(&'static str, String)> {
        let mut q = Vec::new();
        if let Some(v) = self.limit {
            q.push(("limit", v.to_string()));
        }
        if let Some(v) = self.offset {
            q.push(("offset", v.to_string()));
        }
        if let Some(v) = &self.customer_id {
            q.push(("customer_id", v.clone()));
        }
        if let Some(v) = &self.search {
            q.push(("search", v.clone()));
        }
        if let Some(v) = &self.email {
            q.push(("email", v.clone()));
        }
        if let Some(v) = &self.start_time {
            q.push(("start_time", v.clone()));
        }
        if let Some(v) = &self.end_time {
            q.push(("end_time", v.clone()));
        }
        if let Some(v) = &self.profile_id {
            q.push(("profile_id", v.clone()));
        }
        // One comma-separated value, not repeated keys: the customers endpoints
        // cannot parse `?profile_ids=a&profile_ids=b` and fail the whole
        // request rather than ignoring the second id. An empty list means "no
        // shop filter", which is the absent key.
        if !self.profile_ids.is_empty() {
            q.push(("profile_ids", self.profile_ids.join(",")));
        }
        if let Some(v) = &self.project_id {
            q.push(("project_id", v.clone()));
        }
        q
    }

    /// Filter by several shops at once.
    #[must_use]
    pub fn profile_ids<I, S>(mut self, profile_ids: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.profile_ids = profile_ids.into_iter().map(Into::into).collect();
        self
    }
}

/// Parameters for [`Customers::create`], [`Customers::update`] and their
/// shop-scoped twins [`Customers::create_by_profile`] and
/// [`Customers::update_by_profile`].
#[derive(Debug, Clone, Default, Serialize)]
pub struct CustomerCreateRequest {
    /// Provide your own customer ID (acts as an idempotency key server-side).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub customer_id: Option<String>,
    /// Customer's full name.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    /// Customer's email address.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub email: Option<String>,
    /// Customer's phone number (digits only).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub phone: Option<String>,
    /// Phone country code (e.g. `"+44"`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub phone_country_code: Option<String>,
    /// Internal notes about the customer.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    /// Default billing/shipping address (open shape — see the API reference).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub address: Option<Value>,
    /// Arbitrary key-value metadata.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub metadata: Option<Value>,
    /// On [`Customers::create`] with a merchant-wide key: the shop the new
    /// customer belongs to at once. It must be a shop of the merchant. On
    /// [`Customers::create_by_profile`] only the caller's own shop is accepted.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub profile_id: Option<String>,
    /// Any additional fields, merged verbatim.
    #[serde(flatten, skip_serializing_if = "serde_json::Map::is_empty")]
    pub extra: serde_json::Map<String, Value>,
}

/// Names of `CustomerCreateRequest`'s fields, as they appear on the wire
/// (`extra` excluded). See `PAYMENT_CREATE_REQUEST_NAMED` in `payments.rs`
/// for why this list lives next to the struct.
const CUSTOMER_CREATE_REQUEST_NAMED: &[&str] = &[
    "customer_id",
    "name",
    "email",
    "phone",
    "phone_country_code",
    "description",
    "address",
    "metadata",
    "profile_id",
];

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

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

    /// Name the shop a merchant-wide key creates the customer in.
    pub fn profile_id(mut self, profile_id: impl Into<String>) -> Self {
        self.profile_id = Some(profile_id.into());
        self
    }

    /// Set the customer's email.
    pub fn email(mut self, email: impl Into<String>) -> Self {
        self.email = Some(email.into());
        self
    }

    /// Set the customer's name.
    pub fn name(mut self, name: impl Into<String>) -> Self {
        self.name = Some(name.into());
        self
    }

    /// Set the customer's phone (digits) and country code.
    pub fn phone(mut self, phone: impl Into<String>, country_code: impl Into<String>) -> Self {
        self.phone = Some(phone.into());
        self.phone_country_code = Some(country_code.into());
        self
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    use crate::core::models::buyer_portal::BuyerPortalSubscriptionPermissions;
    use crate::core::models::customer_identity::CustomerIdentityImportOutcome;
    use crate::http::mock::{Step, client_with, client_with_retries};

    const IMPORT_JSON: &str = r#"{
        "run_id": "cir_1",
        "idempotency_key": "af-0001",
        "replayed": false,
        "rows_total": 1,
        "rows_accepted": 1,
        "rows_unchanged": 0,
        "rows_rejected": 0,
        "created_at": "2026-10-31T12:00:00.000Z",
        "rows": [{"row_index": 0, "external_ref": "u1-email-0", "customer_id": "cus_1",
                  "kind": "email", "outcome": "accepted", "reason": null, "entry_id": "cih_1"}]
    }"#;

    const PORTAL_LINK_SUMMARY_JSON: &str = r#"{
        "id": "bpl_1",
        "profile_id": "pro_1",
        "expires_at": 1767225600,
        "allow_subscription_changes": true,
        "restrictions": {"refund_requests": false, "subscription_actions": {"pause": true}},
        "surprise_field": 1
    }"#;

    #[tokio::test]
    async fn create_portal_link_posts_only_the_set_fields() {
        let (client, mock) = client_with(vec![Step::ok(
            r##"{"id":"bpl_1","url":"https://portal.test/#tok","expires_at":1767225600,"surprise_field":1}"##,
        )]);
        let params = BuyerInvoiceLinkRequest::new()
            .profile_id("pro_1")
            .allow_subscription_changes(true)
            .restrictions(
                BuyerPortalLinkRestrictions::new()
                    .refund_requests(false)
                    .subscription_actions(BuyerPortalSubscriptionPermissions::new().pause(true)),
            )
            .expires_in_seconds(3600);
        let link = client
            .customers()
            .create_portal_link("cus/1", &params)
            .await
            .unwrap();
        assert_eq!(link.id, "bpl_1");
        assert_eq!(link.url, "https://portal.test/#tok");
        assert_eq!(link.expires_at, 1_767_225_600);
        assert_eq!(link.extra["surprise_field"], 1);

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(
            seen[0].url,
            "https://api.test/customers/cus%2F1/portal-links"
        );
        assert_eq!(
            seen[0].body_json(),
            json!({
                "profile_id": "pro_1",
                "allow_subscription_changes": true,
                "restrictions": {"refund_requests": false, "subscription_actions": {"pause": true}},
                "expires_in_seconds": 3600
            })
        );
    }

    #[tokio::test]
    async fn create_portal_link_sends_an_empty_object_by_default() {
        let (client, mock) = client_with(vec![Step::ok(
            r#"{"id":"bpl_1","url":"https://portal.test/","expires_at":1}"#,
        )]);
        client
            .customers()
            .create_portal_link("cus_1", &BuyerInvoiceLinkRequest::new())
            .await
            .unwrap();
        assert_eq!(mock.seen.lock().unwrap()[0].body_json(), json!({}));
    }

    #[tokio::test]
    async fn list_portal_links_serializes_pagination() {
        let page = format!(
            r#"{{"data":[{PORTAL_LINK_SUMMARY_JSON}],"total_count":1,"limit":10,"offset":20}}"#
        );
        let (client, mock) = client_with(vec![Step::ok(&page), Step::ok(&page)]);
        let customers = client.customers();
        let out = customers
            .list_portal_links(
                "cus/1",
                Some(&BuyerPortalLinkListParams {
                    limit: Some(10),
                    offset: Some(20),
                }),
            )
            .await
            .unwrap();
        assert_eq!(out.total_count, 1);
        let summary = &out.data[0];
        assert_eq!(summary.id, "bpl_1");
        assert!(summary.allow_subscription_changes);
        assert_eq!(summary.restrictions.refund_requests, Some(false));
        assert_eq!(
            summary
                .restrictions
                .subscription_actions
                .as_ref()
                .unwrap()
                .pause,
            Some(true)
        );
        assert_eq!(summary.extra["surprise_field"], 1);
        customers.list_portal_links("cus/1", None).await.unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "GET");
        assert_eq!(
            seen[0].url,
            "https://api.test/customers/cus%2F1/portal-links?limit=10&offset=20"
        );
        assert_eq!(
            seen[1].url,
            "https://api.test/customers/cus%2F1/portal-links"
        );
    }

    #[tokio::test]
    async fn revoke_portal_link_deletes_the_link_path_and_accepts_an_empty_body() {
        let (client, mock) = client_with(vec![Step::ok(""), Step::ok(r#"{"revoked":true}"#)]);
        let customers = client.customers();
        customers
            .revoke_portal_link("cus/1", "bpl/1")
            .await
            .unwrap();
        // A body the API may add later must not break the call.
        customers
            .revoke_portal_link("cus/1", "bpl/1")
            .await
            .unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "DELETE");
        assert_eq!(
            seen[0].url,
            "https://api.test/customers/cus%2F1/portal-links/bpl%2F1"
        );
    }

    /// Drift guard for `BUYER_INVOICE_LINK_REQUEST_NAMED`.
    #[test]
    fn buyer_invoice_link_request_named_fields_are_complete() {
        let value = serde_json::to_value(
            BuyerInvoiceLinkRequest::new()
                .profile_id("pro_1")
                .allow_subscription_changes(true)
                .restrictions(BuyerPortalLinkRestrictions::new())
                .expires_in_seconds(3600),
        )
        .unwrap();
        for key in value.as_object().expect("serializes to an object").keys() {
            assert!(
                BUYER_INVOICE_LINK_REQUEST_NAMED.contains(&key.as_str()),
                "BUYER_INVOICE_LINK_REQUEST_NAMED is missing wire key `{key}`"
            );
        }
    }

    /// Drift guard for `BUYER_PORTAL_LINK_RESTRICTIONS_NAMED`.
    #[test]
    fn buyer_portal_link_restrictions_named_fields_are_complete() {
        let value = serde_json::to_value(
            BuyerPortalLinkRestrictions::new()
                .subscription_changes(true)
                .subscription_actions(BuyerPortalSubscriptionPermissions::new())
                .profile_changes(false)
                .email_policy("read_only")
                .refund_requests(true)
                .refund_requests_for_renewals(false),
        )
        .unwrap();
        for key in value.as_object().expect("serializes to an object").keys() {
            assert!(
                BUYER_PORTAL_LINK_RESTRICTIONS_NAMED.contains(&key.as_str()),
                "BUYER_PORTAL_LINK_RESTRICTIONS_NAMED is missing wire key `{key}`"
            );
        }
    }

    /// Drift guard for `BUYER_PORTAL_SUBSCRIPTION_PERMISSIONS_NAMED`.
    #[test]
    fn buyer_portal_subscription_permissions_named_fields_are_complete() {
        let value = serde_json::to_value(
            BuyerPortalSubscriptionPermissions::new()
                .pause(true)
                .resume(true)
                .cancel_at_period_end(false)
                .cancel_immediately(false)
                .change_plan(true),
        )
        .unwrap();
        for key in value.as_object().expect("serializes to an object").keys() {
            assert!(
                BUYER_PORTAL_SUBSCRIPTION_PERMISSIONS_NAMED.contains(&key.as_str()),
                "BUYER_PORTAL_SUBSCRIPTION_PERMISSIONS_NAMED is missing wire key `{key}`"
            );
        }
    }

    #[test]
    fn portal_link_validate_rejects_colliding_extra_keys_at_every_level() {
        let mut top = BuyerInvoiceLinkRequest::new();
        top.extra.insert("profile_id".to_string(), json!("pro_2"));
        assert!(matches!(
            top.validate(),
            Err(DelopayError::InvalidRequest(msg)) if msg.contains("profile_id")
        ));

        let mut restrictions = BuyerPortalLinkRestrictions::new();
        restrictions
            .extra
            .insert("refund_requests".to_string(), json!(true));
        let nested = BuyerInvoiceLinkRequest::new().restrictions(restrictions);
        assert!(matches!(
            nested.validate(),
            Err(DelopayError::InvalidRequest(msg)) if msg.contains("refund_requests")
        ));

        let mut actions = BuyerPortalSubscriptionPermissions::new();
        actions.extra.insert("pause".to_string(), json!(true));
        let deepest = BuyerInvoiceLinkRequest::new()
            .restrictions(BuyerPortalLinkRestrictions::new().subscription_actions(actions));
        assert!(matches!(
            deepest.validate(),
            Err(DelopayError::InvalidRequest(msg)) if msg.contains("pause")
        ));
    }

    fn identity_row() -> CustomerIdentityImportRow {
        CustomerIdentityImportRow {
            customer_id: "cus_1".to_string(),
            kind: "email".to_string(),
            value: "jane.doe@example.com".to_string(),
            external_ref: "u1-email-0".to_string(),
            source_label: "account".to_string(),
            first_seen_at: None,
            last_seen_at: None,
        }
    }

    fn import_request(key: &str) -> CustomerIdentityImportRequest {
        CustomerIdentityImportRequest {
            idempotency_key: key.to_string(),
            rows: vec![identity_row()],
        }
    }

    #[tokio::test]
    async fn identity_import_posts_the_rows_with_their_key_in_body_and_header() {
        let (client, mock) = client_with(vec![Step::ok(IMPORT_JSON)]);
        let run = client
            .customers()
            .import_identity_history(&import_request("af-0001"))
            .await
            .unwrap();
        assert_eq!(run.run_id, "cir_1");
        assert_eq!(run.rows[0].outcome, CustomerIdentityImportOutcome::Accepted);

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(
            seen[0].url,
            "https://api.test/customers/identity-history/import"
        );
        assert_eq!(seen[0].header("idempotency-key"), Some("af-0001"));
        let body = seen[0].body_json();
        assert_eq!(body["idempotency_key"], "af-0001");
        assert_eq!(body["rows"][0]["value"], "jane.doe@example.com");
        // Unknown dates are left out, never sent as null.
        assert!(body["rows"][0].get("first_seen_at").is_none());
    }

    #[tokio::test]
    async fn identity_import_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(IMPORT_JSON),
            ],
            2,
        );
        client
            .customers()
            .import_identity_history(&import_request("af-0001"))
            .await
            .unwrap();
        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen.len(), 2);
        assert_eq!(seen[1].header("idempotency-key"), Some("af-0001"));
        assert_eq!(seen[1].body_json()["idempotency_key"], "af-0001");
    }

    #[tokio::test]
    async fn identity_preview_is_not_retried_after_a_5xx() {
        let (client, mock) = client_with_retries(
            vec![
                Step::status(500, r#"{"error":{"message":"boom"}}"#),
                Step::ok(
                    r#"{"rows_total":1,"rows_accepted":1,"rows_unchanged":0,"rows_rejected":0,"customers_without_record":0,"rows":[]}"#,
                ),
            ],
            2,
        );
        let out = client
            .customers()
            .preview_identity_import(&CustomerIdentityImportPreviewRequest {
                rows: vec![identity_row()],
            })
            .await;
        assert!(out.is_err());
        assert_eq!(mock.seen.lock().unwrap().len(), 1);
    }

    #[tokio::test]
    async fn identity_import_refuses_a_key_the_api_would_refuse_without_sending() {
        let (client, mock) = client_with(vec![]);
        for key in ["", "   ", "line\nbreak", &"k".repeat(256)] {
            let out = client
                .customers()
                .import_identity_history(&import_request(key))
                .await;
            assert!(
                matches!(out, Err(DelopayError::InvalidRequest(_))),
                "{key:?}"
            );
        }
        assert_eq!(mock.seen.lock().unwrap().len(), 0);
    }

    #[tokio::test]
    async fn identity_import_refuses_no_rows_and_more_than_a_thousand() {
        let (client, mock) = client_with(vec![]);
        let mut request = import_request("af-0001");
        request.rows.clear();
        assert!(
            client
                .customers()
                .import_identity_history(&request)
                .await
                .is_err()
        );
        request.rows = vec![identity_row(); MAX_IDENTITY_IMPORT_ROWS + 1];
        assert!(
            client
                .customers()
                .import_identity_history(&request)
                .await
                .is_err()
        );
        assert_eq!(mock.seen.lock().unwrap().len(), 0);
    }

    #[tokio::test]
    async fn identity_search_sends_the_text_in_the_body_only() {
        let (client, mock) = client_with(vec![Step::ok(
            r#"{"entries":[{"id":"cih_1","customer_id":"cus_1","kind":"email",
                "value":"jane.doe@example.com","normalized_value":"jane.doe@example.com",
                "source":"import","source_label":"account","seen_count":1,
                "recorded_at":"2026-10-31T12:00:00.000Z"}],"truncated":true}"#,
        )]);
        let found = client
            .customers()
            .search_identity_history(&CustomerIdentityHistorySearchRequest {
                limit: Some(10),
                ..CustomerIdentityHistorySearchRequest::new("doe@exam")
            })
            .await
            .unwrap();
        assert_eq!(found.truncated, Some(true));
        assert_eq!(found.entries[0].customer_id, "cus_1");

        let seen = mock.seen.lock().unwrap();
        assert_eq!(
            seen[0].url,
            "https://api.test/customers/identity-history/search"
        );
        assert_eq!(seen[0].body_json()["query"], "doe@exam");
        assert_eq!(seen[0].body_json()["limit"], 10);
        assert!(
            seen[0].body_json().get("group_by_customer").is_none(),
            "the default answer sends no grouping"
        );
    }

    #[tokio::test]
    async fn identity_search_by_customer_sends_its_page_and_reads_the_customers() {
        let (client, mock) = client_with(vec![Step::ok(
            r#"{"entries":[],"truncated":false,"total_customers":3,"next_cursor":"6162",
                "customers":[{"customer_id":"cus_1","entries":[{"id":"cih_1","customer_id":"cus_1",
                "kind":"email","value":"jane.doe@example.com","normalized_value":"jane.doe@example.com",
                "source":"import","source_label":"account","seen_count":1,
                "recorded_at":"2026-10-31T12:00:00.000Z"}]}]}"#,
        )]);
        let page = client
            .customers()
            .search_identity_history(&CustomerIdentityHistorySearchRequest {
                group_by_customer: true,
                cursor: Some("5a5a".to_string()),
                limit: Some(1),
                ..CustomerIdentityHistorySearchRequest::new("doe@exam")
            })
            .await
            .unwrap();
        assert_eq!(page.total_customers, Some(3));
        assert_eq!(page.next_cursor.as_deref(), Some("6162"));
        let customers = page.customers.expect("customers");
        assert_eq!(customers[0].customer_id, "cus_1");
        assert_eq!(customers[0].entries.len(), 1);

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].body_json()["group_by_customer"], true);
        assert_eq!(seen[0].body_json()["cursor"], "5a5a");
    }

    #[tokio::test]
    async fn identity_search_refuses_a_limit_outside_one_to_a_hundred() {
        let (client, mock) = client_with(vec![]);
        for limit in [0, MAX_IDENTITY_SEARCH_RESULTS + 1] {
            let out = client
                .customers()
                .search_identity_history(&CustomerIdentityHistorySearchRequest {
                    limit: Some(limit),
                    ..CustomerIdentityHistorySearchRequest::new("doe")
                })
                .await;
            assert!(out.is_err(), "{limit}");
        }
        assert_eq!(mock.seen.lock().unwrap().len(), 0);
    }

    const PREVIEW_JSON: &str = r#"{"rows_total":1,"rows_accepted":1,"rows_unchanged":0,
        "rows_rejected":0,"customers_without_record":1,"rows_with_other_customers":1,
        "rows":[{"row_index":0,"external_ref":"u1-email-0","customer_id":"cus_1",
                 "kind":"email","outcome":"accepted","reason":null,"other_customers":2}]}"#;

    fn preview_of(rows: Vec<CustomerIdentityImportRow>) -> CustomerIdentityImportPreviewRequest {
        CustomerIdentityImportPreviewRequest { rows }
    }

    #[tokio::test]
    async fn identity_preview_reads_the_conflict_note_and_the_customers_without_record() {
        let (client, _mock) = client_with(vec![Step::ok(PREVIEW_JSON)]);
        let preview = client
            .customers()
            .preview_identity_import(&preview_of(vec![identity_row()]))
            .await
            .unwrap();
        assert_eq!(preview.customers_without_record, 1);
        assert_eq!(preview.rows_with_other_customers, 1);
        assert_eq!(preview.rows[0].other_customers, Some(2));
    }

    #[test]
    fn a_time_names_its_offset_only_with_z_or_a_signed_offset() {
        for value in [
            "2026-10-31T12:00:00Z",
            "2026-10-31T12:00:00.123z",
            "2026-10-31T12:00:00+01:00",
            "2026-10-31T12:00:00-05:30",
            "2026-10-31T12:00:00+0100",
        ] {
            assert!(names_its_offset(value), "{value}");
        }
        for value in [
            "2026-10-31T12:00:00",
            "2026-10-31",
            "2026-10-31T12:00:00+",
            "",
        ] {
            assert!(!names_its_offset(value), "{value}");
        }
    }

    #[tokio::test]
    async fn identity_import_refuses_a_time_without_its_offset_without_sending() {
        let (client, mock) = client_with(vec![Step::ok(PREVIEW_JSON)]);
        for (first, last) in [
            (Some("2026-10-31T12:00:00"), None),
            (None, Some("2026-10-31")),
        ] {
            let mut row = identity_row();
            row.first_seen_at = first.map(str::to_owned);
            row.last_seen_at = last.map(str::to_owned);
            let out = client
                .customers()
                .preview_identity_import(&preview_of(vec![identity_row(), row.clone()]))
                .await;
            assert!(
                matches!(out, Err(DelopayError::InvalidRequest(ref message)) if message.contains("rows[1]")),
                "{out:?}"
            );
            let out = client
                .customers()
                .import_identity_history(&CustomerIdentityImportRequest {
                    idempotency_key: "af-0001".to_owned(),
                    rows: vec![row],
                })
                .await;
            assert!(matches!(out, Err(DelopayError::InvalidRequest(_))));
        }
        assert_eq!(mock.seen.lock().unwrap().len(), 0);

        let mut dated = identity_row();
        dated.first_seen_at = Some("2026-10-31T12:00:00Z".to_owned());
        dated.last_seen_at = Some("2026-11-01T08:00:00+01:00".to_owned());
        client
            .customers()
            .preview_identity_import(&preview_of(vec![dated]))
            .await
            .unwrap();
        assert_eq!(
            mock.seen.lock().unwrap()[0].body_json()["rows"][0]["first_seen_at"],
            "2026-10-31T12:00:00Z"
        );
    }

    #[tokio::test]
    async fn identity_import_refuses_a_body_over_its_limit_without_sending() {
        let (client, mock) = client_with(vec![Step::ok(PREVIEW_JSON)]);
        let mut row = identity_row();
        row.value = "x".repeat(7300);
        let over = vec![row.clone(); MAX_IDENTITY_IMPORT_ROWS];
        let out = client
            .customers()
            .preview_identity_import(&preview_of(over.clone()))
            .await;
        assert!(
            matches!(out, Err(DelopayError::InvalidRequest(_))),
            "{out:?}"
        );
        let out = client
            .customers()
            .import_identity_history(&CustomerIdentityImportRequest {
                idempotency_key: "af-0001".to_owned(),
                rows: over,
            })
            .await;
        assert!(
            matches!(out, Err(DelopayError::InvalidRequest(_))),
            "{out:?}"
        );
        assert_eq!(mock.seen.lock().unwrap().len(), 0);

        row.value = "x".repeat(7000);
        client
            .customers()
            .preview_identity_import(&preview_of(vec![row; MAX_IDENTITY_IMPORT_ROWS]))
            .await
            .unwrap();
        assert_eq!(mock.seen.lock().unwrap().len(), 1);
    }

    #[tokio::test]
    async fn identity_list_refuses_a_body_over_its_limit_without_sending() {
        let (client, mock) = client_with(vec![Step::ok(r#"{"entries":[]}"#)]);
        let out = client
            .customers()
            .list_identity_history(&CustomerIdentityHistoryRequest {
                customer_ids: vec!["c".repeat(140); MAX_IDENTITY_CUSTOMERS],
            })
            .await;
        assert!(
            matches!(out, Err(DelopayError::InvalidRequest(_))),
            "{out:?}"
        );
        assert_eq!(mock.seen.lock().unwrap().len(), 0);
        client
            .customers()
            .list_identity_history(&CustomerIdentityHistoryRequest {
                customer_ids: vec!["c".repeat(64); MAX_IDENTITY_CUSTOMERS],
            })
            .await
            .unwrap();
        assert_eq!(mock.seen.lock().unwrap().len(), 1);
    }

    #[tokio::test]
    async fn identity_search_refuses_a_long_query_and_a_cursor_without_grouping() {
        let (client, mock) = client_with(vec![Step::ok(r#"{"entries":[]}"#)]);
        let long = CustomerIdentityHistorySearchRequest::new(
            "q".repeat(MAX_IDENTITY_SEARCH_QUERY_CHARS + 1),
        );
        assert!(matches!(
            client.customers().search_identity_history(&long).await,
            Err(DelopayError::InvalidRequest(_))
        ));
        let ungrouped = CustomerIdentityHistorySearchRequest {
            cursor: Some("c1".to_owned()),
            ..CustomerIdentityHistorySearchRequest::new("doe")
        };
        assert!(matches!(
            client.customers().search_identity_history(&ungrouped).await,
            Err(DelopayError::InvalidRequest(_))
        ));
        assert_eq!(mock.seen.lock().unwrap().len(), 0);
        client
            .customers()
            .search_identity_history(&CustomerIdentityHistorySearchRequest::new(
                "ü".repeat(MAX_IDENTITY_SEARCH_QUERY_CHARS),
            ))
            .await
            .unwrap();
        assert_eq!(mock.seen.lock().unwrap().len(), 1);
    }

    #[tokio::test]
    async fn identity_readback_encodes_the_run_id_and_reads_the_entries() {
        let readback =
            IMPORT_JSON.trim_end().trim_end_matches('}').to_string() + r#","entries":[]}"#;
        let (client, mock) = client_with(vec![Step::ok(&readback)]);
        let run = client
            .customers()
            .retrieve_identity_import("cir/1")
            .await
            .unwrap();
        assert_eq!(run.entries.map(|e| e.len()), Some(0));
        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "GET");
        assert_eq!(
            seen[0].url,
            "https://api.test/customers/identity-history/import/cir%2F1"
        );
    }

    #[tokio::test]
    async fn identity_list_refuses_no_customers_without_sending() {
        let (client, mock) = client_with(vec![]);
        let out = client
            .customers()
            .list_identity_history(&CustomerIdentityHistoryRequest {
                customer_ids: vec![],
            })
            .await;
        assert!(out.is_err());
        assert_eq!(mock.seen.lock().unwrap().len(), 0);
    }

    #[test]
    fn identity_values_never_reach_debug() {
        let row = format!("{:?}", identity_row());
        assert!(!row.contains("jane.doe"), "{row}");
        let search = format!(
            "{:?}",
            CustomerIdentityHistorySearchRequest::new("secret-needle")
        );
        assert!(!search.contains("secret-needle"), "{search}");
        let entry: crate::core::models::customer_identity::CustomerIdentityEntry =
            serde_json::from_str(
                r#"{"id":"cih_1","customer_id":"cus_1","kind":"email",
                    "value":"jane.doe@example.com","normalized_value":"jane.doe@example.com",
                    "source":"import","source_label":"account","seen_count":1,
                    "recorded_at":"2026-10-31T12:00:00.000Z"}"#,
            )
            .unwrap();
        let entry = format!("{entry:?}");
        assert!(!entry.contains("jane.doe"), "{entry}");
    }

    #[test]
    fn an_unknown_import_outcome_still_decodes() {
        let row: crate::core::models::customer_identity::CustomerIdentityImportRowResult =
            serde_json::from_str(r#"{"row_index":0,"external_ref":"x","outcome":"merged"}"#)
                .unwrap();
        assert_eq!(row.outcome, CustomerIdentityImportOutcome::Unknown);
    }

    /// Every optional field populated so serialization emits the full key set.
    fn full_customer_create_request() -> CustomerCreateRequest {
        CustomerCreateRequest {
            customer_id: Some("cus_1".to_string()),
            name: Some("Ada Lovelace".to_string()),
            email: Some("ada@example.com".to_string()),
            phone: Some("5551234".to_string()),
            phone_country_code: Some("+44".to_string()),
            description: Some("VIP customer".to_string()),
            address: Some(json!({"country": "GB"})),
            metadata: Some(json!({"tier": "gold"})),
            profile_id: Some("pro_1".to_string()),
            extra: serde_json::Map::new(),
        }
    }

    /// Drift guard: catches a new field added to `CustomerCreateRequest`
    /// without a matching update to `CUSTOMER_CREATE_REQUEST_NAMED`.
    #[test]
    fn customer_create_request_named_fields_are_complete() {
        let value = serde_json::to_value(full_customer_create_request()).unwrap();
        let obj = value.as_object().expect("serializes to a JSON object");
        for key in obj.keys() {
            assert!(
                CUSTOMER_CREATE_REQUEST_NAMED.contains(&key.as_str()),
                "CUSTOMER_CREATE_REQUEST_NAMED is missing wire key `{key}` -- \
                 add it, or CustomerCreateRequest's extra-key collision guard \
                 will silently stop covering this field"
            );
        }
    }

    #[test]
    fn validate_rejects_extra_key_colliding_with_named_field() {
        let mut req = CustomerCreateRequest::new().email("ada@example.com");
        req.extra.insert("name".to_string(), json!("collide"));

        let err = req.validate().unwrap_err();
        match err {
            DelopayError::InvalidRequest(msg) => assert!(msg.contains("name")),
            other => panic!("expected InvalidRequest, got {other:?}"),
        }
    }

    #[tokio::test]
    async fn list_serializes_shop_filters() {
        let (client, mock) = client_with(vec![Step::ok("[]")]);
        let params = CustomerListParams {
            limit: Some(10),
            profile_id: Some("pro_1".to_string()),
            ..Default::default()
        };
        client.customers().list(Some(&params)).await.unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(
            seen[0].url,
            "https://api.test/customers/list?limit=10&profile_id=pro_1"
        );
    }

    /// `profile_ids` must go out as ONE comma-separated value. Repeated keys
    /// (`?profile_ids=a&profile_ids=b`) fail the whole request server-side
    /// rather than dropping the second id, so a mutation pushing one pair per
    /// id must be caught here.
    #[tokio::test]
    async fn list_sends_profile_ids_as_one_comma_separated_value() {
        let (client, mock) = client_with(vec![Step::ok("[]")]);
        let params = CustomerListParams::default().profile_ids(["pro_1", "pro_2"]);
        client.customers().list(Some(&params)).await.unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(
            seen[0].url,
            "https://api.test/customers/list?profile_ids=pro_1,pro_2"
        );
    }

    /// An empty list means "no shop filter", which is the absent key — not an
    /// empty `profile_ids=` the server would have to interpret.
    #[tokio::test]
    async fn list_omits_an_empty_profile_ids_filter() {
        let (client, mock) = client_with(vec![Step::ok("[]")]);
        let params = CustomerListParams::default().profile_ids(Vec::<String>::new());
        client.customers().list(Some(&params)).await.unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].url, "https://api.test/customers/list");
    }

    #[tokio::test]
    async fn list_with_count_hits_its_path_and_reads_the_total() {
        let (client, mock) = client_with(vec![
            Step::ok(r#"{"total_count":9,"data":[{"customer_id":"cus_1"}]}"#),
            Step::ok(r#"{"total_count":0,"data":[]}"#),
        ]);
        let customers = client.customers();
        let out = customers.list_with_count(None).await.unwrap();
        assert_eq!(out.total_count, Some(9));
        assert_eq!(out.data.len(), 1);
        let params = CustomerListParams {
            customer_id: Some("cus_1".to_string()),
            search: Some("ada".to_string()),
            start_time: Some("2026-01-01T00:00:00Z".to_string()),
            end_time: Some("2026-02-01T00:00:00Z".to_string()),
            ..Default::default()
        };
        customers.list_with_count(Some(&params)).await.unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "GET");
        assert_eq!(seen[0].url, "https://api.test/customers/list-with-count");
        assert_eq!(
            seen[1].url,
            "https://api.test/customers/list-with-count?customer_id=cus_1&search=ada\
             &start_time=2026-01-01T00:00:00Z&end_time=2026-02-01T00:00:00Z"
        );
    }

    #[tokio::test]
    async fn every_customer_list_sends_the_exact_email_filter() {
        let (client, mock) = client_with(vec![
            Step::ok("[]"),
            Step::ok(r#"{"total_count":1,"data":[]}"#),
            Step::ok("[]"),
            Step::ok(r#"{"total_count":1,"data":[]}"#),
        ]);
        let params = CustomerListParams {
            email: Some("jane@example.com".to_string()),
            ..Default::default()
        };
        let customers = client.customers();
        customers.list(Some(&params)).await.unwrap();
        customers.list_with_count(Some(&params)).await.unwrap();
        customers.list_by_profile(Some(&params)).await.unwrap();
        customers
            .list_by_profile_with_count(Some(&params))
            .await
            .unwrap();

        let seen = mock.seen.lock().unwrap();
        let urls: Vec<&str> = seen.iter().map(|call| call.url.as_str()).collect();
        assert_eq!(
            urls,
            [
                "https://api.test/customers/list?email=jane@example.com",
                "https://api.test/customers/list-with-count?email=jane@example.com",
                "https://api.test/customers/profile/list?email=jane@example.com",
                "https://api.test/customers/profile/list-with-count?email=jane@example.com",
            ]
        );
    }

    #[tokio::test]
    async fn profile_scoped_lists_hit_the_profile_paths() {
        // These differ from `list` / `list_with_count` ONLY by path segment;
        // a mutation dropping `/profile` must fail here.
        let (client, mock) = client_with(vec![
            Step::ok("[]"),
            Step::ok(r#"{"total_count":9,"data":[]}"#),
        ]);
        let params = CustomerListParams {
            limit: Some(10),
            search: Some("ada".to_string()),
            ..Default::default()
        };
        client
            .customers()
            .list_by_profile(Some(&params))
            .await
            .unwrap();
        let out = client
            .customers()
            .list_by_profile_with_count(None)
            .await
            .unwrap();
        assert_eq!(out.total_count, Some(9));

        let seen = mock.seen.lock().unwrap();
        assert_eq!(
            (seen[0].method, seen[0].url.as_str()),
            (
                "GET",
                "https://api.test/customers/profile/list?limit=10&search=ada"
            )
        );
        assert_eq!(
            (seen[1].method, seen[1].url.as_str()),
            ("GET", "https://api.test/customers/profile/list-with-count")
        );
    }

    #[tokio::test]
    async fn list_mandates_gets_the_customer_mandates_path() {
        let (client, mock) = client_with(vec![Step::ok(
            r#"[{"mandate_id":"man_1","status":"active"}]"#,
        )]);
        let out = client.customers().list_mandates("cus_1").await.unwrap();
        assert_eq!(out[0].mandate_id, "man_1");

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "GET");
        assert_eq!(seen[0].url, "https://api.test/customers/cus_1/mandates");
    }

    /// A portal link create or revoke never carries an idempotency key, not even the
    /// client-wide one, so a 5xx is not replayed. Mutation: switch a call
    /// site back to `request(.., None)` — the header appears and the call
    /// count grows.
    #[tokio::test]
    async fn portal_link_writes_ignore_the_client_wide_idempotency_key() {
        let (client, mock) = client_with_retries(
            vec![
                Step::status(503, "{}"),
                Step::status(503, "{}"),
                Step::ok(""),
            ],
            2,
        );
        let customers = client.with_idempotency_key("client-key").customers();
        assert!(
            customers
                .create_portal_link("cus_1", &BuyerInvoiceLinkRequest::new())
                .await
                .is_err()
        );
        assert!(
            customers
                .revoke_portal_link("cus_1", "bpl_1")
                .await
                .is_err()
        );
        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen.len(), 2);
        assert!(seen.iter().all(|step| !step.had_idempotency_key()));
    }
}