sepa 0.6.0

SEPA payment utilities: IBAN validation (ISO 13616 + 89-country registry), BIC validation (ISO 9362), SEPA Creditor Identifier (EPC AT-02), pain.001 SCT + SCT Inst XML builder (pain.001.001.09 / .001.03 / .003.03), pain.008 SDD CORE + B2B XML builder (pain.008.001.08 / .001.02 / .003.02), pain.007 SDD reversal XML builder (pain.007.001.09), pain.002 status report parser incl. Verification of Payee, camt.052/053/054 parsers, structured and hybrid postal addresses for the Nov 2026 EPC cut-over, ISO 11649 RF creditor references, EPC field validation and SEPA charset transliteration. Output is XSD-validated in CI. Typed ISO 8601 dates. Zero I/O. No async. No f64 in monetary arithmetic.
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
//! ISO 20022 pain.001 — SEPA Credit Transfer (SCT) initiation.
//!
//! Builds SEPA Credit Transfer XML for outgoing payments:
//! supplier credits, refunds to customers, or any IBAN-to-IBAN EUR transfer.
//! Supports both the DK legacy schema and the current EPC/SCT Inst schema.
//!
//! ## Schema versions
//!
//! | Schema | Variant | Use |
//! |---|---|---|
//! | `pain.001.001.09` | [`CreditTransferSchema::IsoV9`] | Current SEPA version (**default**) |
//! | `pain.001.001.03` | [`CreditTransferSchema::IsoV3`] | EPC version until Nov 2023; still accepted by many banks |
//! | `pain.001.003.03` | [`CreditTransferSchema::DkV2_7`] | Legacy DK V2.7, end-of-life since Nov 2022 |
//!
//! Which one a bank requires varies by bank and by regulatory cutover date, so
//! it is a per-message choice. Select it with [`Pain001Builder::schema`], or
//! parse it from configuration — the enum implements [`FromStr`]
//! over both the message identifier (`"pain.001.001.03"`) and the namespace URN.
//!
//! ## Postal addresses
//!
//! `Dbtr/PstlAdr` sits on the group (it belongs to the account holder) and
//! `Cdtr/PstlAdr` on each transfer. Both are optional, and both must be
//! structured or hybrid — see [`PostalAddress`] for the
//! 15 November 2026 cut-over. The legacy DK schema cannot carry one and says
//! so with [`ValidationError::UnsupportedBySchema`].
//!
//! ## References
//!
//! - ISO 20022 pain.001.001.03 / pain.001.001.09 / pain.001.003.03 schemas
//! - EPC SEPA Credit Transfer Rulebook (SCT), 2025 version
//! - EPC SEPA Instant Credit Transfer Rulebook (SCT Inst), 2025 version
//! - EPC153-22 v2.1, Provision of Addresses under the EPC Payment Schemes
//! - Deutsche Kreditwirtschaft DFÜ-Abkommen V2.7
//!
//! ## Example
//!
//! ```rust
//! use sepa::{CreditTransferEntry, CreditTransferGroup, IsoDate, Pain001Builder, validate_iban};
//! use sepa::pain001::LocalInstrument;
//!
//! let debtor   = validate_iban("DE89370400440532013000")?;
//! let creditor = validate_iban("NL91ABNA0417164300")?;
//! let execute  = IsoDate::new(2026, 7, 20)?;
//!
//! let xml = Pain001Builder::new("Acme GmbH")
//!     .msg_id("CT-2026-07-001")
//!     .add_group(
//!         CreditTransferGroup::new("Acme GmbH", &debtor)
//!             .execution_date(execute)
//!             .add_entry(
//!                 CreditTransferEntry::new("Max Mustermann", creditor.clone(), 12_000, "REFUND")
//!                     .with_description("Erstattung 2025"),
//!             ),
//!     )
//!     .build()?;
//!
//! assert!(xml.contains("<InstdAmt Ccy=\"EUR\">120.00</InstdAmt>"));
//! // pain.001.001.09 wraps the execution date in a <Dt> choice child.
//! assert!(xml.contains("<ReqdExctnDt><Dt>2026-07-20</Dt></ReqdExctnDt>"));
//!
//! // SCT Instant is a property of the group.
//! let inst = Pain001Builder::new("Acme GmbH")
//!     .msg_id("CT-INST-001")
//!     .add_group(
//!         CreditTransferGroup::new("Acme GmbH", &debtor)
//!             .local_instrument(LocalInstrument::Inst)
//!             .execution_date(execute)
//!             .add_entry(CreditTransferEntry::new("Max", creditor, 5_000, "INST-001")),
//!     )
//!     .build()?;
//! assert!(inst.contains("<Cd>INST</Cd>"));
//! # Ok::<(), Box<dyn std::error::Error>>(())
//! ```

use std::str::FromStr;

use crate::address::PostalAddress;
use crate::date::IsoDate;
use crate::party::Party;
use crate::purpose::{CategoryPurpose, Purpose};
use crate::reference::RemittanceInfo;
use crate::validate::{
    BuildError, CharsetPolicy, Locate, Location, MAX_ID_LEN, UnknownSchema, ValidationError,
    WriteError, check_amount, check_id, check_name, truncate_chars,
};
use crate::{Bic, Iban, IsoDateTime, ct_to_eur_str};

// ── Schema version ────────────────────────────────────────────────────────────

/// pain.001 XML schema version to emit.
///
/// The versions differ in ways that matter to the wire format, not just the
/// namespace — see [`CreditTransferSchema::namespace`] and the notes on each
/// variant. [`FromStr`] accepts the message identifier (`"pain.001.001.03"`)
/// and the full namespace URN, which is what makes the target version
/// configurable rather than compiled in.
///
/// # Examples
///
/// ```
/// use sepa::pain001::CreditTransferSchema;
///
/// let from_config: CreditTransferSchema = "pain.001.001.03".parse()?;
/// assert_eq!(from_config, CreditTransferSchema::IsoV3);
/// assert_eq!(from_config.to_string(), "pain.001.001.03");
/// # Ok::<(), sepa::UnknownSchema>(())
/// ```
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum CreditTransferSchema {
    /// `pain.001.001.09` — the current SEPA version (**default**).
    ///
    /// Mandated by the EPC 2023 SCT Rulebook with effect from 19 November 2023
    /// and carried unchanged into the 2025 rulebooks.
    ///
    /// Wire-format specifics versus the older versions:
    /// - `ReqdExctnDt` is a `DateAndDateTime2Choice`, so the date is wrapped:
    ///   `<ReqdExctnDt><Dt>2026-07-20</Dt></ReqdExctnDt>`
    /// - the agent BIC element is named `BICFI`, not `BIC`
    #[default]
    IsoV9,

    /// `pain.001.001.03` — the EPC version in force from 2009 to 19 Nov 2023.
    ///
    /// Superseded by [`IsoV9`](Self::IsoV9) but still the version many banks
    /// and corporate channels accept, and the version the pre-2023 SCT Inst
    /// rulebooks used. Emits a bare `<ReqdExctnDt>2026-07-20</ReqdExctnDt>` and
    /// names the agent BIC element `BIC`.
    IsoV3,

    /// `pain.001.003.03` — legacy Deutsche Kreditwirtschaft DK V2.7 (2013).
    ///
    /// **End-of-life.** Superseded in November 2022 by DK Anlage 3 V3.6 and
    /// absent from every DK format specification since. Retained only for
    /// systems still pinned to it; new integrations should use
    /// [`IsoV9`](Self::IsoV9).
    ///
    /// Emits a bare `<ReqdExctnDt>2026-07-20</ReqdExctnDt>` and names the agent
    /// BIC element `BIC`. Its `PmtTpInf` has no `LclInstrm` element at all, so
    /// it cannot carry [`LocalInstrument::Inst`].
    DkV2_7,
}

impl CreditTransferSchema {
    /// Every schema version this builder can emit, newest first.
    pub const ALL: &'static [Self] = &[Self::IsoV9, Self::IsoV3, Self::DkV2_7];

    /// The ISO 20022 message identifier, e.g. `"pain.001.001.09"`.
    #[must_use]
    pub const fn message_id(self) -> &'static str {
        match self {
            Self::IsoV9 => "pain.001.001.09",
            Self::IsoV3 => "pain.001.001.03",
            Self::DkV2_7 => "pain.001.003.03",
        }
    }

    /// The XML namespace URI for this schema version.
    #[must_use]
    pub const fn namespace(self) -> &'static str {
        match self {
            Self::IsoV9 => "urn:iso:std:iso:20022:tech:xsd:pain.001.001.09",
            Self::IsoV3 => "urn:iso:std:iso:20022:tech:xsd:pain.001.001.03",
            Self::DkV2_7 => "urn:iso:std:iso:20022:tech:xsd:pain.001.003.03",
        }
    }

    /// Whether this schema can carry `PmtTpInf/LclInstrm`.
    ///
    /// The DK schema cannot: `PaymentTypeInformationSCT1` is a sequence of
    /// `InstrPrty`, `SvcLvl` and `CtgyPurp` with no local-instrument element,
    /// so an `INST` batch built against it is schema-invalid rather than merely
    /// unusual.
    #[must_use]
    pub const fn supports_local_instrument(self) -> bool {
        !matches!(self, Self::DkV2_7)
    }

    /// Whether this schema can carry a structured `PstlAdr`.
    ///
    /// The DK schema cannot: its `PostalAddressSEPA` type holds nothing but
    /// `Ctry` and two `AdrLine`s — precisely the unstructured form the EPC
    /// retires on 15 November 2026 — so there is no element to put a town or a
    /// street in. See [`PostalAddress`].
    #[must_use]
    pub const fn supports_postal_address(self) -> bool {
        !matches!(self, Self::DkV2_7)
    }

    /// The element name carrying an agent's BIC.
    ///
    /// ISO renamed `BIC` to `BICFI` in the 2019 maintenance release.
    #[must_use]
    const fn bic_element(self) -> &'static str {
        match self {
            Self::IsoV9 => "BICFI",
            Self::IsoV3 | Self::DkV2_7 => "BIC",
        }
    }

    /// Whether `ReqdExctnDt` is a date/time choice rather than a bare date.
    ///
    /// Only `pain.001.001.09` types it as `DateAndDateTime2Choice`. That is
    /// both why the date needs a `<Dt>` wrapper there and why a timed execution
    /// ([`ExecutionMoment::At`]) is expressible only on that version.
    #[must_use]
    pub const fn supports_execution_time(self) -> bool {
        matches!(self, Self::IsoV9)
    }
}

impl std::fmt::Display for CreditTransferSchema {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.message_id())
    }
}

impl FromStr for CreditTransferSchema {
    type Err = UnknownSchema;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let key = s.trim().to_ascii_lowercase();
        Self::ALL
            .iter()
            .copied()
            .find(|schema| key == schema.message_id() || key == schema.namespace())
            .ok_or_else(|| UnknownSchema {
                value: s.to_owned(),
                supported: "pain.001.001.09, pain.001.001.03, pain.001.003.03",
            })
    }
}

impl TryFrom<&str> for CreditTransferSchema {
    type Error = UnknownSchema;
    fn try_from(s: &str) -> Result<Self, Self::Error> {
        s.parse()
    }
}

// ── LocalInstrument ───────────────────────────────────────────────────────────

/// SEPA Credit Transfer local instrument variant.
///
/// [`Inst`](LocalInstrument::Inst) adds `<LclInstrm><Cd>INST</Cd></LclInstrm>`
/// to the group's `PmtTpInf`. It needs a schema that has that element:
/// `pain.001.001.09` (the 2023 rulebooks) or `pain.001.001.03` (the earlier
/// ones). Combining it with [`CreditTransferSchema::DkV2_7`] is rejected by
/// `build()` with [`ValidationError::UnsupportedBySchema`] rather than emitting
/// a file the schema does not allow.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
#[non_exhaustive]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum LocalInstrument {
    /// Standard SEPA Credit Transfer — no local instrument code (default).
    #[default]
    None,
    /// SEPA Instant Credit Transfer — 10-second settlement window.
    ///
    /// EU Regulation 2024/886 mandates PSP support for SCT Inst in the eurozone.
    Inst,
}

// ── ExecutionMoment ───────────────────────────────────────────────────────────

/// When a payment group is to be executed (`ReqdExctnDt`).
///
/// `pain.001.001.09` types this as a `DateAndDateTime2Choice`, so it is either
/// a bare day or a day *and* a time. The timed form is what the Deutsche
/// Kreditwirtschaft calls a **terminierte Echtzeitüberweisung** — a scheduled
/// SEPA Instant transfer that is to leave the account at a stated moment rather
/// than at some point during the day.
///
/// The older schemas type `ReqdExctnDt` as a bare `ISODate` and have no choice
/// wrapper at all, so [`At`](Self::At) on those is rejected with
/// [`ValidationError::UnsupportedBySchema`] rather than silently downgraded to
/// the date — a payment that was meant to leave at 11:00 must not quietly
/// become "some time that day".
///
/// ## Two rules no XSD can express
///
/// The DK validation subset annotates `DtTm` *"Only allowed for `SCTinst`"*, with
/// the usage rule *"Only UTC time format or local time with UTC offset format
/// can be used"*. Both are prose in the schema, so `xmllint` accepts a file
/// that breaks either and the bank rejects it on ingestion. `build()` returns
/// [`ValidationError::Requires`] instead:
///
/// - [`At`](Self::At) needs [`LocalInstrument::Inst`] on the same group. An
///   ordinary SCT settles some time during the banking day, so a time of day on
///   one instructs nothing.
/// - The timestamp needs a UTC offset — `2026-07-20T11:00:00Z` or
///   `2026-07-20T13:00:00+02:00`. See [`IsoDateTime::in_utc`].
///
/// # Examples
///
/// ```
/// use sepa::{CreditTransferGroup, IsoDate, IsoDateTime, validate_iban};
/// use sepa::pain001::LocalInstrument;
///
/// let iban = validate_iban("DE89370400440532013000")?;
///
/// // The ordinary case — a day.
/// let plain = CreditTransferGroup::new("Acme", &iban)
///     .execution_date(IsoDate::new(2026, 7, 20)?);
///
/// // A scheduled instant transfer — a day and a time.
/// let timed = CreditTransferGroup::new("Acme", &iban)
///     .local_instrument(LocalInstrument::Inst)
///     .execution_at("2026-07-20T11:00:00Z".parse::<IsoDateTime>()?);
/// # let _ = (plain, timed);
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum ExecutionMoment {
    /// `<ReqdExctnDt><Dt>2026-07-20</Dt></ReqdExctnDt>` — a banking day.
    On(IsoDate),
    /// `<ReqdExctnDt><DtTm>2026-07-20T11:00:00Z</DtTm></ReqdExctnDt>` — a moment.
    At(IsoDateTime),
}

impl ExecutionMoment {
    /// The day this group executes on, whichever form was given.
    #[must_use]
    pub const fn date(self) -> IsoDate {
        match self {
            Self::On(date) => date,
            Self::At(moment) => moment.date(),
        }
    }

    /// Whether this carries a time of day, and so needs the `DtTm` branch.
    #[must_use]
    pub const fn is_timed(self) -> bool {
        matches!(self, Self::At(_))
    }
}

impl From<IsoDate> for ExecutionMoment {
    fn from(date: IsoDate) -> Self {
        Self::On(date)
    }
}

impl From<IsoDateTime> for ExecutionMoment {
    fn from(moment: IsoDateTime) -> Self {
        Self::At(moment)
    }
}

/// The ISO 20022 element path a remittance violation should name.
///
/// `Ustrd` and `Strd` are alternatives inside one `RmtInf`, and an error that
/// says which branch failed is what points an operator at the right field.
pub(crate) fn remittance_field(remittance: &RemittanceInfo) -> &'static str {
    match remittance {
        RemittanceInfo::Unstructured(_) => "RmtInf/Ustrd",
        _ => "RmtInf/Strd",
    }
}

// ── CreditTransferEntry ───────────────────────────────────────────────────────

/// A single credit transfer in a pain.001 batch.
///
/// Construct with [`CreditTransferEntry::new`] and chain optional fields.
#[derive(Debug, Clone)]
#[non_exhaustive]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct CreditTransferEntry {
    /// Beneficiary name (`Cdtr/Nm`).
    pub creditor_name: String,
    /// Beneficiary IBAN (validated).
    pub creditor_iban: Iban,
    /// Beneficiary BIC. Uses `NOTPROVIDED` in XML when `None`.
    pub creditor_bic: Option<Bic>,
    /// Beneficiary postal address (`Cdtr/PstlAdr`).
    pub creditor_address: Option<PostalAddress>,
    /// Payment amount in **ct** (1/100 EUR). Must be positive.
    pub amount_ct: i64,
    /// Unique end-to-end reference (`EndToEndId`) visible on beneficiary's statement.
    pub end_to_end_id: String,
    /// Remittance information (`RmtInf`) — free text or a structured reference.
    pub remittance: Option<RemittanceInfo>,
    /// Ultimate debtor (`UltmtDbtr`) — who the money is really from.
    pub ultimate_debtor: Option<Party>,
    /// Ultimate creditor (`UltmtCdtr`) — who the money is really for.
    pub ultimate_creditor: Option<Party>,
    /// Purpose code (`Purp/Cd`), informational.
    pub purpose: Option<Purpose>,
}

impl CreditTransferEntry {
    /// Create a new credit transfer entry with required fields.
    ///
    /// Chain [`with_bic`](Self::with_bic) and [`with_description`](Self::with_description).
    pub fn new(
        creditor_name: impl Into<String>,
        creditor_iban: Iban,
        amount_ct: i64,
        end_to_end_id: impl Into<String>,
    ) -> Self {
        Self {
            creditor_name: creditor_name.into(),
            creditor_iban,
            amount_ct,
            end_to_end_id: end_to_end_id.into(),
            creditor_bic: None,
            creditor_address: None,
            remittance: None,
            ultimate_debtor: None,
            ultimate_creditor: None,
            purpose: None,
        }
    }

    /// Set the beneficiary's BIC (optional).
    #[must_use]
    pub fn with_bic(mut self, bic: Bic) -> Self {
        self.creditor_bic = Some(bic);
        self
    }

    /// Set the beneficiary's postal address (`Cdtr/PstlAdr`).
    ///
    /// Optional in the SEPA schemes, but asked for by some banks and by
    /// sanction screening. See [`PostalAddress`] for the
    /// structured/hybrid rules and the 15 November 2026 cut-over.
    #[must_use]
    pub fn with_creditor_address(mut self, address: PostalAddress) -> Self {
        self.creditor_address = Some(address);
        self
    }

    /// Set free-text remittance information (`RmtInf/Ustrd`), max 140 characters.
    ///
    /// This is the German *Verwendungszweck*: human-readable, but useless for
    /// automatic reconciliation. Prefer
    /// [`with_reference`](Self::with_reference) when you control the invoice.
    #[must_use]
    pub fn with_description(mut self, desc: impl Into<String>) -> Self {
        self.remittance = Some(RemittanceInfo::Unstructured(desc.into()));
        self
    }

    /// Set a structured ISO 11649 creditor reference (`RmtInf/Strd/CdtrRefInf`).
    ///
    /// Mutually exclusive with [`with_description`](Self::with_description) —
    /// the EPC permits one or the other, and the later call wins.
    #[must_use]
    pub fn with_reference(mut self, reference: crate::RfReference) -> Self {
        self.remittance = Some(RemittanceInfo::Structured(reference));
        self
    }

    /// Set remittance information directly.
    #[must_use]
    pub fn with_remittance(mut self, remittance: RemittanceInfo) -> Self {
        self.remittance = Some(remittance);
        self
    }

    /// Set the ultimate debtor (`UltmtDbtr`) — who the money is really from,
    /// when that differs from the account holder.
    #[must_use]
    pub fn with_ultimate_debtor(mut self, party: impl Into<Party>) -> Self {
        self.ultimate_debtor = Some(party.into());
        self
    }

    /// Set the ultimate creditor (`UltmtCdtr`) — who the money is really for.
    ///
    /// pain.001 allows this only at transaction level; the element does not
    /// exist at payment-information level.
    #[must_use]
    pub fn with_ultimate_creditor(mut self, party: impl Into<Party>) -> Self {
        self.ultimate_creditor = Some(party.into());
        self
    }

    /// Set the purpose code (`Purp/Cd`).
    ///
    /// Informational — see [`Purpose`] for why this is not [`CategoryPurpose`].
    ///
    /// [`CategoryPurpose`]: crate::CategoryPurpose
    #[must_use]
    pub fn with_purpose(mut self, purpose: Purpose) -> Self {
        self.purpose = Some(purpose);
        self
    }
}

// ── CreditTransferGroup ───────────────────────────────────────────────────────

/// One `PmtInf` block — a set of transfers sharing a debtor account, an
/// execution date and a local instrument.
///
/// A pain.001 message may carry several of these. That is the only way to put
/// transfers with **different execution dates**, different debtor accounts or a
/// mix of ordinary and instant transfers into a single file, rather than
/// submitting several files to the bank.
///
/// ## Examples
///
/// ```
/// use sepa::{CreditTransferEntry, CreditTransferGroup, IsoDate, validate_iban};
///
/// let iban = validate_iban("DE89370400440532013000")?;
/// let group = CreditTransferGroup::new("Acme GmbH", &iban)
///     .execution_date(IsoDate::new(2026, 7, 20)?)
///     .add_entry(CreditTransferEntry::new("Supplier AG", iban.clone(), 12_000, "E2E-1"));
/// assert_eq!(group.entry_count(), 1);
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct CreditTransferGroup {
    payment_info_id: Option<String>,
    debtor_name: String,
    debtor_iban: Iban,
    debtor_bic: Option<Bic>,
    debtor_address: Option<PostalAddress>,
    execution: ExecutionMoment,
    local_instrument: LocalInstrument,
    batch_booking: Option<bool>,
    category_purpose: Option<CategoryPurpose>,
    ultimate_debtor: Option<Party>,
    entries: Vec<CreditTransferEntry>,
}

impl CreditTransferGroup {
    /// A new payment group drawn on `debtor_iban`.
    pub fn new(debtor_name: impl Into<String>, debtor_iban: &Iban) -> Self {
        Self {
            payment_info_id: None,
            debtor_name: debtor_name.into(),
            debtor_iban: debtor_iban.clone(),
            debtor_bic: None,
            debtor_address: None,
            // Today, meaning "as soon as the bank can". A credit transfer has
            // no pre-notification period to respect — that is a direct debit
            // rule, and borrowing it here put every unset transfer five days
            // into the future for no reason anyone could state.
            execution: ExecutionMoment::On(IsoDate::today()),
            local_instrument: LocalInstrument::None,
            batch_booking: None,
            category_purpose: None,
            ultimate_debtor: None,
            entries: Vec::new(),
        }
    }

    /// Override the `PmtInfId`.
    ///
    /// Defaults to the message's `MsgId` for a single group, and to
    /// `MsgId-<n>` when there are several — truncated if needed to stay inside
    /// the 35-character limit.
    #[must_use]
    pub fn payment_info_id(mut self, id: impl Into<String>) -> Self {
        self.payment_info_id = Some(id.into());
        self
    }

    /// Set the requested execution date (`ReqdExctnDt`).
    ///
    /// Defaults to today — "as soon as the bank can". The date is an
    /// [`IsoDate`], so a malformed one cannot reach the batch; it is calendar
    /// arithmetic, though, so a date landing on a weekend or a TARGET2 holiday
    /// is the caller's to avoid.
    #[must_use]
    pub fn execution_date(mut self, date: IsoDate) -> Self {
        self.execution = ExecutionMoment::On(date);
        self
    }

    /// Set the requested execution **moment** — a day and a time.
    ///
    /// This is the DK's *terminierte Echtzeitüberweisung*: a scheduled instant
    /// transfer due at a stated time. Three things have to line up, and
    /// `build()` checks all three — see [`ExecutionMoment`]:
    ///
    /// 1. `pain.001.001.09`, the only schema whose `ReqdExctnDt` is a
    ///    date/time choice;
    /// 2. [`local_instrument(LocalInstrument::Inst)`](Self::local_instrument)
    ///    on this group;
    /// 3. a UTC offset on `moment` — `"…T11:00:00Z"`, or
    ///    [`IsoDateTime::in_utc`].
    #[must_use]
    pub fn execution_at(mut self, moment: IsoDateTime) -> Self {
        self.execution = ExecutionMoment::At(moment);
        self
    }

    /// When this group is to execute, in whichever form it was set.
    #[must_use]
    pub const fn execution(&self) -> ExecutionMoment {
        self.execution
    }

    /// The day this group is to execute on, whether or not a time was set.
    #[must_use]
    pub const fn requested_execution_date(&self) -> IsoDate {
        self.execution.date()
    }

    /// Set the debtor's BIC (`DbtrAgt`).
    #[must_use]
    pub fn debtor_bic(mut self, bic: Bic) -> Self {
        self.debtor_bic = Some(bic);
        self
    }

    /// Set the debtor's postal address (`Dbtr/PstlAdr`).
    ///
    /// The address belongs to the account holder, so it lives on the group
    /// rather than on each transfer. See
    /// [`PostalAddress`].
    #[must_use]
    pub fn debtor_address(mut self, address: PostalAddress) -> Self {
        self.debtor_address = Some(address);
        self
    }

    /// Set the local instrument for this group.
    ///
    /// [`LocalInstrument::Inst`] marks the group as SEPA Instant. Note the
    /// schema is chosen once for the whole message — see
    /// [`Pain001Builder::schema`].
    #[must_use]
    pub fn local_instrument(mut self, li: LocalInstrument) -> Self {
        self.local_instrument = li;
        self
    }

    /// Request batch booking (`BtchBookg`).
    ///
    /// `true` asks for one aggregate entry on the statement, `false` for one
    /// entry per transaction. Omitted by default, which defers to the agreement
    /// with the bank — there is no scheme-wide default, and German banks treat
    /// an absent value as `true`. `false` takes effect only where a
    /// single-entry agreement is in place.
    #[must_use]
    pub fn batch_booking(mut self, batch: bool) -> Self {
        self.batch_booking = Some(batch);
        self
    }

    /// Set the category purpose (`PmtTpInf/CtgyPurp`) for this group.
    ///
    /// Unlike a purpose code, this may trigger special handling by the banks.
    /// It belongs at one level only, so setting it here excludes setting it per
    /// transaction.
    #[must_use]
    pub fn category_purpose(mut self, purpose: CategoryPurpose) -> Self {
        self.category_purpose = Some(purpose);
        self
    }

    /// Set the ultimate debtor for the whole group (`PmtInf/UltmtDbtr`).
    ///
    /// Mutually exclusive with the per-entry ultimate debtor: the DK rules
    /// require one level or the other, never both.
    #[must_use]
    pub fn ultimate_debtor(mut self, party: impl Into<Party>) -> Self {
        self.ultimate_debtor = Some(party.into());
        self
    }

    /// Add a credit transfer to this group.
    #[must_use]
    pub fn add_entry(mut self, entry: CreditTransferEntry) -> Self {
        self.entries.push(entry);
        self
    }

    /// Add several credit transfers.
    #[must_use]
    pub fn add_entries(mut self, entries: impl IntoIterator<Item = CreditTransferEntry>) -> Self {
        self.entries.extend(entries);
        self
    }

    /// Number of transfers in this group.
    #[must_use]
    pub fn entry_count(&self) -> usize {
        self.entries.len()
    }

    /// Total amount in ct across this group, saturating on overflow.
    #[must_use]
    pub fn total_ct(&self) -> i64 {
        self.entries
            .iter()
            .fold(0i64, |acc, e| acc.saturating_add(e.amount_ct))
    }
}

// ── Builder ───────────────────────────────────────────────────────────────────

/// Builder for an ISO 20022 pain.001 (SEPA Credit Transfer) message.
///
/// A message carries one or more [`CreditTransferGroup`]s, each becoming a
/// `PmtInf` block.
#[derive(Debug, Clone)]
pub struct Pain001Builder {
    initiating_party: String,
    msg_id: String,
    created_at: Option<IsoDateTime>,
    schema: CreditTransferSchema,
    charset: CharsetPolicy,
    groups: Vec<CreditTransferGroup>,
}

impl Pain001Builder {
    /// A new message initiated by `initiating_party`.
    pub fn new(initiating_party: impl Into<String>) -> Self {
        Self {
            initiating_party: initiating_party.into(),
            msg_id: crate::pain008::default_msg_id("sct"),
            created_at: None,
            schema: CreditTransferSchema::default(),
            charset: CharsetPolicy::default(),
            groups: Vec::new(),
        }
    }

    /// Set the `MsgId` (`Max35Text`).
    ///
    /// A `MsgId` is how a bank de-duplicates submissions: two files sharing one
    /// are a duplicate, and the second is rejected — or, worse, accepted and
    /// silently discarded. **Set it from your own persistent sequence.**
    ///
    /// The default is only a placeholder. It is unique within one process, so
    /// building several messages in a loop cannot collide, but it does not
    /// survive a restart and carries no meaning a bank or an auditor can use.
    #[must_use]
    pub fn msg_id(mut self, id: impl Into<String>) -> Self {
        self.msg_id = id.into();
        self
    }

    /// Pin the creation timestamp (`CreDtTm`), ISO 8601.
    ///
    /// Defaults to the current time. Set it explicitly to make output
    /// byte-reproducible — for golden-file tests, or to regenerate a submitted
    /// file identically for an audit.
    #[must_use]
    pub fn created_at(mut self, timestamp: IsoDateTime) -> Self {
        self.created_at = Some(timestamp);
        self
    }

    /// Select the pain.001 schema version (default
    /// [`CreditTransferSchema::IsoV9`]).
    #[must_use]
    pub fn schema(mut self, schema: CreditTransferSchema) -> Self {
        self.schema = schema;
        self
    }

    /// Set how text outside the SEPA character set is handled.
    #[must_use]
    pub fn charset(mut self, policy: CharsetPolicy) -> Self {
        self.charset = policy;
        self
    }

    /// Add a payment group (`PmtInf`).
    #[must_use]
    pub fn add_group(mut self, group: CreditTransferGroup) -> Self {
        self.groups.push(group);
        self
    }

    /// Number of payment groups.
    #[must_use]
    pub fn group_count(&self) -> usize {
        self.groups.len()
    }

    /// Total number of transactions across every group — the `GrpHdr/NbOfTxs`.
    #[must_use]
    pub fn entry_count(&self) -> usize {
        self.groups
            .iter()
            .map(CreditTransferGroup::entry_count)
            .sum()
    }

    /// Total amount in ct across every group, saturating on overflow.
    #[must_use]
    pub fn total_ct(&self) -> i64 {
        self.groups
            .iter()
            .fold(0i64, |acc, g| acc.saturating_add(g.total_ct()))
    }

    /// The effective `PmtInfId` for group `index`.
    fn payment_info_id(&self, index: usize) -> String {
        if let Some(id) = self
            .groups
            .get(index)
            .and_then(|g| g.payment_info_id.clone())
        {
            return id;
        }
        if self.groups.len() <= 1 {
            return self.msg_id.clone();
        }
        // Several groups need distinct identifiers. Suffix the MsgId, trimming
        // it first so the result still fits Max35Text.
        let suffix = format!("-{}", index + 1);
        let keep = MAX_ID_LEN.saturating_sub(suffix.chars().count());
        format!("{}{suffix}", truncate_chars(&self.msg_id, keep))
    }

    /// Refuse a postal address on a schema whose `PstlAdr` cannot hold one.
    fn check_address_supported(&self, feature: &'static str) -> Result<(), ValidationError> {
        if self.schema.supports_postal_address() {
            Ok(())
        } else {
            Err(ValidationError::UnsupportedBySchema {
                feature,
                schema: self.schema.message_id(),
            })
        }
    }

    /// Validate the message without producing XML.
    ///
    /// # Errors
    ///
    /// A [`BuildError`] naming both the broken rule ([`ValidationError`]) and
    /// the group and transaction it belongs to.
    pub fn validate(&self) -> Result<(), BuildError> {
        // `PmtInf` is 1..n at message level; `CdtTrfTxInf` / `DrctDbtTxInf` are
        // 1..n inside each group, and the loop below reports which group is
        // empty rather than blaming the message for it.
        if self.groups.is_empty() {
            return Err(BuildError::message(ValidationError::EmptyBatch));
        }
        let msg = Location::message();
        check_id("GrpHdr/MsgId", &self.msg_id).at(msg)?;
        check_name(
            "InitgPty/Nm",
            &self
                .charset
                .apply("InitgPty/Nm", &self.initiating_party)
                .at(msg)?,
        )
        .at(msg)?;

        let mut total: i64 = 0;
        let mut seen_ids = std::collections::BTreeSet::new();
        for (i, g) in self.groups.iter().enumerate() {
            self.validate_group(i, g, &mut seen_ids, &mut total)?;
        }
        Ok(())
    }

    /// The rules that tie a group's local instrument to its execution moment.
    ///
    /// None of these are expressible in XSD, so a file that breaks them
    /// validates cleanly against the schema and is rejected on ingestion.
    fn check_instrument_and_timing(
        g: &CreditTransferGroup,
        schema: CreditTransferSchema,
    ) -> Result<(), ValidationError> {
        let unsupported = |feature| ValidationError::UnsupportedBySchema {
            feature,
            schema: schema.message_id(),
        };
        // `LclInstrm` does not exist in every schema, so an SCT Inst group on
        // the DK schema would silently produce an invalid file.
        if g.local_instrument == LocalInstrument::Inst && !schema.supports_local_instrument() {
            return Err(unsupported("PmtTpInf/LclInstrm (SCT Inst)"));
        }
        // A timed execution exists only where `ReqdExctnDt` is a choice…
        let ExecutionMoment::At(moment) = g.execution else {
            return Ok(());
        };
        if !schema.supports_execution_time() {
            return Err(unsupported("ReqdExctnDt/DtTm (timed execution)"));
        }
        // …and only for SCT Inst. The DK validation subset annotates `DtTm`
        // "Only allowed for SCTinst": an ordinary SCT settles some time during
        // the banking day, so a time of day on one instructs nothing.
        if g.local_instrument != LocalInstrument::Inst {
            return Err(ValidationError::Requires {
                feature: "ReqdExctnDt/DtTm (timed execution)",
                requires: "PmtTpInf/LclInstrm = INST (SCT Inst)",
            });
        }
        // The same annotation carries the usage rule "Only UTC time format or
        // local time with UTC offset format can be used" — a bare local time
        // does not name an instant, and naming one is the whole point.
        if moment.offset_minutes().is_none() {
            return Err(ValidationError::Requires {
                feature: "ReqdExctnDt/DtTm (timed execution)",
                requires: "a UTC offset — see IsoDateTime::in_utc",
            });
        }
        Ok(())
    }

    /// Validate one `PmtInf` and add its amounts to the running control sum.
    fn validate_group(
        &self,
        i: usize,
        g: &CreditTransferGroup,
        seen_ids: &mut std::collections::BTreeSet<String>,
        total: &mut i64,
    ) -> Result<(), BuildError> {
        {
            let at = Location::group(i);
            if g.entries.is_empty() {
                return Err(BuildError::group(i, ValidationError::EmptyBatch));
            }
            // `PmtInfId` is what a bank echoes back in pain.002 and in a camt
            // `Btch` block, so two groups sharing one make the booking
            // unattributable — and duplicate detection may drop the second.
            let id = self.payment_info_id(i);
            check_id("PmtInf/PmtInfId", &id).at(at)?;
            if !seen_ids.insert(id.clone()) {
                return Err(BuildError::group(
                    i,
                    ValidationError::Duplicate {
                        field: "PmtInf/PmtInfId",
                        value: id,
                    },
                ));
            }
            check_name(
                "Dbtr/Nm",
                &self.charset.apply("Dbtr/Nm", &g.debtor_name).at(at)?,
            )
            .at(at)?;
            Self::check_instrument_and_timing(g, self.schema).at(at)?;
            if let Some(a) = &g.debtor_address {
                self.check_address_supported("Dbtr/PstlAdr").at(at)?;
                a.validate(self.charset).at(at)?;
            }
            if let Some(p) = &g.category_purpose {
                p.validate("PmtTpInf/CtgyPurp/Cd").at(at)?;
            }
            if let Some(p) = &g.ultimate_debtor {
                p.validate("PmtInf/UltmtDbtr", self.charset).at(at)?;
            }

            for (j, e) in g.entries.iter().enumerate() {
                let at = Location::transaction(i, j);
                // The DK forbids the same ultimate party at both levels.
                if g.ultimate_debtor.is_some() && e.ultimate_debtor.is_some() {
                    return Err(BuildError {
                        location: at,
                        kind: ValidationError::ConflictingLevels { field: "UltmtDbtr" },
                    });
                }
                check_id("CdtTrfTxInf/PmtId/EndToEndId", &e.end_to_end_id).at(at)?;
                check_amount("CdtTrfTxInf/Amt/InstdAmt", e.amount_ct).at(at)?;
                check_name(
                    "Cdtr/Nm",
                    &self.charset.apply("Cdtr/Nm", &e.creditor_name).at(at)?,
                )
                .at(at)?;
                if let Some(a) = &e.creditor_address {
                    self.check_address_supported("Cdtr/PstlAdr").at(at)?;
                    a.validate(self.charset).at(at)?;
                }
                if let Some(p) = &e.ultimate_debtor {
                    p.validate("CdtTrfTxInf/UltmtDbtr", self.charset).at(at)?;
                }
                if let Some(p) = &e.ultimate_creditor {
                    p.validate("CdtTrfTxInf/UltmtCdtr", self.charset).at(at)?;
                }
                if let Some(p) = &e.purpose {
                    p.validate("CdtTrfTxInf/Purp/Cd").at(at)?;
                }
                if let Some(r) = &e.remittance {
                    r.validate(remittance_field(r), self.charset).at(at)?;
                }
                *total = total.checked_add(e.amount_ct).ok_or(BuildError {
                    location: at,
                    kind: ValidationError::ControlSumOverflow,
                })?;
            }
        }
        Ok(())
    }

    /// Validate the message and generate the pain.001 XML.
    ///
    /// # Errors
    ///
    /// See [`validate`](Self::validate).
    ///
    /// # Examples
    ///
    /// ```
    /// use sepa::{CreditTransferEntry, CreditTransferGroup, Pain001Builder, validate_iban};
    ///
    /// let iban = validate_iban("DE89370400440532013000")?;
    /// let xml = Pain001Builder::new("Acme GmbH")
    ///     .msg_id("CT-001")
    ///     .add_group(
    ///         CreditTransferGroup::new("Acme GmbH", &iban)
    ///             .execution_date("2026-07-20".parse()?)
    ///             .add_entry(CreditTransferEntry::new("Payee", iban.clone(), 100, "E2E-1")),
    ///     )
    ///     .build()?;
    /// assert!(xml.contains("<NbOfTxs>1</NbOfTxs>"));
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn build(&self) -> Result<String, BuildError> {
        self.validate()?;
        let mut buf = String::with_capacity(850 + self.entry_count() * 420);
        // Writing into a String is infallible.
        let _ = self.write_xml_to(&mut buf);
        Ok(buf)
    }

    /// Validate and stream the pain.001 XML to an [`io::Write`](std::io::Write).
    ///
    /// Validation runs before anything is written, so a rejected message leaves
    /// the writer untouched.
    ///
    /// # Errors
    ///
    /// [`WriteError::Validation`] or [`WriteError::Io`].
    pub fn write_to<W: std::io::Write>(&self, w: &mut W) -> Result<(), WriteError> {
        self.validate()?;
        let mut bridge = crate::xml_util::IoWriterBridge {
            inner: w,
            error: None,
        };
        if self.write_xml_to(&mut bridge).is_err() {
            return Err(WriteError::Io(bridge.error.unwrap_or_else(|| {
                std::io::Error::other("XML serialisation failed")
            })));
        }
        Ok(())
    }

    /// Serialise. Private: callers go through `build` or `write_to`, which validate.
    fn write_xml_to<W: std::fmt::Write>(&self, w: &mut W) -> std::fmt::Result {
        use crate::xml_util::write_escaped;

        let now = self.created_at.unwrap_or_else(IsoDateTime::now);
        let namespace = self.schema.namespace();
        let initiating = self.charset.render(&self.initiating_party);

        w.write_str("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n")?;
        writeln!(w, "<Document xmlns=\"{namespace}\">")?;
        w.write_str("  <CstmrCdtTrfInitn>\n    <GrpHdr>\n      <MsgId>")?;
        write_escaped(w, &self.msg_id)?;
        write!(w, "</MsgId>\n      <CreDtTm>{now}</CreDtTm>\n")?;
        // GrpHdr totals span every group.
        write!(
            w,
            "      <NbOfTxs>{}</NbOfTxs>\n      <CtrlSum>{}</CtrlSum>\n",
            self.entry_count(),
            ct_to_eur_str(self.total_ct())
        )?;
        w.write_str("      <InitgPty><Nm>")?;
        write_escaped(w, &initiating)?;
        w.write_str("</Nm></InitgPty>\n    </GrpHdr>\n")?;

        for (i, g) in self.groups.iter().enumerate() {
            self.write_group(w, g, &self.payment_info_id(i))?;
        }

        w.write_str("  </CstmrCdtTrfInitn>\n</Document>")
    }

    /// Write one `PmtInf` block, in XSD sequence order.
    fn write_group<W: std::fmt::Write>(
        &self,
        w: &mut W,
        g: &CreditTransferGroup,
        payment_info_id: &str,
    ) -> std::fmt::Result {
        use crate::xml_util::write_escaped;

        let bic_el = self.schema.bic_element();
        let debtor_name = self.charset.render(&g.debtor_name);

        w.write_str("    <PmtInf>\n      <PmtInfId>")?;
        write_escaped(w, payment_info_id)?;
        w.write_str("</PmtInfId>\n      <PmtMtd>TRF</PmtMtd>\n")?;
        if let Some(batch) = g.batch_booking {
            writeln!(w, "      <BtchBookg>{batch}</BtchBookg>")?;
        }
        write!(
            w,
            "      <NbOfTxs>{}</NbOfTxs>\n      <CtrlSum>{}</CtrlSum>\n",
            g.entry_count(),
            ct_to_eur_str(g.total_ct())
        )?;
        w.write_str("      <PmtTpInf>\n        <SvcLvl><Cd>SEPA</Cd></SvcLvl>\n")?;
        if g.local_instrument == LocalInstrument::Inst {
            w.write_str("        <LclInstrm><Cd>INST</Cd></LclInstrm>\n")?;
        }
        if let Some(p) = &g.category_purpose {
            writeln!(w, "        <CtgyPurp><Cd>{}</Cd></CtgyPurp>", p.as_code())?;
        }
        w.write_str("      </PmtTpInf>\n")?;

        // pain.001.001.09 types ReqdExctnDt as a date/time choice; the older
        // schemas take a bare ISODate.
        match (self.schema.supports_execution_time(), g.execution) {
            (true, ExecutionMoment::On(date)) => {
                writeln!(w, "      <ReqdExctnDt><Dt>{date}</Dt></ReqdExctnDt>")?;
            }
            (true, ExecutionMoment::At(moment)) => {
                writeln!(w, "      <ReqdExctnDt><DtTm>{moment}</DtTm></ReqdExctnDt>")?;
            }
            // `validate` has already refused a timed moment here.
            (false, moment) => {
                writeln!(w, "      <ReqdExctnDt>{}</ReqdExctnDt>", moment.date())?;
            }
        }

        w.write_str("      <Dbtr><Nm>")?;
        write_escaped(w, &debtor_name)?;
        // XSD sequence inside PartyIdentification: Nm, PstlAdr, Id, …
        w.write_str("</Nm>")?;
        if let Some(address) = &g.debtor_address {
            address.write_xml(w, self.charset)?;
        }
        w.write_str("</Dbtr>\n")?;
        writeln!(
            w,
            "      <DbtrAcct><Id><IBAN>{}</IBAN></Id></DbtrAcct>",
            g.debtor_iban.as_str()
        )?;
        // DbtrAgt is mandatory; with no BIC the EPC "IBAN only" form applies.
        w.write_str("      <DbtrAgt><FinInstnId>")?;
        match &g.debtor_bic {
            Some(bic) => write!(w, "<{bic_el}>{}</{bic_el}>", bic.as_str())?,
            None => w.write_str("<Othr><Id>NOTPROVIDED</Id></Othr>")?,
        }
        w.write_str("</FinInstnId></DbtrAgt>\n")?;

        if let Some(p) = &g.ultimate_debtor {
            p.write_xml(w, "UltmtDbtr", "      ", self.charset)?;
        }
        w.write_str("      <ChrgBr>SLEV</ChrgBr>\n")?;

        for entry in &g.entries {
            self.write_transaction(w, entry)?;
        }
        w.write_str("    </PmtInf>\n")
    }

    fn write_transaction<W: std::fmt::Write>(
        &self,
        w: &mut W,
        e: &CreditTransferEntry,
    ) -> std::fmt::Result {
        use crate::xml_util::{write_escaped, write_eur};

        let bic_el = self.schema.bic_element();
        let name = self.charset.render(&e.creditor_name);

        w.write_str("    <CdtTrfTxInf>\n      <PmtId>\n        <EndToEndId>")?;
        write_escaped(w, &e.end_to_end_id)?;
        w.write_str("</EndToEndId>\n      </PmtId>\n      <Amt><InstdAmt Ccy=\"EUR\">")?;
        write_eur(w, e.amount_ct)?;
        w.write_str("</InstdAmt></Amt>\n")?;

        // XSD sequence: UltmtDbtr precedes the creditor block, UltmtCdtr follows
        // CdtrAcct, and Purp sits between UltmtCdtr and RmtInf.
        if let Some(p) = &e.ultimate_debtor {
            p.write_xml(w, "UltmtDbtr", "      ", self.charset)?;
        }

        // CdtrAgt is optional for SCT. The EPC guidelines say that when the BIC
        // is unknown the element is simply omitted — and pain.001.003.03 makes
        // that structural, since its CdtrAgt type has a mandatory BIC and no
        // Othr branch, leaving no way to express "not provided".
        if let Some(bic) = &e.creditor_bic {
            writeln!(
                w,
                "      <CdtrAgt><FinInstnId><{bic_el}>{}</{bic_el}></FinInstnId></CdtrAgt>",
                bic.as_str()
            )?;
        }

        w.write_str("      <Cdtr><Nm>")?;
        write_escaped(w, &name)?;
        w.write_str("</Nm>")?;
        if let Some(address) = &e.creditor_address {
            address.write_xml(w, self.charset)?;
        }
        w.write_str("</Cdtr>\n      <CdtrAcct><Id><IBAN>")?;
        w.write_str(e.creditor_iban.as_str())?;
        w.write_str("</IBAN></Id></CdtrAcct>\n")?;

        if let Some(p) = &e.ultimate_creditor {
            p.write_xml(w, "UltmtCdtr", "      ", self.charset)?;
        }
        if let Some(purpose) = &e.purpose {
            writeln!(w, "      <Purp><Cd>{}</Cd></Purp>", purpose.as_code())?;
        }

        if let Some(remittance) = &e.remittance {
            // `Strd` is emitted minified: the EPC caps the whole block at 140
            // characters including tags, and pretty-printing alone overruns it.
            remittance.write_xml(w, "      ", self.charset)?;
        }

        w.write_str("    </CdtTrfTxInf>\n")
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::iban::validate_iban;
    use crate::validate::{CharsetPolicy, Location, ValidationError};

    fn d(s: &str) -> IsoDate {
        s.parse().unwrap()
    }

    fn de_iban() -> Iban {
        validate_iban("DE89370400440532013000").unwrap()
    }
    fn nl_iban() -> Iban {
        validate_iban("NL91ABNA0417164300").unwrap()
    }
    fn entry(amount_ct: i64) -> CreditTransferEntry {
        CreditTransferEntry::new("Max Mustermann", nl_iban(), amount_ct, "E2E-001")
    }
    /// A one-group message with everything `build` requires.
    fn one_group(name: &str) -> Pain001Builder {
        Pain001Builder::new(name).msg_id("CT-001").add_group(
            CreditTransferGroup::new(name, &de_iban())
                .execution_date(d("2026-07-20"))
                .add_entry(entry(12_000)),
        )
    }

    #[test]
    fn basic_structure() {
        let xml = one_group("Acme GmbH").build().unwrap();
        assert!(xml.contains("urn:iso:std:iso:20022:tech:xsd:pain.001.001.09"));
        assert!(xml.contains("<MsgId>CT-001</MsgId>"));
        assert!(xml.contains("<PmtMtd>TRF</PmtMtd>"));
        assert!(xml.contains("<InstdAmt Ccy=\"EUR\">120.00</InstdAmt>"));
        assert!(xml.contains("<ChrgBr>SLEV</ChrgBr>"));
        // pain.001.001.09 wraps the date in a <Dt> choice child.
        assert!(xml.contains("<ReqdExctnDt><Dt>2026-07-20</Dt></ReqdExctnDt>"));
    }

    #[test]
    fn several_groups_carry_their_own_dates_and_totals() {
        let xml = Pain001Builder::new("Acme GmbH")
            .msg_id("CT-MULTI")
            .add_group(
                CreditTransferGroup::new("Acme GmbH", &de_iban())
                    .execution_date(d("2026-07-20"))
                    .add_entry(entry(10_000)),
            )
            .add_group(
                CreditTransferGroup::new("Acme GmbH", &nl_iban())
                    .execution_date(d("2026-07-25"))
                    .add_entry(entry(5_000))
                    .add_entry(entry(2_500)),
            )
            .build()
            .unwrap();

        assert_eq!(xml.matches("<PmtInf>").count(), 2);
        // Different execution dates in one file — impossible with one PmtInf.
        assert!(xml.contains("<Dt>2026-07-20</Dt>"));
        assert!(xml.contains("<Dt>2026-07-25</Dt>"));
        // GrpHdr totals span every group; each PmtInf carries its own.
        assert!(xml.contains("<NbOfTxs>3</NbOfTxs>"));
        assert!(xml.contains("<CtrlSum>175.00</CtrlSum>"));
        assert!(xml.contains("<NbOfTxs>1</NbOfTxs>"));
        assert!(xml.contains("<CtrlSum>100.00</CtrlSum>"));
        assert!(xml.contains("<NbOfTxs>2</NbOfTxs>"));
        assert!(xml.contains("<CtrlSum>75.00</CtrlSum>"));
    }

    #[test]
    fn payment_info_ids_are_unique_and_within_max35text() {
        let msg_id = "M".repeat(35);
        let b = Pain001Builder::new("Acme").msg_id(&msg_id);
        let b = (0..3).fold(b, |b, _| {
            b.add_group(
                CreditTransferGroup::new("Acme", &de_iban())
                    .execution_date(d("2026-07-20"))
                    .add_entry(entry(100)),
            )
        });
        let xml = b.build().unwrap();

        let ids: Vec<&str> = xml
            .split("<PmtInfId>")
            .skip(1)
            .map(|c| c.split('<').next().unwrap())
            .collect();
        assert_eq!(ids.len(), 3);
        for id in &ids {
            assert!(id.chars().count() <= 35, "{id} exceeds Max35Text");
        }
        let unique: std::collections::BTreeSet<_> = ids.iter().collect();
        assert_eq!(unique.len(), 3, "PmtInfId must be unique per group");
    }

    #[test]
    fn two_groups_may_not_share_a_payment_info_id() {
        // A bank echoes PmtInfId back in pain.002 and in the camt `Btch` block.
        // Two groups sharing one make a booking unattributable, and duplicate
        // detection may drop the second outright.
        let g = |id: &str| {
            CreditTransferGroup::new("Acme", &de_iban())
                .payment_info_id(id)
                .execution_date(d("2026-07-20"))
                .add_entry(entry(100))
        };
        let err = Pain001Builder::new("Acme")
            .msg_id("CT-DUP")
            .add_group(g("PMT-1"))
            .add_group(g("PMT-1"))
            .build()
            .unwrap_err();
        assert_eq!(err.location, Location::group(1));
        assert_eq!(
            err.kind,
            ValidationError::Duplicate {
                field: "PmtInf/PmtInfId",
                value: "PMT-1".to_owned(),
            }
        );
        // Distinct identifiers, and the generated defaults, are fine.
        assert!(
            Pain001Builder::new("Acme")
                .msg_id("CT-OK")
                .add_group(g("PMT-1"))
                .add_group(g("PMT-2"))
                .build()
                .is_ok()
        );
    }

    #[test]
    fn the_generated_message_id_is_unique_per_message() {
        // Regression: the default was `sct-<epoch seconds>`, so two messages
        // built in the same second shared a MsgId — which is precisely the key
        // a bank de-duplicates submissions by.
        let ids: std::collections::BTreeSet<String> = (0..64)
            .map(|_| Pain001Builder::new("Acme").msg_id.clone())
            .collect();
        assert_eq!(ids.len(), 64, "generated MsgIds collided");
        for id in &ids {
            assert!(
                crate::validate::check_id("GrpHdr/MsgId", id).is_ok(),
                "{id}"
            );
        }
    }

    #[test]
    fn single_group_reuses_the_msg_id_verbatim() {
        let xml = one_group("Acme").build().unwrap();
        assert!(xml.contains("<PmtInfId>CT-001</PmtInfId>"));
    }

    #[test]
    fn legacy_dk_schema_emits_a_bare_date_and_bic() {
        let xml = Pain001Builder::new("Test")
            .schema(CreditTransferSchema::DkV2_7)
            .msg_id("CT-DK")
            .add_group(
                CreditTransferGroup::new("Test", &de_iban())
                    .execution_date(d("2026-07-20"))
                    .debtor_bic("COBADEFF".parse().unwrap())
                    .add_entry(entry(5_000).with_bic("ABNANL2A".parse().unwrap())),
            )
            .build()
            .unwrap();
        assert!(xml.contains("pain.001.003.03"));
        assert!(xml.contains("<ReqdExctnDt>2026-07-20</ReqdExctnDt>"));
        assert!(xml.contains("<BIC>COBADEFF</BIC>"));
        assert!(!xml.contains("BICFI"));
    }

    #[test]
    fn iban_only_agents_and_omitted_creditor_agent() {
        let xml = one_group("Test").build().unwrap();
        assert!(!xml.contains("<CdtrAgt>"), "EPC omits CdtrAgt with no BIC");
        assert!(xml.contains("<DbtrAgt><FinInstnId><Othr><Id>NOTPROVIDED</Id></Othr>"));
        assert!(!xml.contains("NOTPROVIDED</BIC"));
    }

    #[test]
    fn sct_instant_marks_the_group() {
        let xml = Pain001Builder::new("Acme")
            .msg_id("CT-INST")
            .add_group(
                CreditTransferGroup::new("Acme", &de_iban())
                    .local_instrument(LocalInstrument::Inst)
                    .execution_date(d("2026-07-20"))
                    .add_entry(entry(5_000)),
            )
            .build()
            .unwrap();
        assert!(xml.contains("pain.001.001.09"));
        assert!(xml.contains("<LclInstrm><Cd>INST</Cd></LclInstrm>"));
    }

    #[test]
    fn postal_addresses_sit_inside_the_party_after_the_name() {
        // PartyIdentification is a sequence: Nm, then PstlAdr. Emitting them the
        // other way round is schema-invalid even though both elements are legal.
        let xml = Pain001Builder::new("Acme GmbH")
            .msg_id("CT-ADR")
            .add_group(
                CreditTransferGroup::new("Acme GmbH", &de_iban())
                    .execution_date(d("2026-07-20"))
                    .debtor_address(
                        crate::PostalAddress::new("Berlin", "DE")
                            .unwrap()
                            .street("Unter den Linden")
                            .building_number("77")
                            .post_code("10117"),
                    )
                    .add_entry(entry(12_000).with_creditor_address(
                        crate::PostalAddress::new("Amsterdam", "NL").unwrap(),
                    )),
            )
            .build()
            .unwrap();

        assert!(xml.contains(
            "<Dbtr><Nm>Acme GmbH</Nm><PstlAdr><StrtNm>Unter den Linden</StrtNm>\
             <BldgNb>77</BldgNb><PstCd>10117</PstCd><TwnNm>Berlin</TwnNm>\
             <Ctry>DE</Ctry></PstlAdr></Dbtr>"
        ));
        assert!(xml.contains(
            "<Cdtr><Nm>Max Mustermann</Nm><PstlAdr><TwnNm>Amsterdam</TwnNm>\
             <Ctry>NL</Ctry></PstlAdr></Cdtr>"
        ));
    }

    #[test]
    fn an_address_on_a_schema_without_one_is_rejected() {
        // pain.001.003.03's PostalAddressSEPA holds only Ctry and two AdrLines,
        // so a town and a street have nowhere to go.
        let err = Pain001Builder::new("Acme")
            .schema(CreditTransferSchema::DkV2_7)
            .msg_id("CT-DK-ADR")
            .add_group(
                CreditTransferGroup::new("Acme", &de_iban())
                    .execution_date(d("2026-07-20"))
                    .debtor_address(crate::PostalAddress::new("Berlin", "DE").unwrap())
                    .add_entry(entry(100)),
            )
            .build()
            .unwrap_err();
        assert_eq!(
            err.kind,
            ValidationError::UnsupportedBySchema {
                feature: "Dbtr/PstlAdr",
                schema: "pain.001.003.03",
            }
        );
        assert_eq!(err.location, Location::group(0));
    }

    #[test]
    fn address_violations_name_the_element_and_the_transaction() {
        let err = Pain001Builder::new("Acme")
            .msg_id("CT-ADR-BAD")
            .add_group(
                CreditTransferGroup::new("Acme", &de_iban())
                    .execution_date(d("2026-07-20"))
                    .add_entry(entry(100))
                    .add_entry(
                        entry(100).with_creditor_address(
                            crate::PostalAddress::new("Berlin", "DE")
                                .unwrap()
                                .post_code("1".repeat(17)),
                        ),
                    ),
            )
            .build()
            .unwrap_err();
        assert_eq!(err.location, Location::transaction(0, 1));
        assert!(matches!(
            err.kind,
            ValidationError::TooLong {
                field: "PstlAdr/PstCd",
                max: 16,
                ..
            }
        ));
    }

    #[test]
    fn batch_booking_and_category_purpose_are_group_level() {
        let xml = Pain001Builder::new("Acme")
            .msg_id("CT-OPT")
            .add_group(
                CreditTransferGroup::new("Acme", &de_iban())
                    .execution_date(d("2026-07-20"))
                    .batch_booking(true)
                    .category_purpose(CategoryPurpose::Sala)
                    .add_entry(entry(100)),
            )
            .build()
            .unwrap();
        assert!(xml.contains("<BtchBookg>true</BtchBookg>"));
        assert!(xml.contains("<CtgyPurp><Cd>SALA</Cd></CtgyPurp>"));
    }

    #[test]
    fn batch_booking_is_omitted_unless_set() {
        // There is no scheme-wide default; omitting defers to the bank agreement.
        assert!(!one_group("Acme").build().unwrap().contains("BtchBookg"));
    }

    #[test]
    fn ultimate_debtor_cannot_be_set_at_both_levels() {
        let b = Pain001Builder::new("Acme").msg_id("CT-ULT").add_group(
            CreditTransferGroup::new("Acme", &de_iban())
                .execution_date(d("2026-07-20"))
                .ultimate_debtor(Party::new("Gruppe"))
                .add_entry(entry(100).with_ultimate_debtor(Party::new("Transaktion"))),
        );
        assert_eq!(
            b.build(),
            Err(BuildError::transaction(
                0,
                0,
                ValidationError::ConflictingLevels { field: "UltmtDbtr" }
            ))
        );
    }

    #[test]
    fn empty_message_and_empty_group_are_both_rejected() {
        assert_eq!(
            Pain001Builder::new("Acme").msg_id("E").build(),
            Err(BuildError::message(ValidationError::EmptyBatch))
        );
        assert_eq!(
            Pain001Builder::new("Acme")
                .msg_id("E")
                .add_group(CreditTransferGroup::new("Acme", &de_iban()))
                .build(),
            Err(BuildError::group(0, ValidationError::EmptyBatch))
        );
    }

    #[test]
    fn validation_rejects_bad_fields() {
        let g = || CreditTransferGroup::new("Acme", &de_iban()).execution_date(d("2026-07-20"));
        let b = || Pain001Builder::new("Acme").msg_id("OK");
        let kind = |r: Result<String, BuildError>| r.unwrap_err().kind;

        assert!(matches!(
            kind(b().add_group(g().add_entry(entry(0))).build()),
            ValidationError::AmountOutOfRange { .. }
        ));
        assert!(matches!(
            kind(b().add_group(g().add_entry(entry(100_000_000_000))).build()),
            ValidationError::AmountOutOfRange { .. }
        ));
        assert!(matches!(
            kind(
                b().msg_id("X".repeat(36))
                    .add_group(g().add_entry(entry(100)))
                    .build()
            ),
            ValidationError::TooLong { .. }
        ));
    }

    #[test]
    fn errors_name_the_group_and_transaction_that_failed() {
        let g = || CreditTransferGroup::new("Acme", &de_iban()).execution_date(d("2026-07-20"));
        let err = Pain001Builder::new("Acme")
            .msg_id("CT-LOC")
            .add_group(g().add_entry(entry(100)))
            .add_group(g().add_entry(entry(100)).add_entry(entry(0)))
            .build()
            .unwrap_err();
        assert_eq!(err.location, Location::transaction(1, 1));
        assert!(err.to_string().starts_with("PmtInf[1]/Tx[1]: "));
    }

    #[test]
    fn schema_versions_round_trip_through_their_identifiers() {
        for schema in CreditTransferSchema::ALL {
            assert_eq!(
                schema.message_id().parse::<CreditTransferSchema>(),
                Ok(*schema)
            );
            assert_eq!(
                schema.namespace().parse::<CreditTransferSchema>(),
                Ok(*schema)
            );
            assert!(schema.namespace().ends_with(schema.message_id()));
        }
        assert!("pain.001.001.99".parse::<CreditTransferSchema>().is_err());
    }

    #[test]
    fn the_epc_legacy_schema_emits_a_bare_date_and_the_pre_2019_bic_element() {
        let xml = Pain001Builder::new("Acme")
            .schema(CreditTransferSchema::IsoV3)
            .msg_id("CT-V3")
            .add_group(
                CreditTransferGroup::new("Acme", &de_iban())
                    .execution_date(d("2026-07-20"))
                    .debtor_bic("COBADEFF".parse().unwrap())
                    .add_entry(entry(5_000).with_bic("ABNANL2A".parse().unwrap())),
            )
            .build()
            .unwrap();
        assert!(xml.contains("pain.001.001.03"));
        assert!(xml.contains("<ReqdExctnDt>2026-07-20</ReqdExctnDt>"));
        assert!(xml.contains("<BIC>COBADEFF</BIC>"));
        assert!(!xml.contains("BICFI"));
    }

    #[test]
    fn sct_instant_on_a_schema_without_lclinstrm_is_rejected() {
        // Regression: the DK schema has no LclInstrm element, so this used to
        // emit a file that failed its own XSD. It is now a typed error.
        let err = Pain001Builder::new("Acme")
            .schema(CreditTransferSchema::DkV2_7)
            .msg_id("CT-DK-INST")
            .add_group(
                CreditTransferGroup::new("Acme", &de_iban())
                    .local_instrument(LocalInstrument::Inst)
                    .execution_date(d("2026-07-20"))
                    .add_entry(entry(5_000)),
            )
            .build()
            .unwrap_err();
        assert_eq!(
            err.kind,
            ValidationError::UnsupportedBySchema {
                feature: "PmtTpInf/LclInstrm (SCT Inst)",
                schema: "pain.001.003.03",
            }
        );
        assert_eq!(err.location, Location::group(0));

        // The EPC schemas both carry it.
        for schema in [CreditTransferSchema::IsoV9, CreditTransferSchema::IsoV3] {
            let xml = Pain001Builder::new("Acme")
                .schema(schema)
                .msg_id("CT-INST")
                .add_group(
                    CreditTransferGroup::new("Acme", &de_iban())
                        .local_instrument(LocalInstrument::Inst)
                        .execution_date(d("2026-07-20"))
                        .add_entry(entry(5_000)),
                )
                .build()
                .unwrap();
            assert!(
                xml.contains("<LclInstrm><Cd>INST</Cd></LclInstrm>"),
                "{schema}"
            );
        }
    }

    #[test]
    fn totals_use_integer_arithmetic() {
        let b = Pain001Builder::new("Acme").msg_id("CT").add_group(
            CreditTransferGroup::new("Acme", &de_iban())
                .execution_date(d("2026-07-20"))
                .add_entry(entry(10))
                .add_entry(entry(20)),
        );
        assert_eq!(b.total_ct(), 30);
        assert!(b.build().unwrap().contains("<CtrlSum>0.30</CtrlSum>"));
    }

    #[test]
    fn creation_timestamp_can_be_pinned_for_reproducible_output() {
        let build = || {
            one_group("Acme")
                .created_at("2026-07-19T12:00:00".parse().unwrap())
                .build()
                .unwrap()
        };
        assert_eq!(build(), build(), "output must be byte-identical");
        assert!(build().contains("<CreDtTm>2026-07-19T12:00:00</CreDtTm>"));
    }

    #[test]
    fn non_sepa_characters_are_transliterated() {
        let xml = Pain001Builder::new("Müller & Söhne GmbH")
            .msg_id("CT-UML")
            .add_group(
                CreditTransferGroup::new("Müller & Söhne GmbH", &de_iban())
                    .execution_date(d("2026-07-20"))
                    .add_entry(
                        CreditTransferEntry::new("Ökonomie AG", nl_iban(), 100, "E2E-1")
                            .with_description("Zahlung für Groß-Auftrag"),
                    ),
            )
            .build()
            .unwrap();
        assert!(xml.contains("Mueller + Soehne GmbH"));
        assert!(xml.contains("Oekonomie AG"));
        assert!(xml.contains("Zahlung fuer Gross-Auftrag"));
    }

    #[test]
    fn strict_charset_policy_rejects_umlauts() {
        assert!(matches!(
            one_group("Müller GmbH")
                .charset(CharsetPolicy::Strict)
                .build()
                .unwrap_err()
                .kind,
            ValidationError::InvalidCharacter { ch: 'ü', .. }
        ));
    }

    #[test]
    fn streaming_matches_the_in_memory_build() {
        let direct = one_group("Acme")
            .created_at("2026-07-19T12:00:00".parse().unwrap())
            .build()
            .unwrap();
        let mut buf: Vec<u8> = Vec::new();
        one_group("Acme")
            .created_at("2026-07-19T12:00:00".parse().unwrap())
            .write_to(&mut buf)
            .unwrap();
        assert_eq!(direct, String::from_utf8(buf).unwrap());

        // A rejected message writes nothing at all.
        let mut empty: Vec<u8> = Vec::new();
        assert!(Pain001Builder::new("Acme").write_to(&mut empty).is_err());
        assert!(empty.is_empty());
    }
}