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
//! The `buyer_account` resource: a buyer signs in with their email address,
//! by a code or a link mailed to it, and sees their purchases across shops.
//!
//! Starting and completing a sign-in need no credential: a client built with
//! an empty key sends none. Everything after it needs the buyer account
//! session, sent in the `api-key` header: build a separate client with the
//! session `token` as its key. A customer portal grant is not a buyer account
//! session, and neither is a merchant secret key or a dashboard JWT.
//!
//! ```no_run
//! # use delopay::{BuyerAccountVerifyCodeRequest, Delopay};
//! # async fn run(email: &str, code: &str) -> delopay::Result<()> {
//! let anonymous = Delopay::new("");
//! let session = anonymous
//!     .buyer_account()
//!     .verify_code(&BuyerAccountVerifyCodeRequest::new(email, code))
//!     .await?;
//! let buyer = Delopay::new(session.token.as_str());
//! let purchases = buyer.buyer_account().list_purchases(None).await?;
//! # let _ = purchases;
//! # Ok(())
//! # }
//! ```
//!
//! Records are the buyer's customer records at a shop. A record's cases,
//! invoices, refund requests and conversations show once the buyer has
//! confirmed it through the shop's own portal link, with
//! [`BuyerAccount::confirm`].

use std::sync::Arc;

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

use crate::core::encoding::{encode_segment, to_json_vec};
use crate::core::error::Result;
use crate::core::models::buyer_account::{
    BuyerAccountAvailability, BuyerAccountConfirmation, BuyerAccountInvoiceList,
    BuyerAccountPortal, BuyerAccountPurchasePage, BuyerAccountRefundRequestList,
    BuyerAccountSession, BuyerAccountSessionInfo, BuyerAccountShopList, BuyerAccountSignInResponse,
    BuyerAccountSubscriptionList, BuyerNoticeSettings,
};
use crate::core::models::buyer_case::{
    BuyerCaseList, BuyerEvidence, BuyerEvidenceEntry, BuyerEvidenceFile,
};
use crate::core::models::buyer_conversation::{
    BuyerConversationAttachment, BuyerPortalConversationList, BuyerPortalMessage,
    BuyerPortalMessagePage,
};
use crate::http::client::Inner;
use crate::http::transport::HttpMethod;
use crate::resources::ValidateRequest;
use crate::resources::buyer_portal::{
    ANY_FILE, BuyerAttachmentParams, BuyerConversationParams, BuyerEvidenceExtensionRequest,
    BuyerEvidenceSubmitRequest, BuyerFileUpload, BuyerMessageCreateRequest, check_extra,
    delete_ignoring_body,
};

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

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

    /// Whether buyers can sign in on this platform, and which methods are
    /// offered. Needs no credential. `GET /buyer-account/availability`
    pub async fn availability(&self) -> Result<BuyerAccountAvailability> {
        self.get("/buyer-account/availability", &[]).await
    }

    /// Mail a sign-in code, a link, or both to the address, as the platform
    /// offers. The answer is the same whether or not the address has
    /// purchases. Needs no credential. `POST /buyer-account/sign-in`
    pub async fn start_sign_in(
        &self,
        params: &BuyerAccountSignInRequest,
    ) -> Result<BuyerAccountSignInResponse> {
        params.validate()?;
        self.post("/buyer-account/sign-in", params).await
    }

    /// Complete a sign-in with the code from the message. Needs no
    /// credential. `POST /buyer-account/sign-in/code`
    pub async fn verify_code(
        &self,
        params: &BuyerAccountVerifyCodeRequest,
    ) -> Result<BuyerAccountSession> {
        params.validate()?;
        self.post("/buyer-account/sign-in/code", params).await
    }

    /// Complete a sign-in with the token of the link in the message. Needs no
    /// credential. `POST /buyer-account/sign-in/link`
    pub async fn verify_link(
        &self,
        params: &BuyerAccountVerifyLinkRequest,
    ) -> Result<BuyerAccountSession> {
        self.post("/buyer-account/sign-in/link", params).await
    }

    /// The current session: the address signed in with, masked, and its
    /// expiry. `GET /buyer-account/session`
    pub async fn get_session(&self) -> Result<BuyerAccountSessionInfo> {
        self.get("/buyer-account/session", &[]).await
    }

    /// End the current session. `DELETE /buyer-account/session`
    pub async fn sign_out(&self) -> Result<()> {
        delete_ignoring_body(&self.inner, "/buyer-account/session", &[]).await
    }

    /// What the buyer is mailed about: a reply from a shop's team they have
    /// not read, and news in their refund requests and disputes.
    /// `GET /buyer-account/notice-settings`
    pub async fn notice_settings(&self) -> Result<BuyerNoticeSettings> {
        self.get("/buyer-account/notice-settings", &[]).await
    }

    /// Turn either mail on or off for the buyer, at every shop.
    /// `PUT /buyer-account/notice-settings`
    pub async fn set_notice_settings(
        &self,
        params: &BuyerNoticeSettingsRequest,
    ) -> Result<BuyerNoticeSettings> {
        let body = to_json_vec(params)?;
        self.inner
            .request_body_keyed_with_query(
                HttpMethod::Put,
                "/buyer-account/notice-settings",
                Some(&body),
                &[],
                None,
            )
            .await
    }

    /// The buyer's purchases across shops, newest first, as receipts: shop,
    /// date, amount, items and status. Page with `next_cursor`.
    /// `GET /buyer-account/purchases`
    pub async fn list_purchases(
        &self,
        params: Option<&BuyerAccountPurchaseParams>,
    ) -> Result<BuyerAccountPurchasePage> {
        let query = params.map(BuyerAccountPurchaseParams::to_query);
        self.get("/buyer-account/purchases", query.as_deref().unwrap_or(&[]))
            .await
    }

    /// The shops the buyer has purchases at, once each and by name. Pass a
    /// shop's `shop` to [`list_purchases`](Self::list_purchases) to list only
    /// that shop's purchases. `GET /buyer-account/shops`
    pub async fn list_shops(&self) -> Result<BuyerAccountShopList> {
        self.get("/buyer-account/shops", &[]).await
    }

    /// The buyer's subscriptions across shops, newest first. Follow
    /// `next_cursor` with the same shop and mode; an omitted mode includes
    /// both modes. `GET /buyer-account/subscriptions`
    pub async fn list_subscriptions(
        &self,
        params: Option<&BuyerAccountSectionParams>,
    ) -> Result<BuyerAccountSubscriptionList> {
        let query = params.map(BuyerAccountSectionParams::to_query);
        self.get(
            "/buyer-account/subscriptions",
            query.as_deref().unwrap_or(&[]),
        )
        .await
    }

    /// The issued invoices of the records the buyer has confirmed, newest
    /// first. `unconfirmed_records` says when records were left out. Follow
    /// `next_cursor` with the same shop and mode; an omitted mode includes
    /// both modes. `GET /buyer-account/invoices`
    pub async fn list_invoices(
        &self,
        params: Option<&BuyerAccountSectionParams>,
    ) -> Result<BuyerAccountInvoiceList> {
        let query = params.map(BuyerAccountSectionParams::to_query);
        self.get("/buyer-account/invoices", query.as_deref().unwrap_or(&[]))
            .await
    }

    /// The confirmed records' refund requests, newest first, with the shop's
    /// decision. Follow `next_cursor` with the same shop and mode; an omitted
    /// mode includes both modes. `GET /buyer-account/refund-requests`
    pub async fn list_refund_requests(
        &self,
        params: Option<&BuyerAccountSectionParams>,
    ) -> Result<BuyerAccountRefundRequestList> {
        let query = params.map(BuyerAccountSectionParams::to_query);
        self.get(
            "/buyer-account/refund-requests",
            query.as_deref().unwrap_or(&[]),
        )
        .await
    }

    /// The cases of the records the buyer has confirmed: the refund requests
    /// they sent and the disputes about their purchases, newest first, with
    /// where each stands, who acts next, the outcome and the recorded steps.
    /// `shop` narrows them to one shop. `GET /buyer-account/cases`
    pub async fn list_cases(&self, shop: Option<&str>) -> Result<BuyerCaseList> {
        self.get("/buyer-account/cases", &shop_query(shop)).await
    }

    /// The conversations of the records the buyer has confirmed, the latest
    /// message first. `unconfirmed_records` says when other records were left
    /// out. `shop` narrows them to one shop. `GET /buyer-account/conversations`
    pub async fn list_conversations(
        &self,
        shop: Option<&str>,
    ) -> Result<BuyerPortalConversationList> {
        self.get("/buyer-account/conversations", &shop_query(shop))
            .await
    }

    /// The conversation of a confirmed record with one shop, and its newest
    /// messages, oldest first; `before` pages back. `shop` is required here.
    /// `GET /buyer-account/records/{record}/messages`
    pub async fn list_record_messages(
        &self,
        record: &str,
        params: &BuyerConversationParams,
    ) -> Result<BuyerPortalMessagePage> {
        let path = format!("{}/messages", record_path(record));
        self.get(&path, &params.to_query()).await
    }

    /// A message from a confirmed record to one of its shops. A message to a
    /// closed conversation reopens it. Sending again with the same
    /// `client_message_id` returns the message the first send stored.
    /// `POST /buyer-account/records/{record}/messages`
    pub async fn send_record_message(
        &self,
        record: &str,
        params: &BuyerMessageCreateRequest,
    ) -> Result<BuyerPortalMessage> {
        params.validate()?;
        let path = format!("{}/messages", record_path(record));
        self.post(&path, params).await
    }

    /// The buyer has read a record's conversation with one shop up to its
    /// last accepted message. Answers with the buyer's conversations as they
    /// now stand. `POST /buyer-account/records/{record}/messages/read`
    pub async fn mark_record_messages_read(
        &self,
        record: &str,
        params: &BuyerConversationParams,
    ) -> Result<BuyerPortalConversationList> {
        let path = format!("{}/messages/read", record_path(record));
        self.inner
            .request_body_keyed_with_query(HttpMethod::Post, &path, None, &params.to_query(), None)
            .await
    }

    /// Upload a file for the buyer's next message to one shop of a confirmed
    /// record, under the shop's attachment rules (`attachment_rules` on the
    /// message page). It belongs to the buyer until a message names it in
    /// `attachments`; one no message took within a day is cleared. Uploading
    /// again with the same `client_upload_id` returns the file the first
    /// upload stored. `shop` is required here.
    /// `POST /buyer-account/records/{record}/messages/files`
    pub async fn upload_record_message_file(
        &self,
        record: &str,
        upload: &BuyerFileUpload<'_>,
        params: &BuyerAttachmentParams,
    ) -> Result<BuyerConversationAttachment> {
        let path = format!("{}/messages/files", record_path(record));
        let form = upload.encode();
        self.inner
            .request_with_content_type_and_query(
                HttpMethod::Post,
                &path,
                &params.to_query(),
                &form.body,
                &form.content_type,
            )
            .await
    }

    /// Download a file a message of a record's conversation with one shop
    /// carries, as its bytes.
    /// `GET /buyer-account/records/{record}/messages/files/{file}`
    pub async fn download_record_message_file(
        &self,
        record: &str,
        file_id: &str,
        params: &BuyerAttachmentParams,
    ) -> Result<Vec<u8>> {
        let path = format!(
            "{}/messages/files/{}",
            record_path(record),
            encode_segment(file_id)
        );
        self.inner
            .request_bytes(HttpMethod::Get, &path, &params.to_query(), ANY_FILE)
            .await
    }

    /// Remove a file the buyer uploaded for a record's conversation that no
    /// message took. `DELETE /buyer-account/records/{record}/messages/files/{file}`
    pub async fn remove_record_message_file(
        &self,
        record: &str,
        file_id: &str,
        params: &BuyerAttachmentParams,
    ) -> Result<()> {
        let path = format!(
            "{}/messages/files/{}",
            record_path(record),
            encode_segment(file_id)
        );
        delete_ignoring_body(&self.inner, &path, &params.to_query()).await
    }

    /// Confirm the record of a shop's customer portal link for the signed-in
    /// buyer. The link's customer must carry the address the buyer signed in
    /// with. `POST /buyer-account/confirmations`
    pub async fn confirm(
        &self,
        params: &BuyerAccountConfirmRequest,
    ) -> Result<BuyerAccountConfirmation> {
        self.post("/buyer-account/confirmations", params).await
    }

    /// Open the shop's customer portal for a confirmed record, named by the
    /// `record` its purchases carry. Opening another one for the same record
    /// ends the previous one. `POST /buyer-account/records/{record}/portal`
    pub async fn open_portal(&self, record: &str) -> Result<BuyerAccountPortal> {
        let path = format!("{}/portal", record_path(record));
        self.inner
            .request_body_keyed_with_query(HttpMethod::Post, &path, None, &[], None)
            .await
    }

    /// A case's evidence: what may be handed in and by when, the files saved
    /// and handed in, and what the reviewer said. Opened on the first read
    /// while the case still waits. The case is one of a confirmed record's,
    /// named by the `record` its purchases carry and the case id the case list
    /// shows. `GET /buyer-account/records/{record}/cases/{case}/evidence`
    pub async fn case_evidence(&self, record: &str, case_id: &str) -> Result<BuyerEvidence> {
        self.get(&evidence_path(record, case_id), &[]).await
    }

    /// Upload a file for a case. It is saved, not handed in, until a
    /// submission takes it. Uploading again with the same `client_upload_id`
    /// returns the file the first upload stored, also after the cut-off.
    /// `POST /buyer-account/records/{record}/cases/{case}/evidence/files`
    pub async fn upload_evidence_file(
        &self,
        record: &str,
        case_id: &str,
        upload: &BuyerFileUpload<'_>,
    ) -> Result<BuyerEvidenceFile> {
        let path = format!("{}/files", evidence_path(record, case_id));
        let form = upload.encode();
        self.inner
            .request_with_content_type_and_query(
                HttpMethod::Post,
                &path,
                &[],
                &form.body,
                &form.content_type,
            )
            .await
    }

    /// Download a file of the case's evidence, as its bytes.
    /// `GET /buyer-account/records/{record}/cases/{case}/evidence/files/{file}`
    pub async fn download_evidence_file(
        &self,
        record: &str,
        case_id: &str,
        file_id: &str,
    ) -> Result<Vec<u8>> {
        let path = format!(
            "{}/files/{}",
            evidence_path(record, case_id),
            encode_segment(file_id)
        );
        self.inner
            .request_bytes(HttpMethod::Get, &path, &[], ANY_FILE)
            .await
    }

    /// Remove a saved file. A file a submission took stays.
    /// `DELETE /buyer-account/records/{record}/cases/{case}/evidence/files/{file}`
    pub async fn remove_evidence_file(
        &self,
        record: &str,
        case_id: &str,
        file_id: &str,
    ) -> Result<()> {
        let path = format!(
            "{}/files/{}",
            evidence_path(record, case_id),
            encode_segment(file_id)
        );
        delete_ignoring_body(&self.inner, &path, &[]).await
    }

    /// Hand in an explanation, saved files or both, while the buyer's window
    /// is open. Sending again with the same `client_submission_id` returns
    /// the submission the first send stored.
    /// `POST /buyer-account/records/{record}/cases/{case}/evidence/submissions`
    pub async fn submit_evidence(
        &self,
        record: &str,
        case_id: &str,
        params: &BuyerEvidenceSubmitRequest,
    ) -> Result<BuyerEvidenceEntry> {
        params.validate()?;
        let path = format!("{}/submissions", evidence_path(record, case_id));
        self.post(&path, params).await
    }

    /// Ask for more time, once until the cut-off is next set.
    /// `POST /buyer-account/records/{record}/cases/{case}/evidence/extension-requests`
    pub async fn request_evidence_extension(
        &self,
        record: &str,
        case_id: &str,
        params: &BuyerEvidenceExtensionRequest,
    ) -> Result<BuyerEvidenceEntry> {
        let path = format!("{}/extension-requests", evidence_path(record, case_id));
        self.post(&path, params).await
    }

    async fn get<T: serde::de::DeserializeOwned>(
        &self,
        path: &str,
        query: &[(&str, String)],
    ) -> Result<T> {
        self.inner
            .request(HttpMethod::Get, path, None, query, None)
            .await
    }

    async fn post<B: Serialize, T: serde::de::DeserializeOwned>(
        &self,
        path: &str,
        body: &B,
    ) -> Result<T> {
        let body = to_json_vec(body)?;
        self.inner
            .request_body_keyed_with_query(HttpMethod::Post, path, Some(&body), &[], None)
            .await
    }
}

fn record_path(record: &str) -> String {
    format!("/buyer-account/records/{}", encode_segment(record))
}

fn evidence_path(record: &str, case_id: &str) -> String {
    format!(
        "{}/cases/{}/evidence",
        record_path(record),
        encode_segment(case_id)
    )
}

fn shop_query(shop: Option<&str>) -> Vec<(&'static str, String)> {
    shop.map(|s| vec![("shop", s.to_string())])
        .unwrap_or_default()
}

/// Body of [`BuyerAccount::start_sign_in`].
#[derive(Clone, Default, Serialize)]
pub struct BuyerAccountSignInRequest {
    /// The buyer's email address.
    pub email: String,
    /// The language to write the message in, such as `de`. English when
    /// absent or not offered.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub locale: Option<String>,
    /// Any additional fields, merged verbatim.
    #[serde(flatten, skip_serializing_if = "serde_json::Map::is_empty")]
    pub extra: serde_json::Map<String, Value>,
}

impl BuyerAccountSignInRequest {
    /// A sign-in for `email`.
    pub fn new(email: impl Into<String>) -> Self {
        Self {
            email: email.into(),
            ..Default::default()
        }
    }

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

// Hand-written: the address is personal data.
impl std::fmt::Debug for BuyerAccountSignInRequest {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("BuyerAccountSignInRequest")
            .field("email", &"<redacted>")
            .field("locale", &self.locale)
            .finish_non_exhaustive()
    }
}

/// Names of `BuyerAccountSignInRequest`'s fields as they appear on the wire
/// (`extra` excluded).
const BUYER_ACCOUNT_SIGN_IN_REQUEST_NAMED: &[&str] = &["email", "locale"];

impl ValidateRequest for BuyerAccountSignInRequest {
    fn validate(&self) -> Result<()> {
        check_extra(
            &self.extra,
            BUYER_ACCOUNT_SIGN_IN_REQUEST_NAMED,
            "BuyerAccountSignInRequest",
        )
    }
}

/// Body of [`BuyerAccount::verify_code`].
#[derive(Clone, Default, Serialize)]
pub struct BuyerAccountVerifyCodeRequest {
    /// The address the code was mailed to.
    pub email: String,
    /// The code from the message.
    pub code: String,
    /// Any additional fields, merged verbatim.
    #[serde(flatten, skip_serializing_if = "serde_json::Map::is_empty")]
    pub extra: serde_json::Map<String, Value>,
}

impl BuyerAccountVerifyCodeRequest {
    /// Complete the sign-in of `email` with `code`.
    pub fn new(email: impl Into<String>, code: impl Into<String>) -> Self {
        Self {
            email: email.into(),
            code: code.into(),
            extra: serde_json::Map::new(),
        }
    }
}

// Hand-written: the address is personal data and the code a credential.
impl std::fmt::Debug for BuyerAccountVerifyCodeRequest {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("BuyerAccountVerifyCodeRequest")
            .field("email", &"<redacted>")
            .field("code", &"<redacted>")
            .finish_non_exhaustive()
    }
}

/// Names of `BuyerAccountVerifyCodeRequest`'s fields as they appear on the
/// wire (`extra` excluded).
const BUYER_ACCOUNT_VERIFY_CODE_REQUEST_NAMED: &[&str] = &["email", "code"];

impl ValidateRequest for BuyerAccountVerifyCodeRequest {
    fn validate(&self) -> Result<()> {
        check_extra(
            &self.extra,
            BUYER_ACCOUNT_VERIFY_CODE_REQUEST_NAMED,
            "BuyerAccountVerifyCodeRequest",
        )
    }
}

/// Body of [`BuyerAccount::verify_link`].
#[derive(Clone, Serialize)]
pub struct BuyerAccountVerifyLinkRequest {
    /// The token of the link in the message.
    pub token: String,
}

impl BuyerAccountVerifyLinkRequest {
    /// Complete a sign-in with the link's `token`.
    pub fn new(token: impl Into<String>) -> Self {
        Self {
            token: token.into(),
        }
    }
}

// Hand-written: the token signs the buyer in.
impl std::fmt::Debug for BuyerAccountVerifyLinkRequest {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("BuyerAccountVerifyLinkRequest")
            .field("token", &"<redacted>")
            .finish()
    }
}

/// Body of [`BuyerAccount::set_notice_settings`]: both mails, on or off.
#[derive(Debug, Clone, Copy, Serialize)]
pub struct BuyerNoticeSettingsRequest {
    /// Mail the buyer about a reply from a shop's team they have not read.
    pub replies: bool,
    /// Mail the buyer about news in their refund requests and disputes.
    pub case_updates: bool,
}

impl BuyerNoticeSettingsRequest {
    /// Turn each mail on or off.
    pub fn new(replies: bool, case_updates: bool) -> Self {
        Self {
            replies,
            case_updates,
        }
    }
}

/// Body of [`BuyerAccount::confirm`].
#[derive(Clone, Serialize)]
pub struct BuyerAccountConfirmRequest {
    /// The token of the shop's customer portal link.
    pub portal_token: String,
}

impl BuyerAccountConfirmRequest {
    /// Confirm the record of the portal link carrying `portal_token`.
    pub fn new(portal_token: impl Into<String>) -> Self {
        Self {
            portal_token: portal_token.into(),
        }
    }
}

// Hand-written: the portal token opens the shop's portal.
impl std::fmt::Debug for BuyerAccountConfirmRequest {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("BuyerAccountConfirmRequest")
            .field("portal_token", &"<redacted>")
            .finish()
    }
}

/// Paging and shop filter for [`BuyerAccount::list_purchases`].
#[derive(Debug, Clone, Default)]
pub struct BuyerAccountPurchaseParams {
    /// The most purchases to return.
    pub limit: Option<i64>,
    /// The previous page's `next_cursor`.
    pub cursor: Option<String>,
    /// Only this shop's purchases, as [`BuyerAccount::list_shops`] names it.
    pub shop: Option<String>,
}

impl BuyerAccountPurchaseParams {
    /// No filter; set the ones you want.
    pub fn new() -> Self {
        Self::default()
    }

    /// The most purchases to return.
    #[must_use]
    pub fn limit(mut self, limit: i64) -> Self {
        self.limit = Some(limit);
        self
    }

    /// Continue after the previous page.
    #[must_use]
    pub fn cursor(mut self, cursor: impl Into<String>) -> Self {
        self.cursor = Some(cursor.into());
        self
    }

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

    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.cursor {
            q.push(("cursor", v.clone()));
        }
        if let Some(v) = &self.shop {
            q.push(("shop", v.clone()));
        }
        q
    }
}

/// Paging, shop and mode filter for the subscription, invoice and refund
/// request lists of [`BuyerAccount`].
#[derive(Debug, Clone, Default)]
pub struct BuyerAccountSectionParams {
    /// Only this shop's items.
    pub shop: Option<String>,
    /// The previous page's `next_cursor`, followed with the same shop and
    /// mode.
    pub cursor: Option<String>,
    /// The most items to return.
    pub limit: Option<i64>,
    /// Only test-mode (`true`) or live (`false`) items. Both when unset.
    pub test_mode: Option<bool>,
}

impl BuyerAccountSectionParams {
    /// No filter; set the ones you want.
    pub fn new() -> Self {
        Self::default()
    }

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

    /// Continue after the previous page.
    #[must_use]
    pub fn cursor(mut self, cursor: impl Into<String>) -> Self {
        self.cursor = Some(cursor.into());
        self
    }

    /// The most items to return.
    #[must_use]
    pub fn limit(mut self, limit: i64) -> Self {
        self.limit = Some(limit);
        self
    }

    /// Only test-mode or only live items.
    #[must_use]
    pub fn test_mode(mut self, test_mode: bool) -> Self {
        self.test_mode = Some(test_mode);
        self
    }

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

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

    const SESSION_JSON: &str = r#"{
        "token": "bas_secret_token", "expires_at": 1767225600,
        "email": "j***@example.com", "surprise_field": 1
    }"#;

    const CONVERSATION_LIST_JSON: &str = r#"{
        "data": [{
            "id": "conv_1", "record": "rec_1", "shop": "pro_1", "shop_name": "Shop",
            "test_mode": false, "status": "open", "last_message_at": "2026-01-01T00:00:00Z",
            "last_message_by": "buyer", "unread": false
        }],
        "unconfirmed_records": true, "surprise_field": 2
    }"#;

    const MESSAGE_PAGE_JSON: &str = r#"{
        "conversation": {"id": "conv_1", "shop": "pro_1", "shop_name": "Shop",
                         "test_mode": false, "status": "closed",
                         "last_message_at": "2026-01-01T00:00:00Z",
                         "last_message_by": "merchant", "unread": true},
        "messages": [{"id": "msg_1", "sender": "merchant", "sender_name": "Sam",
                      "body": "Hi", "attachments": [], "created_at": "2026-01-01T00:00:00Z"}],
        "has_more": true,
        "case_updates": [{"case": "case_1", "kind": "dispute",
                          "event": {"at": "2026-01-01T00:00:00Z", "kind": "opened",
                                    "actor": "provider"}}],
        "attachment_rules": {"enabled": false, "file_types": [],
                             "max_file_megabytes": 0, "max_files": 0},
        "surprise_field": 3
    }"#;

    const EVIDENCE_JSON: &str = r#"{
        "available": false, "unavailable_reason": "case_closed",
        "can_submit": false, "can_request_extension": false, "extension_requested": false,
        "saved_files": [], "history": [], "surprise_field": 4
    }"#;

    const EVIDENCE_FILE_JSON: &str = r#"{
        "id": "file_1", "file_name": "photo.png", "file_type": "png", "size_bytes": 4,
        "uploaded_at": "2026-01-01T00:00:00Z", "submitted": false, "surprise_field": 5
    }"#;

    const EVIDENCE_ENTRY_JSON: &str = r#"{
        "id": "ent_1", "kind": "extension_requested", "actor": "buyer",
        "at": "2026-01-01T00:00:00Z", "files": [], "surprise_field": 6
    }"#;

    #[tokio::test]
    async fn availability_gets_the_availability_path() {
        let (client, mock) = client_with(vec![Step::ok(
            r#"{"enabled":true,"methods":["code","magic_link"],"surprise_field":1}"#,
        )]);
        let out = client.buyer_account().availability().await.unwrap();
        assert!(out.enabled);
        assert_eq!(out.methods, ["code", "magic_link"]);
        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/buyer-account/availability");
    }

    #[tokio::test]
    async fn start_sign_in_posts_the_address_and_locale() {
        let (client, mock) = client_with(vec![Step::ok(
            r#"{"methods":["code"],"expires_in_seconds":600,"surprise_field":1}"#,
        )]);
        let params = BuyerAccountSignInRequest::new("buyer@example.com").locale("de");
        assert!(!format!("{params:?}").contains("buyer@example.com"));
        let out = client.buyer_account().start_sign_in(&params).await.unwrap();
        assert_eq!(out.expires_in_seconds, 600);
        assert_eq!(out.extra["surprise_field"], 1);

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(seen[0].url, "https://api.test/buyer-account/sign-in");
        assert_eq!(
            seen[0].body_json(),
            json!({"email": "buyer@example.com", "locale": "de"})
        );
    }

    #[tokio::test]
    async fn verify_code_posts_the_code_and_redacts_the_session() {
        let (client, mock) = client_with(vec![Step::ok(SESSION_JSON)]);
        let params = BuyerAccountVerifyCodeRequest::new("buyer@example.com", "123456");
        assert!(!format!("{params:?}").contains("123456"));
        let session = client.buyer_account().verify_code(&params).await.unwrap();
        assert_eq!(session.token, "bas_secret_token");
        assert_eq!(session.extra["surprise_field"], 1);
        // The session token never reaches `Debug`.
        assert!(!format!("{session:?}").contains("bas_secret_token"));

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(seen[0].url, "https://api.test/buyer-account/sign-in/code");
        assert_eq!(
            seen[0].body_json(),
            json!({"email": "buyer@example.com", "code": "123456"})
        );
    }

    #[tokio::test]
    async fn verify_link_posts_the_link_token() {
        let (client, mock) = client_with(vec![Step::ok(SESSION_JSON)]);
        let params = BuyerAccountVerifyLinkRequest::new("lnk_abc");
        assert!(!format!("{params:?}").contains("lnk_abc"));
        client.buyer_account().verify_link(&params).await.unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(seen[0].url, "https://api.test/buyer-account/sign-in/link");
        assert_eq!(seen[0].body_json(), json!({"token": "lnk_abc"}));
    }

    #[tokio::test]
    async fn a_sign_in_from_a_keyless_client_sends_no_credential() {
        // A client built with an empty key sends no `api-key` at all: a
        // mutation sending the empty header fails here.
        let (_client, mock) = client_with(vec![Step::ok(
            r#"{"methods":["code"],"expires_in_seconds":600}"#,
        )]);
        let keyless = crate::Delopay {
            inner: std::sync::Arc::new(crate::http::client::Inner::with_transport(
                mock.clone(),
                "https://api.test".to_string(),
                "https://checkout.test".to_string(),
                String::new(),
                0,
            )),
        };
        keyless
            .buyer_account()
            .start_sign_in(&BuyerAccountSignInRequest::new("jane@example.com"))
            .await
            .unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].header("api-key"), None);
        assert_eq!(seen[0].header("authorization"), None);
    }

    #[tokio::test]
    async fn get_session_sends_the_session_token_as_the_api_key() {
        let (client, mock) = client_with(vec![Step::ok(
            r#"{"email":"j***@example.com","expires_at":1767225600,"has_password":false,
                "surprise_field":1}"#,
        )]);
        let info = client.buyer_account().get_session().await.unwrap();
        assert_eq!(info.expires_at, 1767225600);
        assert_eq!(info.extra["surprise_field"], 1);

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "GET");
        assert_eq!(seen[0].url, "https://api.test/buyer-account/session");
        assert_eq!(seen[0].header("api-key"), Some("prd_test"));
    }

    #[tokio::test]
    async fn sign_out_deletes_the_session() {
        let (client, mock) = client_with(vec![Step::ok(r#"{"deleted":true,"id":"x"}"#)]);
        client.buyer_account().sign_out().await.unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "DELETE");
        assert_eq!(seen[0].url, "https://api.test/buyer-account/session");
    }

    #[tokio::test]
    async fn sign_out_accepts_an_empty_body() {
        let (client, _mock) = client_with(vec![Step::ok("")]);
        client.buyer_account().sign_out().await.unwrap();
    }

    #[tokio::test]
    async fn notice_settings_gets_the_settings() {
        let (client, mock) = client_with(vec![Step::ok(
            r#"{"replies":true,"case_updates":false,"surprise_field":1}"#,
        )]);
        let out = client.buyer_account().notice_settings().await.unwrap();
        assert!(out.replies);
        assert!(!out.case_updates);
        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/buyer-account/notice-settings"
        );
    }

    #[tokio::test]
    async fn set_notice_settings_puts_both_toggles() {
        let (client, mock) =
            client_with(vec![Step::ok(r#"{"replies":false,"case_updates":true}"#)]);
        client
            .buyer_account()
            .set_notice_settings(&BuyerNoticeSettingsRequest::new(false, true))
            .await
            .unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "PUT");
        assert_eq!(
            seen[0].url,
            "https://api.test/buyer-account/notice-settings"
        );
        assert_eq!(
            seen[0].body_json(),
            json!({"replies": false, "case_updates": true})
        );
    }

    #[tokio::test]
    async fn list_purchases_sends_every_query_parameter() {
        let (client, mock) = client_with(vec![Step::ok(
            r#"{"data":[{"id":"pay_1","record":"rec_1","kind":"payment","status":"succeeded",
                "amount":1200,"currency":"EUR","created_at":"2026-01-01T00:00:00Z",
                "shop":"pro_1","shop_name":"Shop","lines":[],"test_mode":false,
                "confirmed":true,"confirmable":false}],
                "next_cursor":"cur_2","surprise_field":1}"#,
        )]);
        let params = BuyerAccountPurchaseParams::new()
            .limit(10)
            .cursor("cur_1")
            .shop("pro_1");
        let page = client
            .buyer_account()
            .list_purchases(Some(&params))
            .await
            .unwrap();
        assert_eq!(page.data[0].record, "rec_1");
        assert_eq!(page.next_cursor.as_deref(), Some("cur_2"));
        assert_eq!(page.extra["surprise_field"], 1);

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "GET");
        assert_eq!(
            seen[0].url,
            "https://api.test/buyer-account/purchases?limit=10&cursor=cur_1&shop=pro_1"
        );
    }

    #[tokio::test]
    async fn list_shops_gets_the_shops_path() {
        let (client, mock) = client_with(vec![Step::ok(
            r#"{"data":[{"shop":"pro_1","name":"Shop"}],"surprise_field":1}"#,
        )]);
        let out = client.buyer_account().list_shops().await.unwrap();
        assert_eq!(out.data[0].name, "Shop");
        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/buyer-account/shops");
    }

    #[tokio::test]
    async fn list_subscriptions_sends_the_section_query() {
        let (client, mock) = client_with(vec![Step::ok(
            r#"{"data":[{"id":"sub_1","record":"rec_1","shop":"pro_1","shop_name":"Shop",
                "status":"active","created_at":"2026-01-01T00:00:00Z","test_mode":true,
                "confirmed":false}],"has_more":false,"surprise_field":1}"#,
        )]);
        let params = BuyerAccountSectionParams::new()
            .shop("pro_1")
            .cursor("cur_1")
            .limit(5)
            .test_mode(true);
        let out = client
            .buyer_account()
            .list_subscriptions(Some(&params))
            .await
            .unwrap();
        assert!(!out.data[0].confirmed);
        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/buyer-account/subscriptions?shop=pro_1&cursor=cur_1&limit=5&test_mode=true"
        );
    }

    #[tokio::test]
    async fn list_invoices_gets_the_invoices_path() {
        let (client, mock) = client_with(vec![Step::ok(
            r#"{"data":[{"id":"inv_1","record":"rec_1","shop":"pro_1","shop_name":"Shop",
                "kind":"invoice","status":"issued","currency":"EUR","gross_amount":1190,
                "supply_date":"2026-01-01","test_mode":false}],
                "has_more":false,"unconfirmed_records":true,"surprise_field":1}"#,
        )]);
        let out = client
            .buyer_account()
            .list_invoices(Some(&BuyerAccountSectionParams::new().test_mode(false)))
            .await
            .unwrap();
        assert_eq!(out.data[0].gross_amount, 1190);
        assert!(out.unconfirmed_records);
        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/buyer-account/invoices?test_mode=false"
        );
    }

    #[tokio::test]
    async fn list_refund_requests_gets_the_refund_requests_path() {
        let (client, mock) = client_with(vec![Step::ok(
            r#"{"data":[{"id":"rr_1","record":"rec_1","shop":"pro_1","shop_name":"Shop",
                "purchase":"pay_1","purchase_kind":"payment","reason":"duplicate",
                "message":"Charged twice","amount":500,"currency":"EUR","status":"approved",
                "approved_amount":500,"created_at":"2026-01-01T00:00:00Z","test_mode":false}],
                "has_more":false,"unconfirmed_records":false,"surprise_field":1}"#,
        )]);
        let out = client
            .buyer_account()
            .list_refund_requests(None)
            .await
            .unwrap();
        assert_eq!(out.data[0].approved_amount, Some(500));
        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/buyer-account/refund-requests"
        );
    }

    #[tokio::test]
    async fn list_cases_sends_the_shop_filter() {
        let (client, mock) = client_with(vec![Step::ok(
            r#"{"data":[],"has_more":false,"unconfirmed_records":true,"surprise_field":1}"#,
        )]);
        let out = client
            .buyer_account()
            .list_cases(Some("pro_1"))
            .await
            .unwrap();
        assert!(out.unconfirmed_records);
        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/buyer-account/cases?shop=pro_1"
        );
    }

    #[tokio::test]
    async fn list_conversations_without_a_shop_sends_no_query() {
        let (client, mock) = client_with(vec![Step::ok(CONVERSATION_LIST_JSON)]);
        let out = client
            .buyer_account()
            .list_conversations(None)
            .await
            .unwrap();
        assert_eq!(out.data[0].record.as_deref(), Some("rec_1"));
        assert_eq!(out.extra["surprise_field"], 2);

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "GET");
        assert_eq!(seen[0].url, "https://api.test/buyer-account/conversations");
    }

    #[tokio::test]
    async fn list_record_messages_encodes_the_record_and_sends_the_shop() {
        let (client, mock) = client_with(vec![Step::ok(MESSAGE_PAGE_JSON)]);
        let page = client
            .buyer_account()
            .list_record_messages("rec/1", &BuyerConversationParams::new("pro_1").limit(10))
            .await
            .unwrap();
        assert_eq!(page.conversation.as_ref().unwrap().status, "closed");
        assert_eq!(page.messages[0].sender_name.as_deref(), Some("Sam"));
        assert_eq!(page.case_updates[0].event.actor, "provider");
        assert_eq!(page.extra["surprise_field"], 3);

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "GET");
        assert_eq!(
            seen[0].url,
            "https://api.test/buyer-account/records/rec%2F1/messages?shop=pro_1&limit=10"
        );
    }

    #[tokio::test]
    async fn send_record_message_posts_to_the_record() {
        let (client, mock) = client_with(vec![Step::ok(
            r#"{"id":"msg_2","sender":"buyer","body":"Thanks","attachments":[],
                "created_at":"2026-01-01T00:00:00Z","surprise_field":1}"#,
        )]);
        let params = BuyerMessageCreateRequest::new("msg_12345678")
            .shop("pro_1")
            .test_mode(false)
            .body("Thanks");
        let out = client
            .buyer_account()
            .send_record_message("rec_1", &params)
            .await
            .unwrap();
        assert_eq!(out.id, "msg_2");
        assert_eq!(out.extra["surprise_field"], 1);

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(
            seen[0].url,
            "https://api.test/buyer-account/records/rec_1/messages"
        );
        assert_eq!(
            seen[0].body_json(),
            json!({
                "client_message_id": "msg_12345678",
                "shop": "pro_1",
                "test_mode": false,
                "body": "Thanks"
            })
        );
        assert!(!seen[0].had_idempotency_key());
    }

    #[tokio::test]
    async fn mark_record_messages_read_posts_with_the_shop_query() {
        let (client, mock) = client_with(vec![Step::ok(CONVERSATION_LIST_JSON)]);
        client
            .buyer_account()
            .mark_record_messages_read("rec_1", &BuyerConversationParams::new("pro_1"))
            .await
            .unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(
            seen[0].url,
            "https://api.test/buyer-account/records/rec_1/messages/read?shop=pro_1"
        );
        assert!(seen[0].body.is_none());
    }

    #[tokio::test]
    async fn upload_record_message_file_posts_multipart_with_the_shop() {
        let (client, mock) = client_with(vec![Step::ok(
            r#"{"id":"att_1","file_name":"a.txt","file_type":"text","size_bytes":2,
                "surprise_field":1}"#,
        )]);
        let upload = BuyerFileUpload::new("upl_12345678", "a.txt", "text/plain", b"hi");
        let out = client
            .buyer_account()
            .upload_record_message_file("rec_1", &upload, &BuyerAttachmentParams::new("pro_1"))
            .await
            .unwrap();
        assert_eq!(out.file_type, "text");
        assert_eq!(out.extra["surprise_field"], 1);

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(
            seen[0].url,
            "https://api.test/buyer-account/records/rec_1/messages/files?shop=pro_1"
        );
        let body = String::from_utf8(seen[0].body.clone().unwrap()).unwrap();
        assert!(body.contains("name=\"client_upload_id\"\r\n\r\nupl_12345678\r\n"));
        assert!(body.contains("filename=\"a.txt\"\r\nContent-Type: text/plain\r\n\r\nhi"));
    }

    #[tokio::test]
    async fn download_record_message_file_gets_the_bytes() {
        let (client, mock) = client_with(vec![Step::ok("hi")]);
        let bytes = client
            .buyer_account()
            .download_record_message_file("rec_1", "att/1", &BuyerAttachmentParams::new("pro_1"))
            .await
            .unwrap();
        assert_eq!(bytes, b"hi");

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "GET");
        assert_eq!(
            seen[0].url,
            "https://api.test/buyer-account/records/rec_1/messages/files/att%2F1?shop=pro_1"
        );
        assert_eq!(seen[0].header("accept"), Some("*/*"));
    }

    #[tokio::test]
    async fn remove_record_message_file_deletes_with_the_shop() {
        let (client, mock) = client_with(vec![Step::ok(r#"{"deleted":true,"id":"x"}"#)]);
        client
            .buyer_account()
            .remove_record_message_file(
                "rec_1",
                "att_1",
                &BuyerAttachmentParams::new("pro_1").test_mode(true),
            )
            .await
            .unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "DELETE");
        assert_eq!(
            seen[0].url,
            "https://api.test/buyer-account/records/rec_1/messages/files/att_1?shop=pro_1&test_mode=true"
        );
    }

    #[tokio::test]
    async fn confirm_posts_the_portal_token() {
        let (client, mock) = client_with(vec![Step::ok(
            r#"{"record":"rec_1","confirmed_at":1767225600,"surprise_field":1}"#,
        )]);
        let params = BuyerAccountConfirmRequest::new("ptk_secret");
        assert!(!format!("{params:?}").contains("ptk_secret"));
        let out = client.buyer_account().confirm(&params).await.unwrap();
        assert_eq!(out.record, "rec_1");
        assert_eq!(out.extra["surprise_field"], 1);

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(seen[0].url, "https://api.test/buyer-account/confirmations");
        assert_eq!(seen[0].body_json(), json!({"portal_token": "ptk_secret"}));
    }

    #[tokio::test]
    async fn open_portal_posts_to_the_record_and_redacts_the_url() {
        let (client, mock) = client_with(vec![Step::ok(
            r#"{"url":"https://portal.example/s/ptk_secret","expires_at":1767225600,
                "surprise_field":1}"#,
        )]);
        let portal = client.buyer_account().open_portal("rec/1").await.unwrap();
        assert_eq!(portal.url, "https://portal.example/s/ptk_secret");
        assert_eq!(portal.extra["surprise_field"], 1);
        assert!(!format!("{portal:?}").contains("ptk_secret"));

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(
            seen[0].url,
            "https://api.test/buyer-account/records/rec%2F1/portal"
        );
        assert!(seen[0].body.is_none());
    }

    #[tokio::test]
    async fn case_evidence_encodes_record_and_case() {
        let (client, mock) = client_with(vec![Step::ok(EVIDENCE_JSON)]);
        let out = client
            .buyer_account()
            .case_evidence("rec/1", "case/1")
            .await
            .unwrap();
        assert_eq!(out.unavailable_reason.as_deref(), Some("case_closed"));
        assert_eq!(out.extra["surprise_field"], 4);

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "GET");
        assert_eq!(
            seen[0].url,
            "https://api.test/buyer-account/records/rec%2F1/cases/case%2F1/evidence"
        );
    }

    #[tokio::test]
    async fn upload_evidence_file_posts_multipart_to_the_case() {
        let (client, mock) = client_with(vec![Step::ok(EVIDENCE_FILE_JSON)]);
        let upload = BuyerFileUpload::new("upl_12345678", "photo.png", "image/png", b"PNG!");
        let out = client
            .buyer_account()
            .upload_evidence_file("rec_1", "case_1", &upload)
            .await
            .unwrap();
        assert_eq!(out.id, "file_1");
        assert_eq!(out.extra["surprise_field"], 5);

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(
            seen[0].url,
            "https://api.test/buyer-account/records/rec_1/cases/case_1/evidence/files"
        );
        let body = String::from_utf8(seen[0].body.clone().unwrap()).unwrap();
        assert!(body.contains("name=\"client_upload_id\"\r\n\r\nupl_12345678\r\n"));
        assert!(body.contains("Content-Type: image/png\r\n\r\nPNG!"));
    }

    #[tokio::test]
    async fn download_evidence_file_gets_the_bytes() {
        let (client, mock) = client_with(vec![Step::ok("PNG!")]);
        let bytes = client
            .buyer_account()
            .download_evidence_file("rec_1", "case_1", "file_1")
            .await
            .unwrap();
        assert_eq!(bytes, b"PNG!");

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "GET");
        assert_eq!(
            seen[0].url,
            "https://api.test/buyer-account/records/rec_1/cases/case_1/evidence/files/file_1"
        );
    }

    #[tokio::test]
    async fn remove_evidence_file_deletes_the_file() {
        let (client, mock) = client_with(vec![Step::ok(r#"{"deleted":true,"id":"x"}"#)]);
        client
            .buyer_account()
            .remove_evidence_file("rec_1", "case_1", "file/1")
            .await
            .unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "DELETE");
        assert_eq!(
            seen[0].url,
            "https://api.test/buyer-account/records/rec_1/cases/case_1/evidence/files/file%2F1"
        );
    }

    #[tokio::test]
    async fn submit_evidence_posts_to_the_case() {
        let (client, mock) = client_with(vec![Step::ok(EVIDENCE_ENTRY_JSON)]);
        let params = BuyerEvidenceSubmitRequest::new("sub_12345678").explanation("See photo");
        client
            .buyer_account()
            .submit_evidence("rec_1", "case_1", &params)
            .await
            .unwrap();

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(
            seen[0].url,
            "https://api.test/buyer-account/records/rec_1/cases/case_1/evidence/submissions"
        );
        assert_eq!(
            seen[0].body_json(),
            json!({"client_submission_id": "sub_12345678", "explanation": "See photo"})
        );
    }

    #[tokio::test]
    async fn request_evidence_extension_posts_to_the_case() {
        let (client, mock) = client_with(vec![Step::ok(EVIDENCE_ENTRY_JSON)]);
        let out = client
            .buyer_account()
            .request_evidence_extension(
                "rec_1",
                "case_1",
                &BuyerEvidenceExtensionRequest::new("Need a week"),
            )
            .await
            .unwrap();
        assert_eq!(out.kind, "extension_requested");
        assert_eq!(out.extra["surprise_field"], 6);

        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen[0].method, "POST");
        assert_eq!(
            seen[0].url,
            "https://api.test/buyer-account/records/rec_1/cases/case_1/evidence/extension-requests"
        );
        assert_eq!(seen[0].body_json(), json!({"message": "Need a week"}));
    }

    /// Drift guard for `BUYER_ACCOUNT_SIGN_IN_REQUEST_NAMED`.
    #[test]
    fn buyer_account_sign_in_request_named_fields_are_complete() {
        let req = BuyerAccountSignInRequest::new("a@example.com").locale("de");
        let value = serde_json::to_value(req).unwrap();
        for key in value.as_object().expect("serializes to an object").keys() {
            assert!(
                BUYER_ACCOUNT_SIGN_IN_REQUEST_NAMED.contains(&key.as_str()),
                "BUYER_ACCOUNT_SIGN_IN_REQUEST_NAMED is missing wire key `{key}`"
            );
        }
    }

    /// Drift guard for `BUYER_ACCOUNT_VERIFY_CODE_REQUEST_NAMED`.
    #[test]
    fn buyer_account_verify_code_request_named_fields_are_complete() {
        let req = BuyerAccountVerifyCodeRequest::new("a@example.com", "123456");
        let value = serde_json::to_value(req).unwrap();
        for key in value.as_object().expect("serializes to an object").keys() {
            assert!(
                BUYER_ACCOUNT_VERIFY_CODE_REQUEST_NAMED.contains(&key.as_str()),
                "BUYER_ACCOUNT_VERIFY_CODE_REQUEST_NAMED is missing wire key `{key}`"
            );
        }
    }

    /// A client carrying a client-wide idempotency key and a retry budget,
    /// over a mock that answers 503 first and `ok` after.
    fn keyed_client(
        ok: &str,
    ) -> (
        crate::Delopay,
        std::sync::Arc<crate::http::mock::MockTransport>,
    ) {
        let (client, mock) = crate::http::mock::client_with_retries(
            vec![
                Step::status(503, r#"{"error":{"message":"down"}}"#),
                Step::ok(ok),
            ],
            2,
        );
        (client.with_idempotency_key("idem_client_wide"), mock)
    }

    /// The write went out once and without the client-wide key: the route
    /// does not deduplicate on the header, so a replay could act twice.
    fn assert_sent_once_without_key(mock: &crate::http::mock::MockTransport) {
        assert_eq!(
            mock.call_count(),
            1,
            "a 503 on this write must not be retried"
        );
        assert!(
            !mock.seen.lock().unwrap()[0].had_idempotency_key(),
            "the client-wide key must not be sent"
        );
    }

    // Mutation: switching any of these call sites back to `request(.., None)`
    // sends the client-wide key and replays the 503, so both checks fail.
    // A code or a link is a one-time challenge: a replay would spend it twice.
    #[tokio::test]
    async fn account_writes_ignore_the_client_wide_idempotency_key() {
        let (client, mock) = keyed_client(r#"{"methods":["code"],"expires_in_seconds":600}"#);
        let params = BuyerAccountSignInRequest::new("buyer@example.com");
        assert!(client.buyer_account().start_sign_in(&params).await.is_err());
        assert_sent_once_without_key(&mock);

        let (client, mock) = keyed_client(SESSION_JSON);
        let params = BuyerAccountVerifyCodeRequest::new("buyer@example.com", "123456");
        assert!(client.buyer_account().verify_code(&params).await.is_err());
        assert_sent_once_without_key(&mock);

        let (client, mock) = keyed_client(SESSION_JSON);
        let params = BuyerAccountVerifyLinkRequest::new("lnk_abc");
        assert!(client.buyer_account().verify_link(&params).await.is_err());
        assert_sent_once_without_key(&mock);

        let (client, mock) = keyed_client(r#"{"replies":true,"case_updates":true}"#);
        assert!(
            client
                .buyer_account()
                .set_notice_settings(&BuyerNoticeSettingsRequest::new(true, true))
                .await
                .is_err()
        );
        assert_sent_once_without_key(&mock);

        let (client, mock) = keyed_client("");
        assert!(client.buyer_account().sign_out().await.is_err());
        assert_sent_once_without_key(&mock);
    }
}