sepa 0.9.0

SEPA identifiers and ISO 20022 payment messages: builders, bank-report parsers, validation and integer 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
//! EPC field-level rules for outgoing pain.001 / pain.008 messages.
//!
//! Almost none of these constraints live in the XSD. The published ISO schemas
//! allow amounts of `0`, five decimal places, any ISO 4217 currency, 140-character
//! names and arbitrary Unicode — so a file can validate cleanly against the
//! schema and still be rejected by the bank on ingestion. The rules here come
//! from the EPC Implementation Guidelines and the DK DFÜ-Abkommen, and they are
//! additional restrictions, not a guarantee of bank acceptance.
//!
//! | Field | Rule | Source |
//! |---|---|---|
//! | `MsgId`, `PmtInfId`, `EndToEndId`, `MndtId` | 1–35 chars, no leading/trailing `/`, no `//` | `Max35Text`, EPC230-15 |
//! | `Nm` (any party) | 1–70 chars (XSD permits 140) | EPC IG |
//! | `Ustrd` | 1–140 chars, one occurrence | EPC IG |
//! | `InstdAmt` | 0.01 – 999,999,999.99 EUR, 2 decimals | EPC IG §2.95 |
//! | emitted structured/hybrid `PstlAdr` | `TwnNm` + `Ctry`, ≤2 `AdrLine` | EPC153-22 v2.2; library scope |
//! | Batch | at least one transaction | `CdtTrfTxInf`/`DrctDbtTxInf` are `1..n` |
//!
//! Two kinds of rule are absent from that table because they are enforced by
//! construction rather than checked here:
//!
//! - **Dates** are [`IsoDate`] values, so a malformed `ReqdColltnDt` cannot
//!   reach a builder in the first place.
//! - **Unstructured addresses** are not representable: [`PostalAddress`]
//!   requires town/country for library scope. Current EPC guidance still permits
//!   unstructured addresses without a new cutoff.
//!
//! [`IsoDate`]: crate::IsoDate
//! [`PostalAddress`]: crate::PostalAddress
//!
//! The amount ceiling is uniform across SCT, SCT Inst, SDD Core and SDD B2B.
//! The old 100,000 EUR SCT Inst cap was removed from the scheme on
//! 5 October 2025 (2025 SCT Inst Rulebook, following Art 5a(6) of the amended
//! SEPA Regulation), so it is deliberately not enforced here — a lower ceiling
//! is now a PSP or user policy limit, not a scheme rule.

use crate::charset::{Transliteration, first_invalid_char, transliterate};

// ── limits ────────────────────────────────────────────────────────────────────

/// Maximum length of an ISO 20022 `Max35Text` identifier.
pub const MAX_ID_LEN: usize = 35;
/// Maximum length of a party name (`Nm`) under the EPC guidelines.
pub const MAX_NAME_LEN: usize = 70;
/// Maximum length of unstructured remittance information (`Ustrd`).
pub const MAX_REMITTANCE_LEN: usize = 140;
/// Maximum length of an external code (`SvcLvl/Cd`, `Purp/Cd`, …) — `Max4Text`.
pub const MAX_CODE_LEN: usize = 4;
/// Maximum length of `PstlAdr/BldgNb` and `PstlAdr/PstCd` — `Max16Text`.
pub const MAX_BUILDING_LEN: usize = 16;
/// Maximum serialised length of a structured remittance block (`RmtInf/Strd`).
///
/// The EPC guidelines cap `Strd` at 140 characters **including the XML tags**,
/// not just the data — which is why the writers emit the block minified and
/// why the limit is checked against the rendered bytes rather than against any
/// one field. Nothing in the XSD expresses this.
///
/// The EPC's optional **Extended Remittance Information** scheme (EPC092-19)
/// raises this to 999 occurrences of 280 characters, but it binds only PSPs
/// that have adhered to the ERI option separately, and sending an ERI-shaped
/// message to one that has not is a rejection. This crate emits the base
/// scheme; see the scope table in the README.
pub const MAX_STRUCTURED_REMITTANCE_LEN: usize = 140;
/// Maximum length of `CxlRsnInf/AddtlInf` — `Max105Text`.
pub const MAX_ADDITIONAL_INFO_LEN: usize = 105;
/// Smallest permitted amount: 0.01 EUR.
pub const MIN_AMOUNT_CT: i64 = 1;
/// Largest permitted amount: 999,999,999.99 EUR.
pub const MAX_AMOUNT_CT: i64 = 99_999_999_999;
/// Largest control sum a `CtrlSum` can carry: 9,999,999,999,999,999.99 EUR.
///
/// `CtrlSum` is a `DecimalNumber`, which the ISO schemas restrict to
/// `totalDigits = 18` — eighteen nines once written with two fraction digits.
/// That is **not** `i64::MAX`, which in cents is 92,233,720,368,547,758.07 and
/// carries nineteen digits. Entries that are each inside [`MAX_AMOUNT_CT`] can
/// sum into the gap between the two, so the bound has to be the schema's.
pub const MAX_CTRL_SUM_CT: i64 = 999_999_999_999_999_999;

/// The `Max*Text` bound for an emitted element, as the EPC restricts it.
///
/// This is the single place the length limits are written down. `element` is
/// the element's own name and `parent` its immediately enclosing element, which
/// is what disambiguates the names ISO 20022 reuses: `SvcLvl/Cd` is a
/// `Max4Text` external code while `LclInstrm/Cd` is a `Max35Text`, and `Othr/Id`
/// is an identifier while a bare `Id` is a container.
///
/// `None` means the element carries no character limit *here* — a container, a
/// date, an amount, a boolean, or a value whose own type already bounds it
/// (`IBAN`, `BICFI`, an enumerated code).
///
/// A consumer can use this to pre-check its own data with the same numbers the
/// builders enforce, rather than copying them:
///
/// ```
/// use sepa::validate::max_text_len;
///
/// assert_eq!(max_text_len(Some("Cdtr"), "Nm"), Some(70));      // EPC, not the XSD's 140
/// assert_eq!(max_text_len(Some("PstlAdr"), "TwnNm"), Some(35));
/// assert_eq!(max_text_len(Some("PstlAdr"), "BldgNb"), Some(16));
/// assert_eq!(max_text_len(Some("SvcLvl"), "Cd"), Some(4));
/// assert_eq!(max_text_len(Some("LclInstrm"), "Cd"), Some(35));
/// assert_eq!(max_text_len(Some("DbtrAcct"), "IBAN"), None);    // bounded by its own type
/// ```
// Arms are grouped by *what the element is*, not by the number that happens to
// bound it. `TwnNm` is a `Max35Text` and so is an identifier; `AdrLine` is a
// `Max70Text` and so is a name. Merging them to satisfy `match_same_arms` would
// assert an equivalence the schema does not make, and would silently move the
// wrong group the next time one of the two limits changes.
#[allow(
    clippy::match_same_arms,
    reason = "grouped by element kind, not by the coincident bound"
)]
#[must_use]
pub fn max_text_len(parent: Option<&str>, element: &str) -> Option<usize> {
    // Parent-qualified first: these are the names ISO 20022 reuses.
    if let Some(parent) = parent {
        match (parent, element) {
            // External code lists are four characters, and so is every value
            // of the `DocumentType3Code` enumeration under `CdOrPrtry`. A
            // local instrument code is not — it is a `Max35Text`.
            ("SvcLvl" | "CtgyPurp" | "Purp" | "Rsn" | "CdOrPrtry", "Cd") => {
                return Some(MAX_CODE_LEN);
            }
            ("LclInstrm", "Cd") => return Some(MAX_ID_LEN),
            ("Othr", "Id") => return Some(MAX_ID_LEN),
            // camt.055's case identifiers. Parent-qualified because a bare
            // `Id` is a container everywhere else — `DbtrAcct/Id` holds an
            // `IBAN`, not text.
            ("Assgnmt" | "Case" | "RslvdCase", "Id") => return Some(MAX_ID_LEN),
            ("SchmeNm" | "Rsn", "Prtry") => return Some(MAX_ID_LEN),
            // The structured remittance reference and the scheme that issued it.
            ("CdtrRefInf", "Ref") | ("Tp", "Issr") => return Some(MAX_ID_LEN),
            _ => {}
        }
    }
    match element {
        // Every party name. The EPC caps this at 70 where the XSD permits 140.
        "Nm" => Some(MAX_NAME_LEN),
        // Unstructured remittance information.
        "Ustrd" => Some(MAX_REMITTANCE_LEN),
        // OCT Inst carries AT-T020 — the currency requested for the non-euro
        // leg — in `InstrForCdtrAgt/InstrInf`, a `Max140Text`. The value this
        // crate puts there is a three-letter code, but the table has to
        // explain every element the writers emit, not only the long ones
        // (D37).
        "InstrInf" => Some(MAX_REMITTANCE_LEN),
        // Every `Max35Text` identifier the builders emit.
        "MsgId" | "PmtInfId" | "EndToEndId" | "MndtId" | "OrgnlMndtId" | "OrgnlMsgId"
        | "OrgnlMsgNmId" | "OrgnlPmtInfId" | "OrgnlEndToEndId" | "RvslPmtInfId" | "CxlId"
        | "PmtCxlId" | "OrgnlInstrId" | "GrpCxlId" => Some(MAX_ID_LEN),
        // `PostalAddress6` / `PostalAddress24`, in the elements the two share.
        "Dept" | "SubDept" | "StrtNm" | "AdrLine" => Some(MAX_NAME_LEN),
        "TwnNm" | "CtrySubDvsn" => Some(MAX_ID_LEN),
        "BldgNb" | "PstCd" => Some(MAX_BUILDING_LEN),
        // camt.055 free text about a cancellation — `Max105Text`, which is a
        // limit nothing else in the crate shares.
        "AddtlInf" => Some(MAX_ADDITIONAL_INFO_LEN),
        _ => None,
    }
}

// ── error ─────────────────────────────────────────────────────────────────────

/// A field-level violation of the EPC rules for a payment batch.
///
/// Every variant names the offending `field` using its ISO 20022 element path,
/// so the message points at the exact element a bank would reject.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum ValidationError {
    /// An address country is unknown or is not a normalized country code.
    #[error("{field} contains an unknown or non-normalized country code {code:?}")]
    UnknownCountry {
        /// ISO 20022 element path of the offending field.
        field: &'static str,
        /// The rejected country spelling.
        code: String,
    },

    /// The batch contains no transactions.
    ///
    /// `CdtTrfTxInf` and `DrctDbtTxInf` are both `1..n`, so an empty batch is
    /// not merely useless — it is schema-invalid.
    #[error("batch contains no transactions: at least one is required")]
    EmptyBatch,

    /// A mandatory field was empty or blank.
    #[error("{field} must not be empty")]
    Empty {
        /// ISO 20022 element path of the offending field.
        field: &'static str,
    },

    /// A field exceeded its maximum length.
    #[error("{field} is {actual} characters, exceeding the maximum of {max}")]
    TooLong {
        /// ISO 20022 element path of the offending field.
        field: &'static str,
        /// Maximum permitted length in characters.
        max: usize,
        /// Actual length in characters.
        actual: usize,
    },

    /// A repeating element occurred more often than the rules allow.
    ///
    /// Separate from [`TooLong`](Self::TooLong), which is about one value being
    /// too long. This is about too many values — `PstlAdr/AdrLine` is capped at
    /// two by the EPC even though the XSD permits seven.
    #[error("{field} occurs {actual} times, exceeding the maximum of {max}")]
    TooMany {
        /// ISO 20022 element path of the offending field.
        field: &'static str,
        /// Maximum permitted number of occurrences.
        max: usize,
        /// Actual number of occurrences.
        actual: usize,
    },

    /// A field contained a character outside the SEPA Basic Latin set.
    ///
    /// Produced under [`CharsetPolicy::Strict`] or for identifiers, which are
    /// never transliterated. The default policy transliterates ordinary text.
    #[error("{field} contains {ch:?}, which is not in the SEPA character set")]
    InvalidCharacter {
        /// ISO 20022 element path of the offending field.
        field: &'static str,
        /// The first offending character.
        ch: char,
    },

    /// A field contained a character forbidden by XML 1.0.
    #[error("{field} contains {ch:?}, which is not a legal XML 1.0 character")]
    InvalidXmlCharacter {
        /// ISO 20022 element path of the offending field.
        field: &'static str,
        /// The first offending character.
        ch: char,
    },

    /// An identifier began or ended with `/`, or contained `//`.
    #[error("{field} must not start or end with '/' nor contain '//' (EPC230-15)")]
    SlashRule {
        /// ISO 20022 element path of the offending field.
        field: &'static str,
    },

    /// An amount fell outside 0.01 – 999,999,999.99 EUR.
    #[error("{field} is {amount_ct} ct, outside the permitted 1 – {MAX_AMOUNT_CT} ct")]
    AmountOutOfRange {
        /// ISO 20022 element path of the offending field.
        field: &'static str,
        /// The rejected amount in cents.
        amount_ct: i64,
    },

    /// A `ChrgBr` value the scheme does not allow.
    ///
    /// The four SEPA schemes mandate `SLEV` and OCT Inst forbids it, allowing
    /// only `CRED`, `DEBT` and `SHAR`. Both directions pass every XSD and are
    /// rejected on ingestion.
    #[error("charge bearer {bearer} is not allowed under service level {scheme}")]
    ChargeBearerNotAllowed {
        /// The rejected `ChargeBearerType1Code`.
        bearer: &'static str,
        /// The `SvcLvl/Cd` of the scheme that refused it.
        scheme: &'static str,
    },

    /// The batch's amounts sum past what `CtrlSum` can carry.
    ///
    /// The bound is the schema's, not the host language's: `CtrlSum` is a
    /// `DecimalNumber` with `totalDigits = 18`, so the limit is
    /// [`MAX_CTRL_SUM_CT`] — see its docs for why `i64::MAX` is the wrong one.
    #[error(
        "batch control sum exceeds the CtrlSum bound of {} EUR (DecimalNumber, totalDigits=18)",
        crate::ct_to_eur_str(MAX_CTRL_SUM_CT)
    )]
    ControlSumOverflow,

    /// The same element was set at both payment-information and transaction
    /// level, where the rules permit one or the other.
    #[error("{field} must be set at either payment-information or transaction level, not both")]
    ConflictingLevels {
        /// The ISO 20022 element name.
        field: &'static str,
    },

    /// Two mutually exclusive alternatives were both supplied.
    ///
    /// Distinct from [`ConflictingLevels`](Self::ConflictingLevels), which is
    /// about the same element appearing at two *levels* of the message. This is
    /// about two different elements that stand in for one another — a mandate
    /// amendment cannot both name the previous debtor account and say `SMNDA`
    /// for it.
    #[error("{field}: {first} and {second} are alternatives — set one, not both")]
    MutuallyExclusive {
        /// ISO 20022 element path of the enclosing field.
        field: &'static str,
        /// The first alternative.
        first: &'static str,
        /// The second alternative.
        second: &'static str,
    },

    /// The selected schema version cannot carry a requested feature.
    ///
    /// The older schemas are not merely renamed: `pain.001.003.03` has no
    /// `LclInstrm` element at all, so an SCT Instant batch built against it
    /// would be schema-invalid rather than merely unusual.
    #[error("{feature} is not available in {schema}")]
    UnsupportedBySchema {
        /// What the batch asked for, named as its ISO 20022 element.
        feature: &'static str,
        /// The message identifier of the selected schema, e.g. `pain.001.003.03`.
        schema: &'static str,
    },

    /// Two dates in the same message contradict each other.
    ///
    /// Needs no clock: both values are in the document, and one cannot precede
    /// the other and still describe a real event. A mandate signed *after* the
    /// collection it authorises is the case in point — the collection has no
    /// mandate behind it on the day it is taken, which is what the debtor's
    /// bank checks and refuses with `MD01`.
    #[error("{later} {later_value} must not be after {earlier} {earlier_value}")]
    DateOrder {
        /// ISO 20022 element path of the date that must come first.
        later: &'static str,
        /// Its value.
        later_value: crate::IsoDate,
        /// ISO 20022 element path of the date it must not follow.
        earlier: &'static str,
        /// Its value.
        earlier_value: crate::IsoDate,
    },

    /// A feature was used without the element the scheme requires beside it.
    ///
    /// Distinct from [`UnsupportedBySchema`](Self::UnsupportedBySchema): the
    /// element exists in the selected schema, but the scheme rules only admit
    /// it in combination with another. A timed `ReqdExctnDt` is the case in
    /// point — the DK schema annotates `DtTm` *"Only allowed for `SCTinst`"*.
    #[error("{feature} requires {requires}")]
    Requires {
        /// What the batch asked for, named as its ISO 20022 element.
        feature: &'static str,
        /// What has to accompany it.
        requires: &'static str,
    },

    /// A value is well-formed but the selected schema's type cannot hold it.
    ///
    /// Distinct from [`UnsupportedBySchema`](Self::UnsupportedBySchema), which
    /// is about an *element* the schema does not have. Here the element exists
    /// and the value is legal under the current standard — it is the older
    /// schema's narrower pattern that refuses it. A BIC with a digit in its
    /// business party prefix is the case in point: ISO 9362:2022 admits it and
    /// `BICFIDec2014Identifier` accepts it, while the pre-2019 `BICIdentifier`
    /// of `pain.008.001.02` does not.
    #[error("{field} {value:?} does not match {expected}, the pattern {schema} uses")]
    SchemaPattern {
        /// ISO 20022 element path of the offending field.
        field: &'static str,
        /// The value that cannot be written there.
        value: String,
        /// The message identifier of the selected schema, e.g. `pain.008.001.02`.
        schema: &'static str,
        /// The XSD pattern the value fails, as the schema writes it.
        expected: &'static str,
    },

    /// Two `PmtInf` groups in one message carry the same identifier.
    ///
    /// `PmtInfId` is the key a bank echoes back in `pain.002` and in the
    /// `NtryDtls/Btch` block of a camt statement, so duplicates make a booking
    /// unattributable — and duplicate-file detection may drop the second group
    /// outright.
    #[error("{field} {value:?} is used by more than one group — it must be unique in a message")]
    Duplicate {
        /// ISO 20022 element path of the offending field.
        field: &'static str,
        /// The value that occurred more than once.
        value: String,
    },
}

/// Error returned when a schema version cannot be parsed from a string.
///
/// Produced by `CreditTransferSchema::from_str` and
/// `DirectDebitSchema::from_str`, which is how a bank-specific target version
/// gets read out of a configuration file.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[error("unknown schema {value:?}: expected one of {supported}")]
pub struct UnknownSchema {
    /// The unrecognised text.
    pub value: String,
    /// The message identifiers this builder can emit.
    pub supported: &'static str,
}

// ── location ──────────────────────────────────────────────────────────────────

/// Where in a message a validation error occurred.
///
/// A collection run is thousands of transactions long, so "`Dbtr/Nm` is too
/// long" only becomes actionable once it says *which* one. Both indices are
/// zero-based and refer to the order the groups and entries were added.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Location {
    /// Index of the `PmtInf` group, or `None` for a message-level error.
    pub group: Option<usize>,
    /// Index of the transaction within that group, or `None` for a group-level
    /// error.
    pub transaction: Option<usize>,
}

impl Location {
    /// A message-level location — neither group nor transaction.
    #[must_use]
    pub const fn message() -> Self {
        Self {
            group: None,
            transaction: None,
        }
    }

    /// A group-level location.
    #[must_use]
    pub const fn group(index: usize) -> Self {
        Self {
            group: Some(index),
            transaction: None,
        }
    }

    /// A transaction-level location.
    #[must_use]
    pub const fn transaction(group: usize, transaction: usize) -> Self {
        Self {
            group: Some(group),
            transaction: Some(transaction),
        }
    }
}

impl std::fmt::Display for Location {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match (self.group, self.transaction) {
            (None, _) => f.write_str("message"),
            (Some(g), None) => write!(f, "PmtInf[{g}]"),
            (Some(g), Some(t)) => write!(f, "PmtInf[{g}]/Tx[{t}]"),
        }
    }
}

// ── build error ───────────────────────────────────────────────────────────────

/// A validation failure, with the position in the message that caused it.
///
/// Returned by `Pain001Builder::build` and `Pain008Builder::build`. Match on
/// [`kind`](Self::kind) to react to the rule that was broken and read
/// [`location`](Self::location) to tell the operator which transaction to fix.
///
/// # Examples
///
/// ```
/// use sepa::{
///     DirectDebitEntry, DirectDebitGroup, IsoDate, Pain008Builder, ValidationError,
///     validate_creditor_id, validate_iban,
/// };
///
/// let iban = validate_iban("DE89370400440532013000")?;
/// let ci = validate_creditor_id("DE98ZZZ09999999999")?;
/// let date = IsoDate::new(2026, 7, 20)?;
///
/// let err = Pain008Builder::new("Stadtwerke GmbH", "DD-1")
///     .add_group(
///         DirectDebitGroup::new("Stadtwerke GmbH", &iban, &ci, date)
///             .add_entry(DirectDebitEntry::new(
///                 "MND-1", date, "Erste Kundin", iban.clone(), 100, "E2E-1",
///             ))
///             // The second collection has a zero amount.
///             .add_entry(DirectDebitEntry::new(
///                 "MND-2", date, "Zweiter Kunde", iban.clone(), 0, "E2E-2",
///             )),
///     )
///     .build()
///     .unwrap_err();
///
/// assert_eq!(err.location.group, Some(0));
/// assert_eq!(err.location.transaction, Some(1));
/// assert!(matches!(err.kind, ValidationError::AmountOutOfRange { .. }));
/// assert_eq!(
///     err.to_string(),
///     "PmtInf[0]/Tx[1]: DrctDbtTxInf/InstdAmt is 0 ct, outside the permitted 1 \u{2013} 99999999999 ct",
/// );
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[error("{location}: {kind}")]
pub struct BuildError {
    /// Which group and transaction the failure belongs to.
    pub location: Location,
    /// The rule that was broken.
    #[source]
    pub kind: ValidationError,
}

impl BuildError {
    /// A message-level failure.
    #[must_use]
    pub const fn message(kind: ValidationError) -> Self {
        Self {
            location: Location::message(),
            kind,
        }
    }

    /// A group-level failure.
    #[must_use]
    pub const fn group(index: usize, kind: ValidationError) -> Self {
        Self {
            location: Location::group(index),
            kind,
        }
    }

    /// A transaction-level failure.
    #[must_use]
    pub const fn transaction(group: usize, transaction: usize, kind: ValidationError) -> Self {
        Self {
            location: Location::transaction(group, transaction),
            kind,
        }
    }
}

/// Attach a [`Location`] to a `Result<_, ValidationError>`.
pub(crate) trait Locate<T> {
    fn at(self, location: Location) -> Result<T, BuildError>;
}

impl<T> Locate<T> for Result<T, ValidationError> {
    fn at(self, location: Location) -> Result<T, BuildError> {
        self.map_err(|kind| BuildError { location, kind })
    }
}

/// Error returned when streaming a batch to an [`io::Write`](std::io::Write) target.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum WriteError {
    /// The batch violates an EPC rule; nothing was written.
    #[error(transparent)]
    Validation(#[from] BuildError),

    /// The underlying writer failed.
    #[error(transparent)]
    Io(#[from] std::io::Error),
}

// ── charset policy ────────────────────────────────────────────────────────────

/// How a builder handles text outside the SEPA Basic Latin character set.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum CharsetPolicy {
    /// Convert unsupported characters automatically (default).
    ///
    /// Length limits are checked **after** conversion, since German-style
    /// transliteration can lengthen a string (`Müller` → `Mueller`).
    Transliterate(Transliteration),
    /// Reject unsupported characters with [`ValidationError::InvalidCharacter`].
    ///
    /// Use when the caller has already sanitised its data and wants a hard
    /// guarantee that nothing is silently rewritten.
    Strict,
}

impl CharsetPolicy {
    /// Apply this policy to `text`, returning SEPA-legal output.
    ///
    /// # Errors
    ///
    /// Under [`CharsetPolicy::Strict`], returns [`ValidationError::InvalidCharacter`]
    /// for the first character outside the SEPA set.
    pub fn apply<'a>(
        self,
        field: &'static str,
        text: &'a str,
    ) -> Result<std::borrow::Cow<'a, str>, ValidationError> {
        match self {
            Self::Transliterate(style) => Ok(transliterate(text, style)),
            Self::Strict => match first_invalid_char(text) {
                Some(ch) => Err(ValidationError::InvalidCharacter { field, ch }),
                None => Ok(std::borrow::Cow::Borrowed(text)),
            },
        }
    }

    /// The form of `text` a writer emits — the same conversion as
    /// [`apply`](Self::apply), minus the error.
    ///
    /// Serialisation runs only after `validate()` has accepted the message, so
    /// under [`Strict`](Self::Strict) there is by then nothing left to reject
    /// and the text passes through. Having one infallible entry point for the
    /// writers keeps that reasoning in a single place rather than repeated at
    /// every element.
    pub(crate) fn render(self, text: &str) -> std::borrow::Cow<'_, str> {
        match self {
            Self::Transliterate(style) => transliterate(text, style),
            Self::Strict => std::borrow::Cow::Borrowed(text),
        }
    }
}

impl Default for CharsetPolicy {
    fn default() -> Self {
        Self::Transliterate(Transliteration::German)
    }
}

// ── field checks ──────────────────────────────────────────────────────────────

/// Validate a `Max35Text` identifier: non-empty, ≤35 chars, slash rules.
///
/// # Errors
///
/// See [`ValidationError`].
pub fn check_id(field: &'static str, value: &str) -> Result<(), ValidationError> {
    check_len(field, value, MAX_ID_LEN)?;

    // Identifiers are never transliterated, whatever the CharsetPolicy says: an
    // identifier is a key the bank echoes back in pain.002 and camt.05x, so
    // silently rewriting `MND-Straße` to `MND-Strasse` would break the caller's
    // own reconciliation. Out-of-set characters are a hard error instead.
    if let Some(ch) = first_invalid_char(value) {
        return Err(ValidationError::InvalidCharacter { field, ch });
    }

    // EPC230-15 applies the slash rules to references and identifiers only.
    // Inspecting trimmed identifiers is library policy, not XSD normalization.
    let trimmed = value.trim();
    if trimmed.starts_with('/') || trimmed.ends_with('/') || trimmed.contains("//") {
        return Err(ValidationError::SlashRule { field });
    }
    Ok(())
}

/// Validate a party name: non-empty, ≤70 characters.
///
/// # Errors
///
/// See [`ValidationError`].
pub fn check_name(field: &'static str, value: &str) -> Result<(), ValidationError> {
    check_len(field, value, MAX_NAME_LEN)
}

/// Validate unstructured remittance information: non-empty, ≤140 characters.
///
/// # Errors
///
/// See [`ValidationError`].
pub fn check_remittance(field: &'static str, value: &str) -> Result<(), ValidationError> {
    check_len(field, value, MAX_REMITTANCE_LEN)
}

/// Validate a free-text element against an explicit `Max*Text` bound.
///
/// Used where the limit is per-element rather than one of the three shared
/// SEPA limits — the `PstlAdr` sub-elements run from `Max16Text` to
/// `Max70Text`.
///
/// # Errors
///
/// See [`ValidationError`].
pub fn check_text(field: &'static str, value: &str, max: usize) -> Result<(), ValidationError> {
    check_len(field, value, max)
}

/// Non-empty and within `max` **characters** (not bytes).
///
/// Counts the emitted value, including padding. ISO `Max*Text` types derived
/// from `xs:string` preserve whitespace. Blank-only refusal is library policy.
fn check_len(field: &'static str, value: &str, max: usize) -> Result<(), ValidationError> {
    if let Some(ch) = value
        .chars()
        .find(|character| !crate::xml::is_xml_character(*character))
    {
        return Err(ValidationError::InvalidXmlCharacter { field, ch });
    }
    if value.trim().is_empty() {
        return Err(ValidationError::Empty { field });
    }
    // Counted in chars: the ISO limits are character limits, and a byte-based
    // check would both mis-measure and risk slicing a multi-byte character.
    let actual = value.chars().count();
    if actual > max {
        return Err(ValidationError::TooLong { field, max, actual });
    }
    Ok(())
}

/// Validate an amount in cents against the SEPA range 0.01 – 999,999,999.99.
///
/// # Errors
///
/// Returns [`ValidationError::AmountOutOfRange`] outside that range. Note this
/// rejects zero and all negative amounts.
pub fn check_amount(field: &'static str, amount_ct: i64) -> Result<(), ValidationError> {
    if !(MIN_AMOUNT_CT..=MAX_AMOUNT_CT).contains(&amount_ct) {
        return Err(ValidationError::AmountOutOfRange { field, amount_ct });
    }
    Ok(())
}

/// Add one entry's amount to a running `CtrlSum`, bounded by the schema.
///
/// The single place that arithmetic happens, so the three writers cannot
/// disagree about it. A bare `checked_add` would bound the sum at `i64::MAX`,
/// three orders of magnitude looser than [`MAX_CTRL_SUM_CT`].
///
/// # Errors
///
/// [`ValidationError::ControlSumOverflow`] when the running total would pass
/// [`MAX_CTRL_SUM_CT`].
///
/// # Examples
///
/// ```
/// use sepa::validate::{MAX_CTRL_SUM_CT, accumulate_control_sum};
/// assert_eq!(accumulate_control_sum(100, 50), Ok(150));
/// assert!(accumulate_control_sum(MAX_CTRL_SUM_CT, 1).is_err());
/// ```
pub fn accumulate_control_sum(total: i64, amount_ct: i64) -> Result<i64, ValidationError> {
    total
        .checked_add(amount_ct)
        .filter(|sum| *sum <= MAX_CTRL_SUM_CT)
        .ok_or(ValidationError::ControlSumOverflow)
}

/// The longest prefix of `s` that is at most `max` **characters**.
///
/// Slicing by byte index (`&s[..35]`) panics whenever the boundary lands inside
/// a multi-byte character — which a German name reaches routinely — and would
/// mis-measure the limit even when it did not panic, since ISO 20022 counts
/// characters.
///
/// This is for values the crate *derives*, such as the `PmtInfId` it suffixes
/// from a `MsgId`. Caller-supplied text is never silently shortened: an
/// over-long field is a [`ValidationError::TooLong`], because a truncated
/// remittance line is a reconciliation failure the sender never sees.
#[must_use]
pub fn truncate_chars(s: &str, max: usize) -> &str {
    match s.char_indices().nth(max) {
        Some((byte_idx, _)) => &s[..byte_idx],
        None => s,
    }
}

// ── tests ─────────────────────────────────────────────────────────────────────

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

    #[test]
    fn text_length_counts_the_untrimmed_value_that_writers_emit() {
        assert!(check_text("Text", " A ", 3).is_ok());
        assert_eq!(
            check_text("Text", " A ", 2),
            Err(ValidationError::TooLong {
                field: "Text",
                max: 2,
                actual: 3
            })
        );
        assert!(check_text("Text", "\tA\n", 2).is_err());
        assert!(check_text("Text", "   ", 3).is_err());
    }

    #[test]
    fn text_refuses_xml_forbidden_characters_without_rewriting() {
        for character in [
            '\0', '\u{1}', '\u{b}', '\u{c}', '\u{1f}', '\u{fffe}', '\u{ffff}',
        ] {
            let text = format!("A{character}B");
            assert_eq!(
                check_text("Text", &text, 3),
                Err(ValidationError::InvalidXmlCharacter {
                    field: "Text",
                    ch: character
                })
            );
        }
        for character in [
            '\t',
            '\n',
            '\r',
            '\u{20}',
            '\u{d7ff}',
            '\u{e000}',
            '\u{fffd}',
            '\u{10000}',
            '\u{10ffff}',
        ] {
            let text = format!("A{character}B");
            assert!(check_text("Text", &text, 3).is_ok(), "{character:?}");
        }
    }

    #[test]
    fn ids_respect_length_and_slash_rules() {
        assert!(check_id("MsgId", "DD-2026-07-001").is_ok());
        assert!(check_id("MsgId", &"X".repeat(35)).is_ok());

        assert_eq!(
            check_id("MsgId", &"X".repeat(36)),
            Err(ValidationError::TooLong {
                field: "MsgId",
                max: 35,
                actual: 36
            })
        );
        assert_eq!(
            check_id("MsgId", ""),
            Err(ValidationError::Empty { field: "MsgId" })
        );
        assert_eq!(
            check_id("MsgId", "   "),
            Err(ValidationError::Empty { field: "MsgId" })
        );
        for bad in ["/leading", "trailing/", "double//slash"] {
            assert_eq!(
                check_id("EndToEndId", bad),
                Err(ValidationError::SlashRule {
                    field: "EndToEndId"
                }),
                "{bad:?} must violate the slash rule"
            );
        }
        // A single interior slash is fine.
        assert!(check_id("EndToEndId", "INV/2026/07").is_ok());
    }

    #[test]
    fn lengths_are_counted_in_characters_not_bytes() {
        // 70 'ä' is 140 bytes but only 70 characters — must be accepted.
        let name = "ä".repeat(70);
        assert_eq!(name.len(), 140);
        assert!(check_name("Nm", &name).is_ok());
        assert!(check_name("Nm", &"ä".repeat(71)).is_err());
    }

    #[test]
    fn name_and_remittance_limits() {
        assert!(check_name("Cdtr/Nm", &"A".repeat(70)).is_ok());
        assert!(check_name("Cdtr/Nm", &"A".repeat(71)).is_err());
        assert!(check_remittance("Ustrd", &"A".repeat(140)).is_ok());
        assert!(check_remittance("Ustrd", &"A".repeat(141)).is_err());
    }

    #[test]
    fn amount_range_matches_the_epc_rule() {
        assert!(check_amount("InstdAmt", 1).is_ok());
        assert!(check_amount("InstdAmt", MAX_AMOUNT_CT).is_ok());

        for bad in [0, -1, MAX_AMOUNT_CT + 1, i64::MIN, i64::MAX] {
            assert_eq!(
                check_amount("InstdAmt", bad),
                Err(ValidationError::AmountOutOfRange {
                    field: "InstdAmt",
                    amount_ct: bad
                }),
                "{bad} must be rejected"
            );
        }
    }

    #[test]
    fn sct_inst_100k_cap_is_not_enforced() {
        // Removed from the scheme on 5 Oct 2025 — 250,000 EUR must be accepted.
        assert!(check_amount("InstdAmt", 25_000_000).is_ok());
    }

    #[test]
    fn identifiers_reject_non_sepa_characters_under_every_policy() {
        // An identifier is a reconciliation key: it must round-trip exactly, so
        // it is never transliterated, even under the default policy.
        for field in ["MsgId", "EndToEndId", "MndtId"] {
            assert_eq!(
                check_id(field, "MND-Straße"),
                Err(ValidationError::InvalidCharacter { field, ch: 'ß' })
            );
        }
        assert!(check_id("MsgId", "MND-Strasse-01").is_ok());
    }

    #[test]
    fn slash_rule_survives_whitespace_padding() {
        // XSD whitespace collapse would strip the padding and expose the slash.
        assert_eq!(
            check_id("MsgId", " /x "),
            Err(ValidationError::SlashRule { field: "MsgId" })
        );
        assert_eq!(
            check_id("MsgId", " x/ "),
            Err(ValidationError::SlashRule { field: "MsgId" })
        );
    }

    #[test]
    fn locations_read_as_element_paths() {
        assert_eq!(Location::message().to_string(), "message");
        assert_eq!(Location::group(0).to_string(), "PmtInf[0]");
        assert_eq!(Location::transaction(1, 42).to_string(), "PmtInf[1]/Tx[42]");
    }

    #[test]
    fn build_errors_carry_both_the_rule_and_the_position() {
        let err = BuildError::transaction(
            2,
            7,
            ValidationError::AmountOutOfRange {
                field: "InstdAmt",
                amount_ct: 0,
            },
        );
        assert_eq!(err.location, Location::transaction(2, 7));
        assert!(err.to_string().starts_with("PmtInf[2]/Tx[7]: "));
        // The rule stays matchable through the wrapper.
        assert!(matches!(err.kind, ValidationError::AmountOutOfRange { .. }));
    }

    #[test]
    fn strict_policy_rejects_non_sepa_characters() {
        let policy = CharsetPolicy::Strict;
        assert_eq!(policy.apply("Nm", "Mueller").unwrap(), "Mueller");
        assert_eq!(
            policy.apply("Nm", "Müller"),
            Err(ValidationError::InvalidCharacter {
                field: "Nm",
                ch: 'ü'
            })
        );
    }

    #[test]
    fn default_policy_transliterates() {
        let policy = CharsetPolicy::default();
        assert_eq!(policy.apply("Nm", "Müller & Co").unwrap(), "Mueller + Co");
    }

    #[test]
    fn truncation_never_splits_a_character() {
        // Regression: `&desc[..140]` panicked when byte 140 fell inside 'ü'.
        let s = format!("{}ü", "A".repeat(139));
        assert_eq!(s.len(), 141, "141 bytes, 140 characters");
        let out = truncate_chars(&s, 140);
        assert_eq!(out.chars().count(), 140);
        assert!(out.ends_with('ü'), "the whole character must survive");

        // One character over: the 'ü' is dropped whole, not split.
        let s2 = format!("{}ü", "A".repeat(140));
        let out2 = truncate_chars(&s2, 140);
        assert_eq!(out2, "A".repeat(140));
    }

    #[test]
    fn truncation_is_a_no_op_when_within_limit() {
        assert_eq!(truncate_chars("short", 140), "short");
        assert_eq!(truncate_chars("", 140), "");
    }

    #[test]
    fn render_is_apply_without_the_error() {
        // Writers run after validation, so `render` never has to reject.
        assert_eq!(
            CharsetPolicy::default().render("Müller & Co"),
            "Mueller + Co"
        );
        assert_eq!(CharsetPolicy::Strict.render("Mueller"), "Mueller");
    }

    #[test]
    fn epc_policy_transliterates_one_to_one() {
        let policy = CharsetPolicy::Transliterate(Transliteration::Epc);
        assert_eq!(policy.apply("Nm", "Müller & Co").unwrap(), "Muller + Co");
    }
}