daaki-message 0.2.0

RFC 5322 email message parser and builder
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
//! Public API types for parsed and outgoing email messages.
//!
//! All types are fully owned (`String` / `Vec<u8>`) with no lifetime parameters,
//! per workspace conventions.
//!
//! # References
//! - RFC 5322 (Internet Message Format — address, date-time)
//! - RFC 2045 (MIME — Content-Transfer-Encoding)
//! - RFC 2183 (Content-Disposition)
//! - RFC 3501 Section 6.4.5 (IMAP MIME section numbers)

// ---------------------------------------------------------------------------
// Validated newtypes
// ---------------------------------------------------------------------------

/// Error returned when constructing a validated protocol type from an invalid string.
///
/// Shared across `daaki-imap` and `daaki-smtp` for validated newtypes
/// such as `SequenceSet`, `MailboxName`, `Domain`, `ForwardPath`, etc.
/// Each crate's [`Error`] type provides a blanket `From<ValidationError>`
/// conversion so these can be used with `?` in application code.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[error("{0}")]
pub struct ValidationError(String);

impl ValidationError {
    /// Create a new validation error with the given message.
    pub fn new(message: impl Into<String>) -> Self {
        Self(message.into())
    }

    /// Return the error message as a string slice.
    pub fn message(&self) -> &str {
        &self.0
    }
}

/// A validated RFC 5322 header field name.
///
/// RFC 5322 Section 2.2 defines a field name as `1*ftext`, where
/// `ftext = %d33-57 / %d59-126` — printable US-ASCII excluding the colon
/// (`:`). This newtype enforces that constraint at construction time so
/// that downstream code can rely on the name being well-formed.
///
/// # Case Insensitivity
///
/// Comparison and hashing are case-insensitive per RFC 5322 Section 2.2,
/// so `HeaderName::new("Subject")` and `HeaderName::new("subject")` are equal.
///
/// # References
/// - RFC 5322 Section 2.2 (header field syntax)
#[non_exhaustive]
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(try_from = "String", into = "String"))]
pub struct HeaderName(String);

impl HeaderName {
    /// Creates a new `HeaderName` after validating ftext syntax
    /// (RFC 5322 Section 2.2).
    ///
    /// The name must be non-empty and consist solely of printable US-ASCII
    /// characters (33..=126) excluding colon (58).
    ///
    /// # Errors
    ///
    /// Returns [`crate::error::Error::InvalidHeaderName`] if the name is
    /// empty or contains invalid characters.
    ///
    /// # References
    /// - RFC 5322 Section 2.2
    pub fn new(s: impl Into<String>) -> crate::Result<Self> {
        let s = s.into();
        validate_ftext(&s)?;
        Ok(Self(s))
    }

    /// Creates a `HeaderName` without validation — test-only.
    #[cfg(test)]
    pub(crate) fn new_unchecked(s: impl Into<String>) -> Self {
        Self(s.into())
    }

    /// Returns the header name as a string slice.
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// Consumes self and returns the inner `String`.
    pub fn into_inner(self) -> String {
        self.0
    }
}

impl AsRef<str> for HeaderName {
    fn as_ref(&self) -> &str {
        &self.0
    }
}

/// Internet message field names are case-insensitive during comparison.
///
/// RFC 822 Section 3.4.7 states this rule explicitly, and RFC 5322 retains
/// the same `field-name` model for message headers.
impl PartialEq for HeaderName {
    fn eq(&self, other: &Self) -> bool {
        self.0.eq_ignore_ascii_case(&other.0)
    }
}

impl Eq for HeaderName {}

/// Hash header names case-insensitively so hashing matches equality.
///
/// RFC 822 Section 3.4.7: field-name case is not distinguished. RFC 5322
/// continues the same header field model.
impl std::hash::Hash for HeaderName {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        for byte in self.0.as_bytes() {
            byte.to_ascii_lowercase().hash(state);
        }
    }
}

/// Order header names case-insensitively (RFC 5322 Section 2.2).
impl PartialOrd for HeaderName {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

/// Total ordering on header names, case-insensitive (RFC 5322 Section 2.2).
impl Ord for HeaderName {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        let a = self.0.as_bytes().iter().map(u8::to_ascii_lowercase);
        let b = other.0.as_bytes().iter().map(u8::to_ascii_lowercase);
        a.cmp(b)
    }
}

impl std::fmt::Display for HeaderName {
    /// Displays the header name verbatim (RFC 5322 Section 2.2).
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.0)
    }
}

impl TryFrom<String> for HeaderName {
    type Error = crate::error::Error;

    /// Converts a `String` into a validated `HeaderName` (RFC 5322 Section 2.2).
    fn try_from(s: String) -> Result<Self, Self::Error> {
        Self::new(s)
    }
}

impl TryFrom<&str> for HeaderName {
    type Error = crate::error::Error;

    /// Converts a `&str` into a validated `HeaderName` (RFC 5322 Section 2.2).
    fn try_from(s: &str) -> Result<Self, Self::Error> {
        Self::new(s)
    }
}

impl From<HeaderName> for String {
    fn from(h: HeaderName) -> Self {
        h.into_inner()
    }
}

/// Validates that `s` is a valid `ftext` sequence per RFC 5322 Section 2.2.
///
/// `field-name = 1*ftext` where `ftext = %d33-57 / %d59-126` — printable
/// US-ASCII characters excluding colon (`:`).
///
/// # References
/// - RFC 5322 Section 2.2
fn validate_ftext(s: &str) -> crate::Result<()> {
    if s.is_empty() {
        return Err(crate::error::Error::InvalidHeaderName(
            "header name must not be empty".into(),
        ));
    }
    if let Some(bad) = s.chars().find(|&c| {
        // ftext: printable ASCII (33..=126) excluding ':' (58)
        let b = c as u32;
        !(33..=126).contains(&b) || c == ':'
    }) {
        return Err(crate::error::Error::InvalidHeaderName(format!(
            "header name contains invalid character {bad:?} (RFC 5322 Section 2.2)"
        )));
    }
    Ok(())
}

/// A validated RFC 5322 message-ID (bare, without angle brackets).
///
/// RFC 5322 Section 3.6.4 defines `msg-id = "<" id-left "@" id-right ">"`.
/// This type stores only the bare `id-left "@" id-right` content. Angle
/// brackets are added by the builder when emitting wire format.
///
/// # Validation rules
/// - Non-empty
/// - Exactly one `@` separator
/// - `id-left` and `id-right` must each be non-empty
/// - No whitespace, angle brackets, or control characters
///
/// # References
/// - RFC 5322 Section 3.6.4 (message identification)
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(try_from = "String", into = "String"))]
pub struct MessageId(String);

impl MessageId {
    /// Creates a new `MessageId` after validation (RFC 5322 Section 3.6.4).
    ///
    /// The value must be a bare message-ID (no angle brackets) containing
    /// exactly one `@` with non-empty parts on each side, and no
    /// whitespace, angle brackets, or control characters.
    ///
    /// # Errors
    ///
    /// Returns [`crate::error::Error::InvalidMessageId`] if validation fails.
    ///
    /// # References
    /// - RFC 5322 Section 3.6.4
    pub fn new(s: impl Into<String>) -> crate::Result<Self> {
        let s = s.into();
        validate_message_id(&s)?;
        Ok(Self(s))
    }

    /// Creates a `MessageId` without validation — test-only.
    #[cfg(test)]
    pub(crate) fn new_unchecked(s: impl Into<String>) -> Self {
        Self(s.into())
    }

    /// Returns the message-ID as a string slice.
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// Consumes self and returns the inner `String`.
    pub fn into_inner(self) -> String {
        self.0
    }
}

impl AsRef<str> for MessageId {
    fn as_ref(&self) -> &str {
        &self.0
    }
}

impl std::fmt::Display for MessageId {
    /// Displays the bare message-ID (RFC 5322 Section 3.6.4).
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.0)
    }
}

impl TryFrom<String> for MessageId {
    type Error = crate::error::Error;

    /// Converts a `String` into a validated `MessageId` (RFC 5322 Section 3.6.4).
    fn try_from(s: String) -> Result<Self, Self::Error> {
        Self::new(s)
    }
}

impl TryFrom<&str> for MessageId {
    type Error = crate::error::Error;

    /// Converts a `&str` into a validated `MessageId` (RFC 5322 Section 3.6.4).
    fn try_from(s: &str) -> Result<Self, Self::Error> {
        Self::new(s)
    }
}

impl From<MessageId> for String {
    fn from(m: MessageId) -> Self {
        m.into_inner()
    }
}

/// Validates a bare message-ID per RFC 5322 Section 3.6.4.
///
/// The value must contain exactly one `@`. For outbound/public API values,
/// RFC 5322 Section 3.6.4 permits only modern generated forms:
/// `id-left = dot-atom-text` and `id-right = dot-atom-text / no-fold-literal`.
/// Obsolete parser-only forms remain accepted by the inbound parser via
/// separate recovery helpers.
///
/// RFC 6532 Section 3.2 extends the relevant `atext`, `qtext`, and `dtext`
/// productions to permit UTF-8 non-ASCII.
///
/// # References
/// - RFC 5322 Section 3.6.4
/// - RFC 5322 Section 3.2.3
/// - RFC 5322 Section 3.2.4
/// - RFC 6532 Section 3.2
fn validate_message_id(s: &str) -> crate::Result<()> {
    if s.is_empty() {
        return Err(crate::error::Error::InvalidMessageId(
            "message-ID must not be empty".into(),
        ));
    }

    let Some((id_left, id_right)) = split_strict_message_id_parts(s) else {
        return Err(crate::error::Error::InvalidMessageId(
            "message-ID must contain exactly one '@' \
             (RFC 5322 Section 3.6.4)"
                .into(),
        ));
    };

    if id_left.is_empty() {
        return Err(crate::error::Error::InvalidMessageId(
            "message-ID id-left (before '@') must not be empty \
             (RFC 5322 Section 3.6.4)"
                .into(),
        ));
    }
    if id_right.is_empty() {
        return Err(crate::error::Error::InvalidMessageId(
            "message-ID id-right (after '@') must not be empty \
             (RFC 5322 Section 3.6.4)"
                .into(),
        ));
    }

    // RFC 5322 Section 3.6.4 prose says generated msg-id syntax "only permits
    // the dot-atom-text form on the left-hand side of the @". Appendix A notes
    // that no-fold-quote was removed from the modern msg-id syntax, even
    // though obsolete parser forms still exist in Section 4.5.4.
    if !is_message_id_dot_atom_text(id_left) {
        return Err(crate::error::Error::InvalidMessageId(
            "message-ID id-left must be dot-atom-text \
             (RFC 5322 Section 3.6.4)"
                .into(),
        ));
    }
    if !(is_message_id_dot_atom_text(id_right) || is_message_id_no_fold_literal(id_right)) {
        return Err(crate::error::Error::InvalidMessageId(
            "message-ID id-right must be dot-atom-text or no-fold-literal \
             (RFC 5322 Sections 3.6.4 and 3.2.3)"
                .into(),
        ));
    }

    Ok(())
}

/// Returns `true` when `s` is a syntactically valid bare message-ID body for
/// liberal inbound parsing.
///
/// RFC 5322 Section 4.5.4 still defines obsolete `obs-id-left` /
/// `obs-id-right` forms that parsers may recover from inbound messages, even
/// though generators and strict public validators should not emit them.
///
/// # References
/// - RFC 5322 Section 3.6.4
/// - RFC 5322 Section 4.5.4
/// - RFC 5322 Section 3.2.3
/// - RFC 5322 Section 3.2.4
/// - RFC 6532 Section 3.2
pub(crate) fn is_valid_bare_message_id_body(s: &str) -> bool {
    split_liberal_message_id_parts(s).is_some_and(|(id_left, id_right)| {
        !id_left.is_empty()
            && !id_right.is_empty()
            && (is_message_id_dot_atom_text(id_left) || is_message_id_no_fold_quote(id_left))
            && (is_message_id_dot_atom_text(id_right) || is_message_id_no_fold_literal(id_right))
    })
}

/// Returns `true` when `s` is a syntactically valid bare message-ID body for
/// generated output and strict public API validation.
///
/// Unlike liberal parser recovery, this follows the modern generation rule
/// from RFC 5322 Section 3.6.4: `id-left` is limited to `dot-atom-text`.
///
/// # References
/// - RFC 5322 Section 3.6.4
/// - RFC 5322 Section 3.2.3
/// - RFC 6532 Section 3.2
pub(crate) fn is_strict_bare_message_id_body(s: &str) -> bool {
    split_strict_message_id_parts(s).is_some_and(|(id_left, id_right)| {
        !id_left.is_empty()
            && !id_right.is_empty()
            && is_message_id_dot_atom_text(id_left)
            && (is_message_id_dot_atom_text(id_right) || is_message_id_no_fold_literal(id_right))
    })
}

/// Split a bare message-ID body into `id-left` and `id-right` at the single
/// `@` separator for strict/generated validation.
///
/// RFC 5322 Section 3.6.4 limits generated `msg-id` values to dot-atom
/// `id-left`, so any additional `@` character makes the identifier invalid.
///
/// # References
/// - RFC 5322 Section 3.6.4
fn split_strict_message_id_parts(s: &str) -> Option<(&str, &str)> {
    let (id_left, id_right) = s.split_once('@')?;
    if id_right.contains('@') {
        return None;
    }
    Some((id_left, id_right))
}

/// Split a bare message-ID body into `id-left` and `id-right` at the single
/// unquoted `@` separator for liberal inbound parsing.
///
/// RFC 5322 Section 4.5.4 allows obsolete local-part syntax on the left-hand
/// side, so `@` characters inside quoted strings are not treated as
/// separators during parser recovery.
///
/// # References
/// - RFC 5322 Section 3.6.4
/// - RFC 5322 Section 4.5.4
/// - RFC 5322 Section 3.2.4
fn split_liberal_message_id_parts(s: &str) -> Option<(&str, &str)> {
    let bytes = s.as_bytes();
    let mut in_quotes = false;
    let mut escaped = false;
    let mut at_pos = None;

    for (index, &byte) in bytes.iter().enumerate() {
        if in_quotes {
            if escaped {
                escaped = false;
                continue;
            }

            match byte {
                b'\\' => escaped = true,
                b'"' => in_quotes = false,
                _ => {}
            }
            continue;
        }

        match byte {
            b'"' => in_quotes = true,
            b'@' => {
                if at_pos.is_some() {
                    return None;
                }
                at_pos = Some(index);
            }
            _ => {}
        }
    }

    if in_quotes || escaped {
        return None;
    }

    at_pos.map(|index| (&s[..index], &s[index + 1..]))
}

/// Returns `true` when `s` matches RFC 5322 Section 3.2.3 `dot-atom-text`.
///
/// RFC 6532 Section 3.2 extends `atext` to include UTF-8 non-ASCII octets.
///
/// # References
/// - RFC 5322 Section 3.2.3
/// - RFC 6532 Section 3.2
fn is_message_id_dot_atom_text(s: &str) -> bool {
    if s.is_empty() || s.starts_with('.') || s.ends_with('.') || s.contains("..") {
        return false;
    }

    s.bytes()
        .all(|byte| is_message_id_atext(byte) || byte == b'.' || byte >= 0x80)
}

/// Returns `true` when `s` matches the quoted-string form allowed by obsolete
/// `obs-id-left` parser recovery.
///
/// RFC 6532 Section 3.2 extends `qtext` to include UTF-8 non-ASCII octets.
///
/// # References
/// - RFC 5322 Section 4.5.4
/// - RFC 5322 Section 3.4.1
/// - RFC 5322 Section 3.2.4
/// - RFC 6532 Section 3.2
fn is_message_id_no_fold_quote(s: &str) -> bool {
    let Some(inner) = s
        .strip_prefix('"')
        .and_then(|value| value.strip_suffix('"'))
    else {
        return false;
    };

    let bytes = inner.as_bytes();
    let mut index = 0;
    while index < bytes.len() {
        let byte = bytes[index];
        if byte == b'\\' {
            index += 1;
            if index >= bytes.len() {
                return false;
            }

            let escaped = bytes[index];
            if !(escaped == b'\t' || (0x20..=0x7E).contains(&escaped)) {
                return false;
            }
        } else if !(matches!(byte, 33 | 35..=91 | 93..=126) || byte >= 0x80) {
            return false;
        }
        index += 1;
    }

    true
}

/// Returns `true` when `s` matches RFC 5322 Section 3.6.4 `no-fold-literal`.
///
/// RFC 6532 Section 3.2 extends `dtext` to include UTF-8 non-ASCII octets.
///
/// # References
/// - RFC 5322 Section 3.6.4
/// - RFC 6532 Section 3.2
fn is_message_id_no_fold_literal(s: &str) -> bool {
    let Some(inner) = s
        .strip_prefix('[')
        .and_then(|value| value.strip_suffix(']'))
    else {
        return false;
    };

    inner
        .bytes()
        .all(|byte| matches!(byte, 33..=90 | 94..=126) || byte >= 0x80)
}

/// Returns `true` when `byte` is RFC 5322 `atext`.
///
/// # References
/// - RFC 5322 Section 3.2.3
fn is_message_id_atext(byte: u8) -> bool {
    byte.is_ascii_alphanumeric()
        || matches!(
            byte,
            b'!' | b'#'
                | b'$'
                | b'%'
                | b'&'
                | b'\''
                | b'*'
                | b'+'
                | b'-'
                | b'/'
                | b'='
                | b'?'
                | b'^'
                | b'_'
                | b'`'
                | b'{'
                | b'|'
                | b'}'
                | b'~'
        )
}

// ---------------------------------------------------------------------------

/// A parsed email message.
///
/// Produced by [`crate::parse_email`]. All fields are owned.
/// Missing or unparseable optional fields are `None`.
///
/// # References
/// - RFC 5322 (message structure)
/// - RFC 2045–2046 (MIME body parts)
#[non_exhaustive]
#[derive(Debug, Clone, Default, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct ParsedEmail {
    /// Message-ID with angle brackets stripped (RFC 5322 Section 3.6.4).
    ///
    /// This field uses `String` rather than [`MessageId`] because parsed
    /// messages may originate from non-conformant sources whose message IDs
    /// do not pass strict RFC 5322 validation. The parser follows Postel's
    /// law: accept what you can, even if the value is technically malformed.
    /// [`OutgoingEmail::in_reply_to`] and [`OutgoingEmail::references`] use
    /// the validated [`MessageId`] type to ensure outgoing messages are
    /// strictly conformant.
    pub message_id: Option<String>,
    /// All `In-Reply-To` message-ids, angle brackets stripped (RFC 5322 Section 3.6.4).
    ///
    /// RFC 5322: `in-reply-to = "In-Reply-To:" 1*msg-id CRLF` — multiple
    /// message-IDs are valid. Each element is a single message-ID without
    /// angle brackets.
    ///
    /// Uses `String` rather than [`MessageId`] for the same reason as
    /// [`message_id`](Self::message_id): parsed messages may contain
    /// non-conformant IDs that would fail strict validation.
    pub in_reply_to: Vec<String>,
    /// All `References` message-ids, angle brackets stripped (RFC 5322 Section 3.6.4).
    ///
    /// RFC 5322: `references = "References:" 1*msg-id CRLF`. Each element is
    /// a single message-ID without angle brackets.
    ///
    /// Uses `String` rather than [`MessageId`] for the same reason as
    /// [`message_id`](Self::message_id): parsed messages may contain
    /// non-conformant IDs that would fail strict validation.
    pub references: Vec<String>,
    /// Decoded subject (RFC 5322 Section 3.6.5, RFC 2047 encoded words decoded).
    pub subject: Option<String>,
    /// Originator mailboxes (RFC 5322 Section 3.6.2: `from = "From:" mailbox-list`).
    pub from: Vec<Address>,
    /// The agent responsible for actual transmission of the message
    /// (RFC 5322 Section 3.6.2: `sender = "Sender:" mailbox`).
    ///
    /// Contains exactly one mailbox. Required when `From` contains multiple
    /// addresses; otherwise optional. `None` when the header is absent.
    pub sender: Option<Address>,
    /// To recipients (RFC 5322 Section 3.6.3).
    pub to: Vec<Address>,
    /// Cc recipients (RFC 5322 Section 3.6.3).
    pub cc: Vec<Address>,
    /// Bcc recipients (RFC 5322 Section 3.6.3).
    pub bcc: Vec<Address>,
    /// Reply-To addresses (RFC 5322 Section 3.6.2).
    pub reply_to: Vec<Address>,
    /// Parsed date with original timezone offset preserved (RFC 5322 Section 3.3).
    pub date: Option<DateTime>,
    /// First `text/plain` body part, decoded to UTF-8.
    pub body_text: Option<String>,
    /// First `text/html` body part, decoded to UTF-8.
    pub body_html: Option<String>,
    /// Detected attachments with IMAP section numbers.
    pub attachments: Vec<ParsedAttachment>,
    /// Raw header bytes as a `String` (everything before the header/body separator).
    pub raw_headers: String,
    /// Optional fields not defined by RFC 5322 (RFC 5322 Section 3.6.8).
    ///
    /// Contains all headers that are not one of the well-known structured
    /// headers (From, To, Cc, Bcc, Reply-To, Subject, Date, Message-ID,
    /// In-Reply-To, References, Sender, Content-Type,
    /// Content-Transfer-Encoding, MIME-Version), plus any top-level
    /// `Content-Disposition` or `Content-ID` field preserved for RFC 2183
    /// Section 2.10 and RFC 2045 Section 7 consumers. Each entry is a
    /// `(lowercase-name, decoded-value)` pair, preserving the order they
    /// appeared in the message.
    pub extra_headers: Vec<(String, String)>,
    /// Total byte count of the input.
    pub size: u64,
}

impl ParsedEmail {
    /// Convert extra headers to validated `(HeaderName, String)` pairs
    /// suitable for use in [`OutgoingEmail::extra_headers`].
    ///
    /// Headers whose names fail RFC 5322 Section 2.2 validation are
    /// silently dropped — such names originate from non-conformant
    /// messages and cannot be reproduced in well-formed output.
    pub fn validated_extra_headers(&self) -> Vec<(HeaderName, String)> {
        self.extra_headers
            .iter()
            .filter_map(|(name, value)| {
                HeaderName::new(name.clone())
                    .ok()
                    .map(|hn| (hn, value.clone()))
            })
            .collect()
    }
}

/// An email address with optional display name.
///
/// # References
/// - RFC 5322 Section 3.4 (address specification)
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Address {
    /// Display name, decoded from RFC 2047 encoded words if present.
    pub name: Option<String>,
    /// Email address (`addr-spec` form).
    pub email: String,
}

impl Address {
    /// Creates an address with only an email, validating the syntax.
    ///
    /// # Errors
    ///
    /// Returns [`crate::Error::InvalidAddress`] if the email is not valid
    /// per RFC 5322 Section 3.4.
    pub fn new(email: impl Into<String>) -> crate::Result<Self> {
        let addr = Self {
            name: None,
            email: email.into(),
        };
        crate::builder::validate_address(&addr)?;
        Ok(addr)
    }

    /// Creates an address with a display name and email, validating the syntax.
    ///
    /// # Errors
    ///
    /// Returns [`crate::Error::InvalidAddress`] if the email is not valid
    /// per RFC 5322 Section 3.4.
    pub fn with_name(name: impl Into<String>, email: impl Into<String>) -> crate::Result<Self> {
        let addr = Self {
            name: Some(name.into()),
            email: email.into(),
        };
        crate::builder::validate_address(&addr)?;
        Ok(addr)
    }

    /// Creates an `Address` **without validating** the email syntax.
    ///
    /// # You almost certainly want [`Address::new`] or [`Address::with_name`] instead
    ///
    /// Those constructors validate the email address against RFC 5322
    /// Section 3.4 and reject malformed input. An `Address` built with
    /// `new_unchecked` may contain syntax that is invalid for outgoing
    /// mail, which can cause:
    ///
    /// - Rejected `RCPT TO` commands at the SMTP layer.
    /// - Malformed `From`/`To`/`Cc` headers that downstream MTAs or MUAs
    ///   cannot parse.
    /// - Messages that silently disappear into spam filters or bounce
    ///   queues.
    ///
    /// # When this method is appropriate
    ///
    /// This exists for **parser and protocol-conversion code** that must
    /// accept addresses already received from the network, where Postel's
    /// law applies (RFC 5322 Section 3.4): be liberal in what you accept.
    /// For example, an IMAP ENVELOPE address or a `From:` header parsed
    /// from an incoming message may contain syntax that is technically
    /// non-conformant but still meaningful. Rejecting it would discard
    /// data the user needs to see.
    ///
    /// If you are **building a new outgoing message**, use [`Address::new`]
    /// or [`Address::with_name`] — they enforce the same validation the
    /// message builder applies and will catch mistakes at construction
    /// time rather than at send time.
    pub fn new_unchecked(name: Option<String>, email: String) -> Self {
        Self { name, email }
    }
}

/// RFC 5322 specials that require a display name to be quoted.
const SPECIALS: &[char] = &[
    '(', ')', '<', '>', '[', ']', ':', ';', '@', '\\', ',', '.', '"',
];

impl std::fmt::Display for Address {
    /// Formats the address per RFC 5322 Section 3.4.
    ///
    /// - Non-ASCII display names are RFC 2047 encoded (RFC 5322 Section 2.2
    ///   requires header field bodies to be US-ASCII; RFC 2047 Section 5
    ///   defines the encoded-word mechanism for non-ASCII text).
    /// - ASCII display names containing specials are quoted per RFC 5322 Section 3.2.4.
    /// - Without display name: bare `email`
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match &self.name {
            // RFC 5322 Section 3.4: display-name is a `phrase` (`1*word`).
            // Whitespace alone does not form a valid word, so treat it as absent.
            Some(name) if !name.trim().is_empty() => {
                if !name.is_ascii() || name.bytes().any(|b| (b < 0x20 && b != b'\t') || b == 0x7F) {
                    // RFC 5322 Section 2.2: field bodies must be US-ASCII printable.
                    // RFC 5322 Section 3.2.3: atext excludes control characters.
                    // HTAB (0x09) is valid WSP per RFC 5322 Section 2.2.
                    // RFC 2047 Section 5: use encoded-words for non-ASCII/non-printable text.
                    let encoded = crate::builder::encode_rfc2047_if_needed(name);
                    write!(f, "{encoded} <{}>", self.email)
                } else if name.contains("=?") {
                    // RFC 2047 Section 5: an unquoted phrase may contain
                    // encoded-words. A display name that literally contains
                    // `=?` would be mis-decoded by the parser. Quoting
                    // prevents this: RFC 2047 Section 5 says encoded-words
                    // MUST NOT appear inside a quoted-string.
                    let escaped = name.replace('\\', "\\\\").replace('"', "\\\"");
                    write!(f, "\"{escaped}\" <{}>", self.email)
                } else if name.chars().any(|c| SPECIALS.contains(&c)) {
                    let escaped = name.replace('\\', "\\\\").replace('"', "\\\"");
                    write!(f, "\"{escaped}\" <{}>", self.email)
                } else {
                    write!(f, "{name} <{}>", self.email)
                }
            }
            _ => write!(f, "{}", self.email),
        }
    }
}

impl std::str::FromStr for Address {
    type Err = crate::error::Error;

    /// Parses an address from a string (RFC 5322 Section 3.4).
    ///
    /// Accepts both `Display Name <email>` and bare `email` forms.
    /// Decodes RFC 2047 encoded words in the display name (RFC 2047 Section 5).
    #[allow(clippy::too_many_lines)]
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let s = s.trim();
        if s.is_empty() {
            return Err(crate::error::Error::InvalidAddress(
                "empty address string".into(),
            ));
        }

        // Try "Display Name <email>" form
        if let Some(angle_start) = s.rfind('<') {
            if let Some(angle_end) = s.rfind('>') {
                if angle_end > angle_start {
                    let trailing = &s[angle_end + 1..];
                    validate_trailing_cfws(
                        trailing,
                        s,
                        "angle-addr",
                        "RFC 5322 Section 3.4 / Section 3.2.2",
                    )?;
                    let mut email = s[angle_start + 1..angle_end].trim().to_string();
                    // RFC 5322 Section 4.4: strip obsolete source route
                    // (obs-route = obs-domain-list ":"). Example:
                    // `<@hop1,@hop2:user@domain>` → `user@domain`.
                    if email.starts_with('@') {
                        if let Some(colon) = email.find(':') {
                            email = email[colon + 1..].trim().to_string();
                        }
                    }
                    let name_part = s[..angle_start].trim();
                    let name = crate::parser::normalize_display_name_phrase(name_part);
                    if email.is_empty() {
                        return Err(crate::error::Error::InvalidAddress(
                            "empty email in angle brackets".into(),
                        ));
                    }
                    let addr = Self { name, email };
                    // RFC 5322 Section 3.4.1 / RFC 6531 Section 3.3: parse
                    // the display name leniently, but validate the addr-spec
                    // with the same rules the builder enforces for emission.
                    crate::builder::validate_address(&addr)?;
                    return Ok(addr);
                }
            }
        }

        // Bare email — RFC 5322 Section 3.4.1: `addr-spec = local-part "@" domain`.
        // Both local-part and domain must be non-empty.
        //
        // Also handles comments (RFC 5322 Section 3.2.2) before or after the
        // addr-spec: `addr-spec (comment)` or `(comment) addr-spec`.  The
        // comment text is extracted as the display name, matching the behavior
        // of `parse_single_address` in the parser.
        if s.find('@').is_some() {
            // Check for a parenthesized comment: `user@host (Name)` (trailing)
            // or `(Name) user@host` (leading).
            // RFC 5322 Section 3.2.2: `comment = "(" *([FWS] ccontent) [FWS] ")"`.
            let (addr_part, comment_name) = if let Some(paren_start) =
                crate::parser::find_paren_outside_quotes(s)
            {
                let before_paren = s[..paren_start].trim();
                let comment_and_rest = &s[paren_start..];
                // Extract comment content, handling nested parentheses
                // (RFC 5322 Section 3.2.2).
                let after_paren = &s[paren_start + 1..];
                let name = strip_comment_delimiters(after_paren);
                let comment_name = if name.is_empty() { None } else { Some(name) };

                if !before_paren.is_empty() && before_paren.contains('@') {
                    // Trailing comment: `user@host (Name)`
                    validate_trailing_cfws(
                        comment_and_rest,
                        s,
                        "addr-spec comment",
                        "RFC 5322 Section 3.4.1 / Section 3.2.2",
                    )?;
                    (before_paren, comment_name)
                } else {
                    // Leading comment: `(Name) user@host`
                    // RFC 5322 Section 3.2.2: CFWS (including comments) may
                    // appear before the addr-spec.
                    // Find the text after the closing paren for the addr-spec.
                    let close_paren = find_matching_close_paren(&s[paren_start..]);
                    let after_comment = s.get(paren_start + close_paren + 1..).unwrap_or("").trim();
                    if !after_comment.is_empty() && after_comment.contains('@') {
                        (after_comment, comment_name)
                    } else {
                        // `@` was inside the comment, not in the address
                        (before_paren, comment_name)
                    }
                }
            } else {
                (s, None)
            };

            // Find `@` in the addr_part (not in the original string `s`),
            // since `addr_part` may be a shorter substring when a comment
            // was stripped. Fall back to the full addr_part length if there
            // is no `@` in addr_part (which means the `@` was inside the
            // comment, not in the address).
            let at_in_addr = addr_part.find('@').unwrap_or(addr_part.len());
            let local = &addr_part[..at_in_addr];
            let domain = addr_part.get(at_in_addr + 1..).unwrap_or("");
            if local.is_empty() || domain.is_empty() {
                return Err(crate::error::Error::InvalidAddress(format!(
                    "invalid bare email (empty local-part or domain): {s} \
                     (RFC 5322 Section 3.4.1)"
                )));
            }
            let addr = Self {
                name: comment_name,
                email: addr_part.to_string(),
            };
            // RFC 5322 Section 3.4.1 / RFC 6531 Section 3.3: bare addr-spec
            // syntax must satisfy the same validation rules used by the
            // message builder so public parsing and emission stay aligned.
            crate::builder::validate_address(&addr)?;
            return Ok(addr);
        }

        Err(crate::error::Error::InvalidAddress(format!(
            "cannot parse address: {s}"
        )))
    }
}

/// Finds the offset (from the start of `s`) of the closing `)` that matches
/// the opening `(` at position 0, respecting nesting and backslash escapes.
///
/// Returns `s.len() - 1` if no matching close paren is found (Postel's law:
/// treat the rest of the string as the comment body).
///
/// # References
/// - RFC 5322 Section 3.2.2 (nested comments, quoted-pair in comments)
fn find_matching_close_paren(s: &str) -> usize {
    let bytes = s.as_bytes();
    if bytes.is_empty() || bytes[0] != b'(' {
        return 0;
    }
    let mut depth: u32 = 0;
    let mut i = 0;
    while i < bytes.len() {
        match bytes[i] {
            b'\\' => {
                // Skip escaped character (RFC 5322 Section 3.2.4 quoted-pair).
                i += 2;
                continue;
            }
            b'(' => {
                depth = depth.saturating_add(1);
            }
            b')' => {
                depth = depth.saturating_sub(1);
                if depth == 0 {
                    return i;
                }
            }
            _ => {}
        }
        i += 1;
    }
    // No matching close paren found — use end of string.
    s.len().saturating_sub(1)
}

/// Extracts the text content from inside a parenthesized comment, handling
/// nested parentheses and backslash escaping per RFC 5322 Section 3.2.2.
///
/// `input` should be the text AFTER the opening `(`.  Returns the trimmed
/// content with the trailing `)` stripped.  Nested parentheses are preserved
/// in the output.
///
/// # References
/// - RFC 5322 Section 3.2.2 (comment = "(" *([FWS] ccontent) [FWS] ")")
/// - RFC 5322 Section 3.2.4 (quoted-pair = "\" (VCHAR / WSP))
fn strip_comment_delimiters(input: &str) -> String {
    let bytes = input.as_bytes();
    let mut depth: u32 = 1;
    let mut end = input.len();
    let mut i = 0;
    while i < bytes.len() {
        match bytes[i] {
            b'\\' => {
                // Skip the next character (quoted-pair per RFC 5322 Section 3.2.4).
                i += 2;
                continue;
            }
            b'(' => {
                depth = depth.saturating_add(1);
            }
            b')' => {
                depth = depth.saturating_sub(1);
                if depth == 0 {
                    end = i;
                    break;
                }
            }
            _ => {}
        }
        i += 1;
    }
    // RFC 5322 Section 3.2.2: resolve quoted-pair escapes (`\X` → `X`)
    // within the extracted comment content.
    unescape_quoted_string(input[..end].trim())
}

/// Returns `true` if the input contains only CFWS after trimming leading FWS.
///
/// Used to validate text after an `angle-addr` where RFC 5322 Section 3.4
/// permits only trailing CFWS, not arbitrary atoms or phrases.
///
/// # References
/// - RFC 5322 Section 3.2.2 (comments / CFWS)
/// - RFC 5322 Section 3.4 (angle-addr)
fn is_cfws_only(mut input: &str) -> bool {
    loop {
        input = input.trim_start();
        if input.is_empty() {
            return true;
        }
        if !input.starts_with('(') {
            return false;
        }

        let close = find_matching_close_paren(input);
        if input.as_bytes().get(close) != Some(&b')') {
            return false;
        }
        input = &input[close + 1..];
    }
}

/// Reject trailing non-CFWS text after a parsed address component.
///
/// # References
/// - RFC 5322 Section 3.2.2 (comments / CFWS)
/// - RFC 5322 Sections 3.4-3.4.1 (address forms)
fn validate_trailing_cfws(
    trailing: &str,
    original: &str,
    context: &str,
    rfc_sections: &str,
) -> Result<(), crate::error::Error> {
    if trailing.is_empty() || is_cfws_only(trailing) {
        return Ok(());
    }
    Err(crate::error::Error::InvalidAddress(format!(
        "invalid trailing text after {context}: {original} ({rfc_sections})"
    )))
}

/// Unescapes a quoted-string: removes backslash from `\\` → `\` and `\"` → `"`.
///
/// Per RFC 5322 Section 3.2.4, a `quoted-pair` is `"\" (VCHAR / WSP)`.
fn unescape_quoted_string(input: &str) -> String {
    let mut result = String::with_capacity(input.len());
    let mut chars = input.chars();
    while let Some(c) = chars.next() {
        if c == '\\' {
            if let Some(next) = chars.next() {
                result.push(next);
            } else {
                result.push(c);
            }
        } else {
            result.push(c);
        }
    }
    result
}

/// Metadata for an attachment found during parsing.
///
/// Does not contain the attachment binary data — use the `section` field
/// to fetch the content on-demand via IMAP `BODY.PEEK[section]`.
///
/// # References
/// - RFC 2183 (Content-Disposition)
/// - RFC 3501 Section 6.4.5 (MIME section numbers)
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct ParsedAttachment {
    /// Filename from `Content-Disposition` or `Content-Type` name parameter.
    pub filename: Option<String>,
    /// MIME content type (e.g., `"application/pdf"`).
    pub content_type: String,
    /// Content-ID header value, stripped of angle brackets (RFC 2392).
    pub content_id: Option<String>,
    /// `true` if `Content-Disposition: inline` or has a `Content-ID`.
    pub is_inline: bool,
    /// Size of the MIME part body in bytes (if available).
    pub size: Option<u64>,
    /// IMAP MIME section number (e.g., `"2"`, `"1.2"`) for on-demand fetch.
    pub section: Option<String>,
}

/// Day-of-week abbreviations per RFC 5322 Section 3.3.
const DOW_NAMES: [&str; 7] = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];

/// Month abbreviations per RFC 5322 Section 3.3.
const MONTH_NAMES: [&str; 12] = [
    "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
];

/// Date-time with timezone offset preserved.
///
/// # Equality and Ordering
///
/// `PartialEq`, `Eq`, `Hash`, `PartialOrd`, and `Ord` are implemented manually
/// rather than derived. All comparisons normalize to UTC first, so two values
/// representing the same instant with different timezone offsets are considered
/// equal (e.g., `2025-01-01T00:00:00+0000` == `2024-12-31T19:00:00-0500`).
///
/// # References
/// - RFC 5322 Section 3.3 (date-time specification)
#[non_exhaustive]
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct DateTime {
    /// Year (e.g., 2025).
    pub(crate) year: u16,
    /// Month (1–12).
    pub(crate) month: u8,
    /// Day of month (1–31).
    pub(crate) day: u8,
    /// Hour (0–23).
    pub(crate) hour: u8,
    /// Minute (0–59).
    pub(crate) minute: u8,
    /// Second (0–59).
    pub(crate) second: u8,
    /// Timezone offset from UTC in minutes (e.g., +0530 → 330, −0800 → −480).
    pub(crate) tz_offset_minutes: i16,
}

impl DateTime {
    /// Creates a new `DateTime` from individual components.
    ///
    /// Fields are stored as-is; clamping to valid ranges happens at
    /// formatting / comparison time (see [`Self::to_rfc5322_string`],
    /// [`Self::to_unix_timestamp`]).
    ///
    /// # References
    /// - RFC 5322 Section 3.3 (date-time specification)
    pub fn new(
        year: u16,
        month: u8,
        day: u8,
        hour: u8,
        minute: u8,
        second: u8,
        tz_offset_minutes: i16,
    ) -> Self {
        Self {
            year,
            month,
            day,
            hour,
            minute,
            second,
            tz_offset_minutes,
        }
    }

    /// Returns the year (e.g., 2025).
    pub fn year(&self) -> u16 {
        self.year
    }

    /// Returns the month, clamped to 1–12 (RFC 5322 Section 3.3).
    pub fn month(&self) -> u8 {
        self.month.clamp(1, 12)
    }

    /// Returns the day of month, clamped to a valid range for the
    /// current month and year (RFC 5322 Section 3.3).
    pub fn day(&self) -> u8 {
        let month = self.month.clamp(1, 12);
        let max_day = Self::days_in_month(month, self.year);
        self.day.clamp(1, max_day)
    }

    /// Returns the hour, clamped to 0–23 (RFC 5322 Section 3.3).
    pub fn hour(&self) -> u8 {
        self.hour.clamp(0, 23)
    }

    /// Returns the minute, clamped to 0–59 (RFC 5322 Section 3.3).
    pub fn minute(&self) -> u8 {
        self.minute.clamp(0, 59)
    }

    /// Returns the second, clamped to 0–60 (60 is valid for leap
    /// seconds per RFC 5322 Section 3.3).
    pub fn second(&self) -> u8 {
        self.second.clamp(0, 60)
    }

    /// Returns the timezone offset from UTC in minutes (e.g., +0530 → 330,
    /// −0800 → −480), clamped to ±1439 (RFC 5322 Section 3.3).
    pub fn tz_offset_minutes(&self) -> i16 {
        self.tz_offset_minutes.clamp(-1439, 1439)
    }

    /// Converts this date-time to a Unix timestamp (seconds since 1970-01-01T00:00:00Z).
    ///
    /// The timezone offset is applied so the result is always UTC-based.
    /// Uses the same civil-to-days algorithm as the builder.
    ///
    /// # References
    /// - RFC 5322 Section 3.3
    pub fn to_unix_timestamp(&self) -> i64 {
        // Clamp all fields to valid ranges, consistent with the string
        // formatters (RFC 5322 §3.3). This ensures the timestamp matches
        // the date-time that would be printed by to_rfc5322_string().
        let (month, day, hour, minute, second) = self.clamped_fields();
        let days = Self::civil_to_days(i32::from(self.year), u32::from(month), u32::from(day));
        // RFC 5322 Section 3.3 allows second=60 (leap second), but Unix
        // timestamps have no leap-second representation.  Clamp to 59 so
        // the timestamp stays within the correct minute (RFC 5322 §3.3).
        let second = if second >= 60 { 59 } else { second };
        let secs =
            days * 86400 + i64::from(hour) * 3600 + i64::from(minute) * 60 + i64::from(second);
        // Clamp timezone offset to the valid RFC 5322 Section 3.3 range
        // (±23:59 = ±1439 minutes), consistent with tz_parts() used by
        // to_rfc5322_string(). Without this clamp, an out-of-range offset
        // produces a timestamp that disagrees with the formatted string.
        let tz = i64::from(self.tz_offset_minutes.clamp(-1439, 1439));
        secs - tz * 60
    }

    /// Creates a `DateTime` from a Unix timestamp (seconds since epoch) and a
    /// timezone offset in minutes.
    ///
    /// # References
    /// - RFC 5322 Section 3.3
    #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
    pub fn from_unix_timestamp(timestamp: i64, tz_offset_minutes: i16) -> Self {
        // Clamp timezone offset to the valid RFC 5322 Section 3.3 range
        // (±23:59 = ±1439 minutes) before computing local time. This
        // ensures the stored offset matches what to_rfc5322_string() and
        // to_unix_timestamp() will use, preserving round-trip consistency.
        let tz_offset_minutes = tz_offset_minutes.clamp(-1439, 1439);
        // Apply timezone offset to get local time
        let local_secs = timestamp + i64::from(tz_offset_minutes) * 60;
        let days = local_secs.div_euclid(86400);
        let time_secs = local_secs.rem_euclid(86400) as u64;

        let (year, month, day) = Self::civil_from_days(days);

        // Clamp year to 0–9999 to prevent silent truncation when casting
        // i32 → u16. Negative years (BCE dates) and years above 9999 are
        // outside the RFC 5322 Section 3.3 representable range (year =
        // 4*DIGIT). Without this clamp, negative years wrap to large u16
        // values, corrupting the date and breaking round-trips.
        let year = year.clamp(0, 9999) as u16;

        Self {
            year,
            month: month as u8,
            day: day as u8,
            hour: (time_secs / 3600) as u8,
            minute: ((time_secs % 3600) / 60) as u8,
            second: (time_secs % 60) as u8,
            tz_offset_minutes,
        }
    }

    /// Returns the current UTC time as a `DateTime`.
    ///
    /// # References
    /// - RFC 5322 Section 3.3
    #[allow(
        clippy::cast_possible_truncation,
        clippy::cast_sign_loss,
        clippy::cast_possible_wrap
    )]
    pub fn now() -> Self {
        use std::time::{SystemTime, UNIX_EPOCH};

        let secs = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap_or_default()
            .as_secs();

        Self::from_unix_timestamp(secs as i64, 0)
    }

    /// Returns the number of days in the given month, accounting for leap years.
    ///
    /// The RFC 5322 Section 3.3 grammar allows day values 1-31 for all months,
    /// but calendar-valid dates require per-month limits (e.g., Feb has 28 or 29).
    ///
    /// # References
    /// - RFC 5322 Section 3.3 (date-time specification)
    fn days_in_month(month: u8, year: u16) -> u8 {
        match month {
            2 => {
                // Leap year: divisible by 4, except centuries unless divisible by 400
                let y = u32::from(year);
                if (y % 4 == 0 && y % 100 != 0) || (y % 400 == 0) {
                    29
                } else {
                    28
                }
            }
            4 | 6 | 9 | 11 => 30,
            // Months 1, 3, 5, 7, 8, 10, 12 all have 31 days.
            // month is clamped to 1-12 before calling; wildcard covers 31-day months.
            _ => 31,
        }
    }

    /// Returns clamped date-time fields conforming to RFC 5322 Section 3.3.
    ///
    /// Clamps each field to its valid range:
    /// - month: 1–12
    /// - day: 1–`days_in_month(month, year)` (accounts for per-month limits and
    ///   leap years, so invalid dates like Feb 31 are clamped to Feb 28/29)
    /// - hour: 0–23
    /// - minute: 0–59
    /// - second: 0–60 (60 is valid for leap seconds per RFC 5322 Section 3.3)
    ///
    /// # References
    /// - RFC 5322 Section 3.3 (date-time specification)
    fn clamped_fields(&self) -> (u8, u8, u8, u8, u8) {
        let month = self.month.clamp(1, 12);
        // Clamp day against the actual number of days in the clamped month
        // and year, not a flat 31 (RFC 5322 Section 3.3).
        let max_day = Self::days_in_month(month, self.year);
        let day = self.day.clamp(1, max_day);
        (
            month,
            day,
            self.hour.clamp(0, 23),
            self.minute.clamp(0, 59),
            self.second.clamp(0, 60),
        )
    }

    /// Returns the day of week for this date.
    ///
    /// Returns 0 for Sunday, 1 for Monday, ..., 6 for Saturday.
    /// Uses clamped month/day values for consistency with `to_rfc5322_string()`
    /// (RFC 5322 Section 3.3).
    ///
    /// # References
    /// - RFC 5322 Section 3.3
    #[allow(clippy::cast_sign_loss)]
    pub fn weekday(&self) -> u8 {
        let (month, day, _, _, _) = self.clamped_fields();
        let days = Self::civil_to_days(i32::from(self.year), u32::from(month), u32::from(day));
        // 1970-01-01 was Thursday (4); result is always in [0, 6]
        (((days % 7) + 4 + 7) % 7) as u8
    }

    /// Formats this date-time as an RFC 5322 date-time string.
    ///
    /// Produces the format: `day-of-week, DD Mon YYYY HH:MM:SS ±HHMM`
    /// (e.g., `"Thu, 13 Feb 2025 15:47:33 +0000"`).
    ///
    /// All fields are clamped to their valid ranges per RFC 5322 Section 3.3
    /// to ensure well-formed output (Postel's law: be conservative in what
    /// you send).
    ///
    /// # References
    /// - RFC 5322 Section 3.3
    pub fn to_rfc5322_string(&self) -> String {
        let (month, day, hour, minute, second) = self.clamped_fields();
        let dow = self.weekday();
        let dow_name = DOW_NAMES[dow as usize];
        // month is already clamped to [1, 12] by clamped_fields()
        let month_name = MONTH_NAMES[(month - 1) as usize];
        let (sign, tz_h, tz_m) = self.tz_parts();
        format!(
            "{dow_name}, {:02} {month_name} {:04} {:02}:{:02}:{:02} {sign}{tz_h:02}{tz_m:02}",
            day, self.year, hour, minute, second,
        )
    }

    /// Formats this date-time as an ISO 8601 / RFC 3339 string.
    ///
    /// Produces the format: `YYYY-MM-DDTHH:MM:SS±HH:MM`
    /// (e.g., `"2025-02-13T15:47:33+00:00"`).
    ///
    /// All fields are clamped to their valid ranges for consistency with
    /// `to_rfc5322_string()`.
    ///
    /// This format is widely used in JSON APIs and structured data exchange.
    ///
    /// # References
    /// - ISO 8601 (date-time representation)
    /// - RFC 3339 (date-time on the Internet)
    pub fn to_iso8601_string(&self) -> String {
        let (month, day, hour, minute, second) = self.clamped_fields();
        let (sign, tz_h, tz_m) = self.tz_parts();
        format!(
            "{:04}-{:02}-{:02}T{:02}:{:02}:{:02}{sign}{tz_h:02}:{tz_m:02}",
            self.year, month, day, hour, minute, second,
        )
    }

    /// Parses an RFC 5322 date-time string into a `DateTime`.
    ///
    /// Accepts: `[day-of-week ","] day month year hour ":" minute [":" second] zone`
    ///
    /// Strips CFWS (comments and folding white space) before parsing, as
    /// allowed by the obsolete date syntax (RFC 5322 Section 4.3).
    ///
    /// Returns `None` if the input is not a valid RFC 5322 date-time.
    ///
    /// # References
    /// - RFC 5322 Section 3.3
    /// - RFC 5322 Section 4.3 (obsolete syntax)
    pub fn parse_rfc5322(input: &str) -> Option<Self> {
        crate::parser::parse_rfc5322_date(input)
    }

    /// Returns the timezone offset decomposed as `(sign, hours, minutes)`.
    ///
    /// # References
    /// - RFC 5322 Section 3.3 (zone = ("+" / "-") 4DIGIT)
    fn tz_parts(&self) -> (char, u16, u16) {
        // Clamp to the valid RFC 5322 range: zone hours 0-23, minutes 0-59,
        // so the maximum magnitude is 23*60+59 = 1439 (RFC 5322 Section 3.3).
        let clamped = self.tz_offset_minutes.clamp(-1439, 1439);
        let sign = if clamped >= 0 { '+' } else { '-' };
        let abs = clamped.unsigned_abs();
        (sign, abs / 60, abs % 60)
    }

    /// Converts days since Unix epoch to `(year, month, day)`.
    ///
    /// Algorithm from Howard Hinnant's date algorithms.
    #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
    fn civil_from_days(z: i64) -> (i32, u32, u32) {
        let z = z + 719_468;
        let era = (if z >= 0 { z } else { z - 146_096 }) / 146_097;
        let doe = (z - era * 146_097) as u32;
        let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
        let y = i64::from(yoe) + era * 400;
        let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
        let mp = (5 * doy + 2) / 153;
        let d = doy - (153 * mp + 2) / 5 + 1;
        let m = if mp < 10 { mp + 3 } else { mp - 9 };
        let y = if m <= 2 { y + 1 } else { y };
        (y as i32, m, d)
    }

    /// Converts `(year, month, day)` to days since Unix epoch.
    ///
    /// Algorithm from Howard Hinnant's date algorithms.
    #[allow(clippy::cast_sign_loss, clippy::cast_possible_wrap)]
    fn civil_to_days(year: i32, month: u32, day: u32) -> i64 {
        let y = if month <= 2 {
            i64::from(year) - 1
        } else {
            i64::from(year)
        };
        let m = if month <= 2 { month + 9 } else { month - 3 };
        let era = (if y >= 0 { y } else { y - 399 }) / 400;
        let yoe = (y - era * 400) as u64;
        let doy = (153 * u64::from(m) + 2) / 5 + u64::from(day) - 1;
        let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
        era * 146_097 + doe as i64 - 719_468
    }
}

impl PartialEq for DateTime {
    /// Compares two `DateTime` values by their UTC-normalized timestamps,
    /// consistent with the `Ord` implementation.
    ///
    /// # References
    /// - RFC 5322 Section 3.3 (date-time specification)
    fn eq(&self, other: &Self) -> bool {
        self.to_unix_timestamp() == other.to_unix_timestamp()
    }
}

impl Eq for DateTime {}

impl std::hash::Hash for DateTime {
    /// Hashes by UTC-normalized timestamp, consistent with `Eq` and `Ord`.
    ///
    /// Two `DateTime` values representing the same UTC instant (but with
    /// different timezone offsets) will produce the same hash, matching the
    /// `Eq` behavior.
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        self.to_unix_timestamp().hash(state);
    }
}

impl PartialOrd for DateTime {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for DateTime {
    /// Compares two `DateTime` values by their UTC-normalized timestamps.
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        self.to_unix_timestamp().cmp(&other.to_unix_timestamp())
    }
}

impl std::fmt::Display for DateTime {
    /// Formats this date-time for human-readable display.
    ///
    /// All fields are clamped to their valid ranges, consistent with
    /// `to_rfc5322_string()` and `to_iso8601_string()` (RFC 5322 §3.3).
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let (month, day, hour, minute, second) = self.clamped_fields();
        let (sign, tz_h, tz_m) = self.tz_parts();
        write!(
            f,
            "{:04}-{:02}-{:02} {:02}:{:02}:{:02} {sign}{tz_h:02}{tz_m:02}",
            self.year, month, day, hour, minute, second,
        )
    }
}

impl std::str::FromStr for DateTime {
    type Err = crate::error::Error;

    /// Parses an RFC 5322 date-time string into a `DateTime`.
    ///
    /// Accepts: `[day-of-week ","] day month year hour ":" minute [":" second] zone`
    ///
    /// This enables the ergonomic `"Thu, 13 Feb 2025 15:47:33 +0000".parse::<DateTime>()`
    /// pattern via the standard `FromStr` trait.
    ///
    /// # References
    /// - RFC 5322 Section 3.3
    /// - RFC 5322 Section 4.3 (obsolete syntax)
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Self::parse_rfc5322(s).ok_or_else(|| {
            crate::error::Error::InvalidDate(format!("cannot parse RFC 5322 date: {s}"))
        })
    }
}

/// An outgoing email to be built into raw RFC 5322 bytes.
///
/// Used as input to [`crate::build_message`].
///
/// # References
/// - RFC 5322 (message format)
/// - RFC 2046 (MIME multipart)
#[non_exhaustive]
#[derive(Debug, Default, Clone, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct OutgoingEmail {
    /// Originator mailboxes (RFC 5322 Section 3.6.2: `from = "From:" mailbox-list`).
    ///
    /// Must contain at least one address. When multiple addresses are present,
    /// `sender` **must** be set per RFC 5322 Section 3.6.2:
    /// "If the from field contains more than one mailbox specification in the
    /// mailbox-list, then the sender field, containing the field value
    /// corresponding to the responsible agent, MUST appear in the message."
    pub from: Vec<Address>,
    /// The agent responsible for actual transmission of the message
    /// (RFC 5322 Section 3.6.2: `sender = "Sender:" mailbox`).
    ///
    /// Required when `from` contains more than one address. Optional when
    /// `from` contains exactly one address.
    pub sender: Option<Address>,
    /// To recipients (RFC 5322 Section 3.6.3).
    pub to: Vec<Address>,
    /// Cc recipients (RFC 5322 Section 3.6.3).
    pub cc: Vec<Address>,
    /// Bcc recipients — included in SMTP envelope (`RCPT TO`) but **must not**
    /// appear in message headers (RFC 5322 Section 3.6.3).
    pub bcc: Vec<Address>,
    /// Reply-To addresses (RFC 5322 Section 3.6.2: `address-list`).
    pub reply_to: Vec<Address>,
    /// Explicit origination date (RFC 5322 Section 3.6.1).
    ///
    /// When `None`, [`crate::build_message`] uses the current UTC time.
    /// Set this when building drafts, re-sending, or importing messages
    /// that require a specific date.
    pub date: Option<DateTime>,
    /// Subject line (RFC 5322 Section 3.6.5).
    pub subject: String,
    /// Plain text body.
    pub body_text: Option<String>,
    /// HTML body.
    pub body_html: Option<String>,
    /// In-Reply-To message-IDs — bare `addr-spec` values (no angle brackets),
    /// builder wraps each in angle brackets for the wire format and silently
    /// drops malformed IDs (RFC 5322 Section 3.6.4: `in-reply-to = 1*msg-id`).
    ///
    /// Accepts plain strings so that parsed message-IDs (which may be
    /// non-conformant) can flow directly from [`ParsedEmail`] into a reply
    /// without fallible conversion.
    pub in_reply_to: Vec<String>,
    /// References message-IDs — bare `addr-spec` values (no angle brackets),
    /// builder wraps each in angle brackets for the wire format and silently
    /// drops malformed IDs (RFC 5322 Section 3.6.4: `references = 1*msg-id`).
    ///
    /// Accepts plain strings for the same reason as [`in_reply_to`](Self::in_reply_to).
    pub references: Vec<String>,
    /// File attachments.
    pub attachments: Vec<OutgoingAttachment>,
    /// Additional headers to include verbatim (RFC 5322 Section 3.6.8).
    ///
    /// Each entry is a `(field-name, unstructured-value)` pair. The
    /// [`HeaderName`] newtype enforces RFC 5322 Section 2.2 ftext syntax at
    /// construction time. Values are sanitized (CR/LF stripped) and long
    /// lines are folded per RFC 5322 Section 2.2.3. Headers are emitted
    /// after the standard headers (From, To, Subject, etc.) in the order
    /// they appear here.
    pub extra_headers: Vec<(HeaderName, String)>,
}

/// An attachment to include in an outgoing email.
///
/// # References
/// - RFC 2183 (Content-Disposition: attachment / inline)
/// - RFC 2392 (Content-ID)
/// - RFC 2045 (Content-Transfer-Encoding: base64)
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct OutgoingAttachment {
    /// Filename for the `Content-Disposition` header.
    pub filename: String,
    /// MIME content type (e.g., `"application/pdf"`).
    pub content_type: String,
    /// Raw file data — will be base64-encoded in the message.
    pub data: Vec<u8>,
    /// When `true`, the part uses `Content-Disposition: inline` instead of
    /// `attachment` (RFC 2183 Section 2).  Typically used for images
    /// embedded in HTML via `cid:` URLs.
    pub is_inline: bool,
    /// Optional `Content-ID` header value (RFC 2392).  Should be a bare
    /// `addr-spec` (e.g., `"image001@example.com"`); the builder wraps it
    /// in angle brackets.  Required for HTML-embedded inline images that
    /// are referenced as `<img src="cid:image001@example.com">`.
    pub content_id: Option<String>,
}

impl OutgoingAttachment {
    /// Creates a regular (non-inline) attachment.
    ///
    /// # References
    /// - RFC 2183 (Content-Disposition: attachment)
    /// - RFC 2045 (Content-Transfer-Encoding: base64)
    pub fn new(
        filename: impl Into<String>,
        content_type: impl Into<String>,
        data: impl Into<Vec<u8>>,
    ) -> Self {
        Self {
            filename: filename.into(),
            content_type: content_type.into(),
            data: data.into(),
            is_inline: false,
            content_id: None,
        }
    }

    /// Creates an inline attachment with a Content-ID for embedding in HTML.
    ///
    /// Inline attachments use `Content-Disposition: inline` (RFC 2183
    /// Section 2) and are referenced by the HTML body via `cid:` URLs
    /// (RFC 2392).
    ///
    /// # References
    /// - RFC 2183 Section 2 (Content-Disposition: inline)
    /// - RFC 2392 (Content-ID)
    pub fn inline(
        filename: impl Into<String>,
        content_type: impl Into<String>,
        data: impl Into<Vec<u8>>,
        content_id: impl Into<String>,
    ) -> Self {
        Self {
            filename: filename.into(),
            content_type: content_type.into(),
            data: data.into(),
            is_inline: true,
            content_id: Some(content_id.into()),
        }
    }
}

/// The result of building an email message.
///
/// # References
/// - RFC 5322 (message format)
/// - RFC 5321 (SMTP envelope)
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct BuiltMessage {
    /// Raw RFC 5322 message bytes (headers + body). BCC excluded from headers.
    pub raw: Vec<u8>,
    /// All envelope recipients (to + cc + bcc) for SMTP `RCPT TO`.
    pub envelope_recipients: Vec<String>,
    /// The generated Message-ID (bare `addr-spec`, no angle brackets).
    pub message_id: String,
}

/// TLS mode for the initial connection (RFC 8314).
///
/// This type lives in `daaki-message` rather than in the protocol crates
/// because both `daaki-imap` and `daaki-smtp` need it, and `daaki-message`
/// is already the shared dependency in the workspace. Both protocol crates
/// re-export it at their crate root.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum TlsMode {
    /// Connect directly over TLS (RFC 8314 Section 3.3).
    Implicit,
    /// Connect in cleartext, then upgrade via STARTTLS.
    StartTls,
    /// No TLS (testing only — should not be used in production).
    None,
}

#[cfg(test)]
#[path = "types_tests.rs"]
mod tests;