wsdp 0.1.0

Async high-level client for ČÚZK WSDP real-estate cadastre services
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
use std::fmt;
use std::str::FromStr;

use super::common::{
    MessageCode, ServiceMessage, XmlDateTime, positive_integer_digits, valid_xml_date,
};
pub(crate) use super::common::{trim_xml_whitespace, unsigned_integer_digits};
use super::id::{
    BuildingId, BuildingRightId, CadastralAreaCode, CompanyId, DocumentId, MunicipalityPartCode,
    OwnershipId, OwnershipSheetId, ParcelId, ParcelNumber, PersonalIdentifier, ProceedingId,
    SubjectId, UnitId, WorkplaceCode,
};
use crate::{Error, Result};

/// An XML Schema date, retaining its lexical representation and optional offset.
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct XmlDate(String);

impl XmlDate {
    /// Validates an `xs:date` without assigning a timezone to a naive date.
    pub fn new(value: impl Into<String>) -> Result<Self> {
        let value = value.into();
        if valid_xml_date(trim_xml_whitespace(&value)) {
            Ok(Self(value))
        } else {
            Err(Error::invalid_input(
                "date",
                "expected an XML date with an optional offset",
            ))
        }
    }

    /// Returns the original lexical representation.
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl fmt::Display for XmlDate {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(self.as_str())
    }
}

impl FromStr for XmlDate {
    type Err = Error;

    fn from_str(value: &str) -> Result<Self> {
        Self::new(value)
    }
}

/// A building-type code (`KodTypuStavbyType`), preserving leading zeroes.
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[cfg_attr(feature = "serde", serde(transparent))]
pub struct BuildingTypeCode(String);

impl BuildingTypeCode {
    /// Validates the schema range 1–9 without discarding the lexical code.
    pub fn new(value: impl Into<String>) -> Result<Self> {
        let value = value.into();
        let valid = positive_integer_digits(&value).is_some_and(|digits| {
            matches!(digits.trim_start_matches('0').as_bytes(), [b'1'..=b'9'])
        });
        if valid {
            Ok(Self(value))
        } else {
            Err(Error::invalid_input(
                "building_type",
                "expected a decimal building-type code in 1..=9",
            ))
        }
    }

    /// Returns the original code.
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl fmt::Display for BuildingTypeCode {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(self.as_str())
    }
}

impl FromStr for BuildingTypeCode {
    type Err = Error;

    fn from_str(value: &str) -> Result<Self> {
        Self::new(value)
    }
}

#[cfg(feature = "serde")]
impl<'de> serde::Deserialize<'de> for BuildingTypeCode {
    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let value = <String as serde::Deserialize>::deserialize(deserializer)?;
        Self::new(value).map_err(serde::de::Error::custom)
    }
}

/// A positive numerator or denominator of an ownership share.
///
/// The XSD permits 30 digits, so this deliberately does not use a machine integer.
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[cfg_attr(feature = "serde", serde(transparent))]
pub struct FractionComponent(String);

impl FractionComponent {
    /// Validates a positive decimal integer of at most 30 digits.
    pub fn new(value: impl Into<String>) -> Result<Self> {
        let value = value.into();
        let Some(digits) = positive_integer_digits(&value) else {
            return Err(Error::invalid_input(
                "fraction_component",
                "expected a positive decimal integer with at most 30 digits",
            ));
        };
        if digits.len() > 30 {
            return Err(Error::invalid_input(
                "fraction_component",
                "expected a positive decimal integer with at most 30 digits",
            ));
        }
        Ok(Self(value))
    }

    /// Returns the exact original integer text.
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl fmt::Display for FractionComponent {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(self.as_str())
    }
}

impl FromStr for FractionComponent {
    type Err = Error;

    fn from_str(value: &str) -> Result<Self> {
        Self::new(value)
    }
}

#[cfg(feature = "serde")]
impl<'de> serde::Deserialize<'de> for FractionComponent {
    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let value = <String as serde::Deserialize>::deserialize(deserializer)?;
        Self::new(value).map_err(serde::de::Error::custom)
    }
}

/// A shortened personal identifier whose debug output is redacted.
#[derive(Clone, Eq, Hash, PartialEq)]
pub struct ShortPersonalIdentifier(String);

impl ShortPersonalIdentifier {
    /// Validates the response schema's 1–10 character constraint.
    pub fn new(value: impl Into<String>) -> Result<Self> {
        let value = value.into();
        if !(1..=10).contains(&value.chars().count()) {
            return Err(Error::invalid_input(
                "short_personal_identifier",
                "expected between 1 and 10 characters",
            ));
        }
        Ok(Self(value))
    }

    /// Explicitly exposes the identifier to callers that need it.
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl fmt::Debug for ShortPersonalIdentifier {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str("ShortPersonalIdentifier([REDACTED])")
    }
}

/// Whether a parcel belongs to the full or simplified cadastral register.
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
#[non_exhaustive]
pub enum ParcelKind {
    /// Cadastral parcel (`PKN`).
    Cadastral,
    /// Simplified-register parcel (`PZE`).
    Simplified,
    /// A future or otherwise unknown value, retained verbatim.
    Other(String),
}

impl ParcelKind {
    pub(crate) fn from_raw(raw: String) -> Self {
        match raw.as_str() {
            "PKN" => Self::Cadastral,
            "PZE" => Self::Simplified,
            _ => Self::Other(raw),
        }
    }

    /// Returns the official or untouched unknown value.
    pub fn as_str(&self) -> &str {
        match self {
            Self::Cadastral => "PKN",
            Self::Simplified => "PZE",
            Self::Other(raw) => raw,
        }
    }
}

/// The parcel numbering scheme.
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
#[non_exhaustive]
pub enum ParcelNumberingKind {
    /// Schema value `1`.
    One,
    /// Schema value `2`.
    Two,
    /// A future or otherwise unknown value, retained verbatim.
    Other(String),
}

impl ParcelNumberingKind {
    pub(crate) fn from_raw(raw: String) -> Self {
        match raw.as_str() {
            "1" => Self::One,
            "2" => Self::Two,
            _ => Self::Other(raw),
        }
    }

    /// Returns the official or untouched unknown value.
    pub fn as_str(&self) -> &str {
        match self {
            Self::One => "1",
            Self::Two => "2",
            Self::Other(raw) => raw,
        }
    }
}

/// A schema `AnoNeType` value.
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
#[non_exhaustive]
pub enum YesNo {
    /// Yes (`a`).
    Yes,
    /// No (`n`).
    No,
    /// A future or otherwise unknown value, retained verbatim.
    Other(String),
}

impl YesNo {
    pub(crate) fn from_raw(raw: String) -> Self {
        match raw.as_str() {
            "a" => Self::Yes,
            "n" => Self::No,
            _ => Self::Other(raw),
        }
    }

    /// Returns the official or untouched unknown value.
    pub fn as_str(&self) -> &str {
        match self {
            Self::Yes => "a",
            Self::No => "n",
            Self::Other(raw) => raw,
        }
    }
}

/// The object of which a building forms a part.
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
#[non_exhaustive]
pub enum BuildingAttachment {
    /// A building right (`R`).
    BuildingRight,
    /// A parcel (`P`).
    Parcel,
    /// A future or otherwise unknown value, retained verbatim.
    Other(String),
}

impl BuildingAttachment {
    pub(crate) fn from_raw(raw: String) -> Self {
        match raw.as_str() {
            "R" => Self::BuildingRight,
            "P" => Self::Parcel,
            _ => Self::Other(raw),
        }
    }

    /// Returns the official or untouched unknown value.
    pub fn as_str(&self) -> &str {
        match self {
            Self::BuildingRight => "R",
            Self::Parcel => "P",
            Self::Other(raw) => raw,
        }
    }
}

/// The kind of an authorized subject.
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
#[non_exhaustive]
pub enum SubjectKind {
    /// Natural person (`OFO`).
    NaturalPerson,
    /// Legal person (`OPO`).
    LegalPerson,
    /// Marital or partner joint property (`BSM`).
    Partnership,
    /// A future or otherwise unknown value, retained verbatim.
    Other(String),
}

impl SubjectKind {
    pub(crate) fn from_raw(raw: String) -> Self {
        match raw.as_str() {
            "OFO" => Self::NaturalPerson,
            "OPO" => Self::LegalPerson,
            "BSM" => Self::Partnership,
            _ => Self::Other(raw),
        }
    }

    /// Returns the official or untouched unknown value.
    pub fn as_str(&self) -> &str {
        match self {
            Self::NaturalPerson => "OFO",
            Self::LegalPerson => "OPO",
            Self::Partnership => "BSM",
            Self::Other(raw) => raw,
        }
    }
}

/// Whether a house number is descriptive or evidentiary.
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
#[non_exhaustive]
pub enum AddressNumberKind {
    /// Descriptive number (`1`).
    Descriptive,
    /// Evidentiary number (`2`).
    Evidentiary,
    /// A future or otherwise unknown value, retained verbatim.
    Other(String),
}

impl AddressNumberKind {
    pub(crate) fn from_raw(raw: String) -> Self {
        match raw.as_str() {
            "1" => Self::Descriptive,
            "2" => Self::Evidentiary,
            _ => Self::Other(raw),
        }
    }

    /// Returns the official or untouched unknown value.
    pub fn as_str(&self) -> &str {
        match self {
            Self::Descriptive => "1",
            Self::Evidentiary => "2",
            Self::Other(raw) => raw,
        }
    }
}

/// A cadastral area with its optional code and display name.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct CadastralAreaReference {
    /// Numeric cadastral-area code.
    pub code: Option<CadastralAreaCode>,
    /// Official display name.
    pub name: Option<String>,
}

/// A municipality part with its code and display name.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct MunicipalityPartReference {
    /// Numeric municipality-part code.
    pub code: MunicipalityPartCode,
    /// Official display name.
    pub name: String,
}

/// Identifying fields shared by full parcel records and nested parcel references.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ParcelIdentity {
    /// Internal parcel ID.
    pub id: ParcelId,
    /// Ownership-sheet ID, when supplied.
    pub ownership_sheet_id: Option<OwnershipSheetId>,
    /// Current cadastral-area code.
    pub cadastral_area: CadastralAreaCode,
    /// Parcel root number.
    pub root_number: u32,
    /// Register kind.
    pub kind: ParcelKind,
    /// Parcel numbering scheme.
    pub numbering_kind: ParcelNumberingKind,
    /// Optional parcel subdivision.
    pub subdivision: Option<u16>,
    /// Original cadastral-area code, when supplied.
    pub original_cadastral_area: Option<CadastralAreaCode>,
    /// Simplified-register recording kind (`typZE`), preserved lexically.
    pub simplified_registration_kind: Option<String>,
    /// Optional parcel part number.
    pub part: Option<u16>,
}

/// The natural-key alternative for a building without a house number.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum BuildingLocation {
    /// Municipality-part code and house number.
    Address {
        /// Municipality-part code.
        municipality_part: MunicipalityPartCode,
        /// Descriptive or evidentiary house number, retaining its lexical form.
        house_number: String,
    },
    /// Identifying parcel for building types that have no house number.
    Parcel(ParcelIdentity),
}

/// A nested building identifier (`StavbaIdentType`).
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct BuildingIdentity {
    /// Internal building ID.
    pub id: BuildingId,
    /// Ownership-sheet ID, when supplied.
    pub ownership_sheet_id: Option<OwnershipSheetId>,
    /// Building-type code.
    pub building_type: BuildingTypeCode,
    /// Address or identifying-parcel choice.
    pub location: BuildingLocation,
}

/// A nested building-right identifier (`PravoStavbyIdentType`).
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct BuildingRightIdentity {
    /// Internal building-right ID.
    pub id: BuildingRightId,
    /// Ownership-sheet ID, when supplied.
    pub ownership_sheet_id: Option<OwnershipSheetId>,
    /// Identifying parcel.
    pub identifying_parcel: ParcelIdentity,
}

/// A complete parcel returned by search or LV preview (`ParcelaType`).
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Parcel {
    /// Internal parcel ID.
    pub id: ParcelId,
    /// Register kind.
    pub kind: ParcelKind,
    /// Current cadastral-area code.
    pub cadastral_area: CadastralAreaCode,
    /// Original cadastral-area code, when supplied.
    pub original_cadastral_area: Option<CadastralAreaCode>,
    /// Parcel root number.
    pub root_number: u32,
    /// Optional parcel subdivision.
    pub subdivision: Option<u16>,
    /// Optional parcel part number.
    pub part: Option<u16>,
    /// Area-determination code, preserved lexically.
    pub area_determination_code: Option<String>,
    /// Simplified-register recording kind (`typZE`), preserved lexically.
    pub simplified_registration_kind: Option<String>,
    /// Land-type code, preserved lexically.
    pub land_type_code: Option<String>,
    /// Land-use code, preserved lexically.
    pub land_use_code: Option<String>,
    /// Parcel-type code, preserved lexically.
    pub parcel_type_code: Option<String>,
    /// Parcel area in the unit defined by WSDP (square metres).
    pub area: u32,
    /// Ownership-sheet ID, when supplied.
    pub ownership_sheet_id: Option<OwnershipSheetId>,
    /// Parcel numbering scheme.
    pub numbering_kind: ParcelNumberingKind,
    /// Related building identifier, when supplied.
    pub building: Option<BuildingIdentity>,
    /// Whether the building is a component of the parcel.
    pub building_is_part: YesNo,
    /// Related building-right identifier, when supplied.
    pub building_right: Option<BuildingRightIdentity>,
}

/// A building returned by search, unit overview, or LV preview (`StavbaType`).
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Building {
    /// Internal building ID.
    pub id: BuildingId,
    /// Building-type code.
    pub building_type: BuildingTypeCode,
    /// Municipality part, when supplied.
    pub municipality_part: Option<MunicipalityPartReference>,
    /// House number, when supplied, retaining its lexical form.
    pub house_number: Option<String>,
    /// Building-use code, preserved lexically.
    pub use_code: Option<String>,
    /// Identifying parcel, when supplied.
    pub identifying_parcel: Option<ParcelIdentity>,
    /// Ownership-sheet ID, when supplied.
    pub ownership_sheet_id: Option<OwnershipSheetId>,
    /// Whether this building is attached to a parcel or building right.
    pub attachment: Option<BuildingAttachment>,
    /// Related building-right identifier, when supplied.
    pub building_right: Option<BuildingRightIdentity>,
    /// Temporary-building flag.
    pub temporary: Option<YesNo>,
    /// Defined-units flag; the official schema notes that this is future data.
    pub defined_units: Option<YesNo>,
}

/// A unit returned by search (`JednotkaType`).
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Unit {
    /// Internal unit ID.
    pub id: UnitId,
    /// Building to which the unit belongs.
    pub building: BuildingIdentity,
    /// Unit-type code, preserved lexically.
    pub unit_type_code: String,
    /// Unit number.
    pub number: u64,
    /// Unit-use code, when supplied and preserved lexically.
    pub use_code: Option<String>,
    /// Ownership-sheet ID, when supplied.
    pub ownership_sheet_id: Option<OwnershipSheetId>,
}

/// A purpose assigned to a building right.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct BuildingRightPurpose {
    /// Dynamic purpose code, preserved lexically.
    pub code: String,
    /// Official purpose name.
    pub name: String,
}

/// A building right returned by search or LV preview (`PravoStavbyType`).
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct BuildingRight {
    /// Internal building-right ID.
    pub id: BuildingRightId,
    /// End of validity.
    pub valid_until: XmlDate,
    /// Ownership-sheet ID, when supplied.
    pub ownership_sheet_id: Option<OwnershipSheetId>,
    /// One or more purposes, as required by the XSD.
    pub purposes: Vec<BuildingRightPurpose>,
    /// Whether `parcels` contains only the identifying parcel.
    pub only_identifying_parcel: YesNo,
    /// One or more associated parcels, as required by the XSD.
    pub parcels: Vec<ParcelIdentity>,
}

/// Fields common to a primary authorized subject and each partner.
#[derive(Clone, Eq, PartialEq)]
pub struct SubjectBase {
    /// Internal authorized-subject ID.
    pub id: SubjectId,
    /// Legal-person name.
    pub name: Option<String>,
    /// Company identification number (IČO).
    pub company_id: Option<CompanyId>,
    /// Company-ID suffix, preserved lexically.
    pub company_id_suffix: Option<String>,
    /// Surname.
    pub surname: Option<String>,
    /// Given name.
    pub given_name: Option<String>,
    /// Title before the name.
    pub title_before: Option<String>,
    /// Title after the name.
    pub title_after: Option<String>,
    /// Shortened personal identifier, redacted from `Debug` output.
    pub short_personal_id: Option<ShortPersonalIdentifier>,
    /// Street name.
    pub street: Option<String>,
    /// House number, retaining its lexical form.
    pub house_number: Option<String>,
    /// Orientation number, preserved as text.
    pub orientation_number: Option<String>,
    /// Municipality-part name.
    pub municipality_part_name: Option<String>,
    /// Municipality name.
    pub municipality_name: Option<String>,
    /// City-district name.
    pub city_district_name: Option<String>,
    /// City-borough name.
    pub city_borough_name: Option<String>,
    /// Postal code, retaining leading zeroes and its lexical form.
    pub postal_code: Option<String>,
    /// Subject kind.
    pub kind: SubjectKind,
    /// Descriptive/evidentiary house-number kind.
    pub address_number_kind: Option<AddressNumberKind>,
    /// Country name.
    pub country_name: Option<String>,
    /// District name.
    pub district_name: Option<String>,
    /// Dynamic subject-characteristic code, preserved lexically.
    pub characteristic_code: Option<String>,
}

impl fmt::Debug for SubjectBase {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str("SubjectBase([REDACTED])")
    }
}

/// An authorized subject, including either optional partner (`OSType`).
#[derive(Clone, Eq, PartialEq)]
pub struct AuthorizedSubject {
    /// Fields common to every subject form.
    pub base: SubjectBase,
    /// First partner for joint-property subjects.
    pub partner1: Option<SubjectBase>,
    /// Second partner for joint-property subjects.
    pub partner2: Option<SubjectBase>,
}

impl fmt::Debug for AuthorizedSubject {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str("AuthorizedSubject([REDACTED])")
    }
}

/// A cadastral proceeding (`RizeniType`).
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Proceeding {
    /// Internal proceeding ID.
    pub id: ProceedingId,
    /// Cadastral-workplace code.
    pub workplace: WorkplaceCode,
    /// Dynamic proceeding-type code, preserved lexically.
    pub proceeding_type: String,
    /// Serial number within year, type, and workplace.
    pub serial_number: u32,
    /// Proceeding year.
    pub year: u16,
    /// External identifier, when supplied.
    pub external_id: Option<String>,
    /// Creation timestamp with its original XML timezone semantics.
    pub created_at: XmlDateTime,
}

/// A document in the collection of deeds (`ListinaType`).
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct CollectionDocument {
    /// Internal document ID.
    pub id: DocumentId,
    /// Official document designation.
    pub designation: String,
    /// Execution timestamp, when supplied.
    pub executed_at: Option<XmlDateTime>,
}

/// A geometric-plan identifier (`GPIdentType`).
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct GeometricPlan {
    /// Cadastral-area code.
    pub cadastral_area: CadastralAreaCode,
    /// Survey-result or field-sketch number, including its sign.
    pub survey_result_number: i32,
    /// Internal document ID.
    pub document_id: DocumentId,
    /// Document file name.
    pub file_name: String,
    /// Proceeding confirming the plan.
    pub proceeding: Proceeding,
    /// Cadastral-change proposal number, when supplied.
    pub change_proposal_number: Option<String>,
    /// Confirmation date, when supplied.
    pub confirmed_on: Option<XmlDate>,
}

/// The object or subject targeted by an ownership record.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum OwnershipTarget {
    /// An authorized subject.
    Subject(SubjectId),
    /// A parcel in additional co-ownership.
    Parcel(ParcelId),
    /// A building in additional co-ownership.
    Building(BuildingId),
    /// A unit in additional co-ownership.
    Unit(UnitId),
    /// A building right in additional co-ownership.
    BuildingRight(BuildingRightId),
}

/// An ownership record returned by information operations (`VlastnictviType`).
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Ownership {
    /// Internal ownership-record ID.
    pub id: OwnershipId,
    /// Ownership-sheet ID.
    pub ownership_sheet_id: OwnershipSheetId,
    /// Exact share numerator, supporting all 30 XSD digits.
    pub share_numerator: FractionComponent,
    /// Exact share denominator, supporting all 30 XSD digits.
    pub share_denominator: FractionComponent,
    /// Dynamic legal-relation code, preserved lexically.
    pub legal_relation_code: String,
    /// Cadastral-area code.
    pub cadastral_area: CadastralAreaCode,
    /// Ownership-sheet number.
    pub ownership_sheet_number: u32,
    /// Subject or object selected by the XSD choice.
    pub target: OwnershipTarget,
}

/// Parcel lookup by internal ID or natural key.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum ParcelSearchSelector {
    /// Internal parcel ID.
    Id(ParcelId),
    /// Cadastral area and parcel number.
    Number(ParcelSearchKey),
}

/// A parcel natural key.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ParcelSearchKey {
    /// Cadastral-area code.
    pub cadastral_area: CadastralAreaCode,
    /// Root number and optional subdivision; omission means unsubdivided.
    pub number: ParcelNumber,
}

impl ParcelSearchKey {
    pub(crate) fn validate(&self) -> Result<()> {
        self.number.validate()
    }
}

/// `najdiParcelu` request.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ParcelSearch {
    /// ID/natural-key choice.
    pub selector: ParcelSearchSelector,
    /// Historical timestamp; `None` requests current server data.
    pub valid_at: Option<XmlDateTime>,
}

impl ParcelSearch {
    pub(crate) fn validate(&self) -> Result<()> {
        validate_parcel_selector(&self.selector)
    }
}

fn validate_parcel_selector(selector: &ParcelSearchSelector) -> Result<()> {
    match selector {
        ParcelSearchSelector::Id(_) => Ok(()),
        ParcelSearchSelector::Number(key) => key.validate(),
    }
}

/// Building lookup by internal ID or natural key.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum BuildingSearchSelector {
    /// Internal building ID.
    Id(BuildingId),
    /// Municipality part, building type, and house number.
    Number(BuildingSearchKey),
}

/// A building natural key.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct BuildingSearchKey {
    /// Municipality-part code.
    pub municipality_part: MunicipalityPartCode,
    /// Building-type code.
    pub building_type: BuildingTypeCode,
    /// House number in 1–9999.
    pub house_number: u16,
}

impl BuildingSearchKey {
    /// Validates the house-number range from `CisloDomovniType`.
    pub fn new(
        municipality_part: MunicipalityPartCode,
        building_type: BuildingTypeCode,
        house_number: u16,
    ) -> Result<Self> {
        let value = Self {
            municipality_part,
            building_type,
            house_number,
        };
        value.validate()?;
        Ok(value)
    }

    pub(crate) fn validate(&self) -> Result<()> {
        if !(1..=9999).contains(&self.house_number) {
            return Err(Error::invalid_input(
                "house_number",
                "house number must be in 1..=9999",
            ));
        }
        Ok(())
    }
}

/// `najdiStavbu` request.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct BuildingSearch {
    /// ID/natural-key choice.
    pub selector: BuildingSearchSelector,
    /// Historical timestamp; `None` requests current server data.
    pub valid_at: Option<XmlDateTime>,
}

impl BuildingSearch {
    pub(crate) fn validate(&self) -> Result<()> {
        validate_building_selector(&self.selector)
    }
}

fn validate_building_selector(selector: &BuildingSearchSelector) -> Result<()> {
    match selector {
        BuildingSearchSelector::Id(_) => Ok(()),
        BuildingSearchSelector::Number(key) => key.validate(),
    }
}

/// Unit lookup by ID or by building and optional unit number.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum UnitSearchSelector {
    /// Internal unit ID.
    Id(UnitId),
    /// Building ID/natural key and an optional unit number.
    Number(UnitSearchKey),
}

/// A unit natural key. Omitting `number` returns units in the selected building(s).
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct UnitSearchKey {
    /// Building ID or natural key.
    pub building: BuildingSearchSelector,
    /// Unit number in 0–9999999999, or all units when omitted.
    pub number: Option<u64>,
}

impl UnitSearchKey {
    /// Validates the optional unit-number range from `CisloJednotkyType`.
    pub fn new(building: BuildingSearchSelector, number: Option<u64>) -> Result<Self> {
        let value = Self { building, number };
        value.validate()?;
        Ok(value)
    }

    pub(crate) fn validate(&self) -> Result<()> {
        validate_building_selector(&self.building)?;
        if self.number.is_some_and(|value| value > 9_999_999_999) {
            return Err(Error::invalid_input(
                "unit_number",
                "unit number must be at most 9999999999",
            ));
        }
        Ok(())
    }
}

/// `najdiJednotku` request.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct UnitSearch {
    /// ID/natural-key choice.
    pub selector: UnitSearchSelector,
    /// Historical timestamp; `None` requests current server data.
    pub valid_at: Option<XmlDateTime>,
}

impl UnitSearch {
    pub(crate) fn validate(&self) -> Result<()> {
        match &self.selector {
            UnitSearchSelector::Id(_) => Ok(()),
            UnitSearchSelector::Number(key) => key.validate(),
        }
    }
}

/// Building-right lookup by its own ID or by a parcel selector.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum BuildingRightSelector {
    /// Internal building-right ID.
    Id(BuildingRightId),
    /// Parcel selected by internal ID or natural key.
    Parcel(ParcelSearchSelector),
}

/// `najdiPravoStavby` request.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct BuildingRightSearch {
    /// Building-right/parcel-ID/parcel-natural-key choice.
    pub selector: BuildingRightSelector,
    /// Historical timestamp; `None` requests current server data.
    pub valid_at: Option<XmlDateTime>,
}

impl BuildingRightSearch {
    pub(crate) fn validate(&self) -> Result<()> {
        match &self.selector {
            BuildingRightSelector::Id(_) => Ok(()),
            BuildingRightSelector::Parcel(selector) => validate_parcel_selector(selector),
        }
    }
}

/// A proceeding natural key.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ProceedingSearchKey {
    /// Dynamic proceeding-type code (1–3 characters).
    pub proceeding_type: String,
    /// Serial number in 1–99999999.
    pub serial_number: u32,
    /// Proceeding year in 1–9999.
    pub year: u16,
    /// Cadastral-workplace code.
    pub workplace: WorkplaceCode,
}

impl ProceedingSearchKey {
    /// Validates the proceeding natural-key fields.
    pub fn new(
        proceeding_type: impl Into<String>,
        serial_number: u32,
        year: u16,
        workplace: WorkplaceCode,
    ) -> Result<Self> {
        let value = Self {
            proceeding_type: proceeding_type.into(),
            serial_number,
            year,
            workplace,
        };
        value.validate()?;
        Ok(value)
    }

    pub(crate) fn validate(&self) -> Result<()> {
        if !(1..=3).contains(&self.proceeding_type.chars().count()) {
            return Err(Error::invalid_input(
                "proceeding_type",
                "proceeding type must contain 1 to 3 characters",
            ));
        }
        if !(1..=99_999_999).contains(&self.serial_number) {
            return Err(Error::invalid_input(
                "serial_number",
                "proceeding serial number must be in 1..=99999999",
            ));
        }
        if !(1..=9999).contains(&self.year) {
            return Err(Error::invalid_input(
                "year",
                "proceeding year must be in 1..=9999",
            ));
        }
        Ok(())
    }
}

/// Proceeding lookup by internal ID or natural key.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum ProceedingSearchSelector {
    /// Internal proceeding ID.
    Id(ProceedingId),
    /// Type, serial number, year, and workplace.
    Number(ProceedingSearchKey),
}

/// `najdiRizeni` request.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ProceedingSearch {
    /// ID/natural-key choice.
    pub selector: ProceedingSearchSelector,
}

impl ProceedingSearch {
    pub(crate) fn validate(&self) -> Result<()> {
        validate_proceeding_selector(&self.selector)
    }
}

fn validate_proceeding_selector(selector: &ProceedingSearchSelector) -> Result<()> {
    match selector {
        ProceedingSearchSelector::Id(_) => Ok(()),
        ProceedingSearchSelector::Number(key) => key.validate(),
    }
}

/// `najdiListinuVeSbirceListin` request.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct CollectionDocumentSearch {
    /// Proceeding ID/natural-key choice.
    pub proceeding: ProceedingSearchSelector,
}

impl CollectionDocumentSearch {
    pub(crate) fn validate(&self) -> Result<()> {
        validate_proceeding_selector(&self.proceeding)
    }
}

/// `najdiGP` request.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct GeometricPlanSearch {
    /// Cadastral-area code.
    pub cadastral_area: CadastralAreaCode,
    /// Survey-result or field-sketch number in -99999–99999.
    pub survey_result_number: i32,
}

impl GeometricPlanSearch {
    /// Validates the signed survey-result number.
    pub fn new(cadastral_area: CadastralAreaCode, survey_result_number: i32) -> Result<Self> {
        let value = Self {
            cadastral_area,
            survey_result_number,
        };
        value.validate()?;
        Ok(value)
    }

    pub(crate) fn validate(&self) -> Result<()> {
        if !(-99_999..=99_999).contains(&self.survey_result_number) {
            return Err(Error::invalid_input(
                "survey_result_number",
                "survey-result number must be in -99999..=99999",
            ));
        }
        Ok(())
    }
}

/// Legal-person subject search. At least one of company ID and name is required.
#[derive(Clone, Eq, PartialEq)]
pub struct LegalPersonSearch {
    /// Company identification number.
    pub company_id: Option<CompanyId>,
    /// Legal-person name, using the exact server matching semantics.
    pub name: Option<String>,
}

impl LegalPersonSearch {
    /// Validates the mandatory-at-least-one rule and search-name length.
    pub fn new(company_id: Option<CompanyId>, name: Option<String>) -> Result<Self> {
        let value = Self { company_id, name };
        value.validate()?;
        Ok(value)
    }

    pub(crate) fn validate(&self) -> Result<()> {
        if self.company_id.is_none() && self.name.is_none() {
            return Err(Error::invalid_input(
                "legal_person",
                "company ID or name is required",
            ));
        }
        if self
            .name
            .as_deref()
            .is_some_and(|value| !(2..=255).contains(&value.chars().count()))
        {
            return Err(Error::invalid_input(
                "name",
                "legal-person search name must contain 2 to 255 characters",
            ));
        }
        Ok(())
    }
}

impl fmt::Debug for LegalPersonSearch {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("LegalPersonSearch")
            .field(
                "company_id",
                &self.company_id.as_ref().map(|_| "[REDACTED]"),
            )
            .field("name", &self.name.as_ref().map(|_| "[REDACTED]"))
            .finish()
    }
}

/// Personal identifier or birth-date choice for natural-person/partnership search.
#[derive(Clone, Eq, PartialEq)]
pub enum PersonBirthSelector {
    /// Full personal identifier; debug output is redacted by its type.
    PersonalIdentifier(PersonalIdentifier),
    /// Birth date.
    BirthDate(XmlDate),
}

impl fmt::Debug for PersonBirthSelector {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(match self {
            Self::PersonalIdentifier(_) => "PersonalIdentifier([REDACTED])",
            Self::BirthDate(_) => "BirthDate([REDACTED])",
        })
    }
}

/// Address filters available for natural-person and partnership lookup.
#[derive(Clone, Default, Eq, PartialEq)]
pub struct SubjectAddressFilter {
    /// Municipality name.
    pub municipality: Option<String>,
    /// Municipality-part name.
    pub municipality_part: Option<String>,
    /// Street name.
    pub street: Option<String>,
    /// Orientation number, preserved as text.
    pub orientation_number: Option<String>,
    /// House number in 1–9999.
    pub house_number: Option<u16>,
}

impl SubjectAddressFilter {
    pub(crate) fn validate(&self) -> Result<()> {
        validate_optional_length(self.municipality.as_deref(), "municipality", 1, 48)?;
        validate_optional_length(
            self.municipality_part.as_deref(),
            "municipality_part",
            1,
            48,
        )?;
        validate_optional_length(self.street.as_deref(), "street", 1, 48)?;
        validate_optional_length(
            self.orientation_number.as_deref(),
            "orientation_number",
            1,
            4,
        )?;
        if self
            .house_number
            .is_some_and(|value| !(1..=9999).contains(&value))
        {
            return Err(Error::invalid_input(
                "house_number",
                "house number must be in 1..=9999",
            ));
        }
        Ok(())
    }
}

impl fmt::Debug for SubjectAddressFilter {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("SubjectAddressFilter")
            .field(
                "municipality",
                &self.municipality.as_ref().map(|_| "[REDACTED]"),
            )
            .field(
                "municipality_part",
                &self.municipality_part.as_ref().map(|_| "[REDACTED]"),
            )
            .field("street", &self.street.as_ref().map(|_| "[REDACTED]"))
            .field(
                "orientation_number",
                &self.orientation_number.as_ref().map(|_| "[REDACTED]"),
            )
            .field("house_number", &self.house_number.map(|_| "[REDACTED]"))
            .finish()
    }
}

fn validate_optional_length(
    value: Option<&str>,
    field: &'static str,
    minimum: usize,
    maximum: usize,
) -> Result<()> {
    if value.is_some_and(|value| !(minimum..=maximum).contains(&value.chars().count())) {
        return Err(Error::invalid_input(
            field,
            format!("value must contain {minimum} to {maximum} characters"),
        ));
    }
    Ok(())
}

/// Natural-person or marital/partner joint-property subject search.
#[derive(Clone, Default, Eq, PartialEq)]
pub struct PersonOrPartnershipSearch {
    /// Given name, with server-defined matching semantics.
    pub given_name: Option<String>,
    /// Surname, with server-defined matching semantics.
    pub surname: Option<String>,
    /// Personal identifier or birth date.
    pub birth: Option<PersonBirthSelector>,
    /// Optional address filters.
    pub address: Option<SubjectAddressFilter>,
}

impl PersonOrPartnershipSearch {
    pub(crate) fn validate(&self) -> Result<()> {
        validate_optional_length(self.given_name.as_deref(), "given_name", 2, 100)?;
        validate_optional_length(self.surname.as_deref(), "surname", 2, 100)?;
        if let Some(address) = &self.address {
            address.validate()?;
        }
        Ok(())
    }
}

impl fmt::Debug for PersonOrPartnershipSearch {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("PersonOrPartnershipSearch")
            .field(
                "given_name",
                &self.given_name.as_ref().map(|_| "[REDACTED]"),
            )
            .field("surname", &self.surname.as_ref().map(|_| "[REDACTED]"))
            .field("birth", &self.birth)
            .field("address", &self.address)
            .finish()
    }
}

/// Legal-person versus natural-person/partnership subject-search choice.
#[derive(Clone, Eq, PartialEq)]
pub enum SubjectSearchSelector {
    /// Search by IČO and/or legal-person name.
    LegalPerson(LegalPersonSearch),
    /// Search natural persons and marital/partner joint-property subjects.
    PersonOrPartnership(PersonOrPartnershipSearch),
}

impl fmt::Debug for SubjectSearchSelector {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::LegalPerson(search) => {
                formatter.debug_tuple("LegalPerson").field(search).finish()
            }
            Self::PersonOrPartnership(search) => formatter
                .debug_tuple("PersonOrPartnership")
                .field(search)
                .finish(),
        }
    }
}

/// `najdiOS` request.
#[derive(Clone, Eq, PartialEq)]
pub struct SubjectSearch {
    /// Subject-form choice.
    pub selector: SubjectSearchSelector,
    /// Historical timestamp; `None` requests current server data.
    pub valid_at: Option<XmlDateTime>,
}

impl SubjectSearch {
    pub(crate) fn validate(&self) -> Result<()> {
        match &self.selector {
            SubjectSearchSelector::LegalPerson(search) => search.validate(),
            SubjectSearchSelector::PersonOrPartnership(search) => search.validate(),
        }
    }
}

impl fmt::Debug for SubjectSearch {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("SubjectSearch")
            .field("selector", &self.selector)
            .field("valid_at", &self.valid_at)
            .finish()
    }
}

/// One of the eight WSDP 3.1 `vyhledat` requests.
#[derive(Clone, Eq, PartialEq)]
pub enum SearchRequest {
    /// `najdiParcelu`.
    Parcel(ParcelSearch),
    /// `najdiJednotku`.
    Unit(UnitSearch),
    /// `najdiStavbu`.
    Building(BuildingSearch),
    /// `najdiOS`.
    Subject(SubjectSearch),
    /// `najdiPravoStavby`.
    BuildingRight(BuildingRightSearch),
    /// `najdiRizeni`.
    Proceeding(ProceedingSearch),
    /// `najdiListinuVeSbirceListin`.
    CollectionDocument(CollectionDocumentSearch),
    /// `najdiGP`.
    GeometricPlan(GeometricPlanSearch),
}

impl SearchRequest {
    pub(crate) fn validate(&self) -> Result<()> {
        match self {
            Self::Parcel(request) => request.validate(),
            Self::Unit(request) => request.validate(),
            Self::Building(request) => request.validate(),
            Self::Subject(request) => request.validate(),
            Self::BuildingRight(request) => request.validate(),
            Self::Proceeding(request) => request.validate(),
            Self::CollectionDocument(request) => request.validate(),
            Self::GeometricPlan(request) => request.validate(),
        }
    }
}

impl fmt::Debug for SearchRequest {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Parcel(request) => formatter.debug_tuple("Parcel").field(request).finish(),
            Self::Unit(request) => formatter.debug_tuple("Unit").field(request).finish(),
            Self::Building(request) => formatter.debug_tuple("Building").field(request).finish(),
            Self::Subject(request) => formatter.debug_tuple("Subject").field(request).finish(),
            Self::BuildingRight(request) => formatter
                .debug_tuple("BuildingRight")
                .field(request)
                .finish(),
            Self::Proceeding(request) => {
                formatter.debug_tuple("Proceeding").field(request).finish()
            }
            Self::CollectionDocument(request) => formatter
                .debug_tuple("CollectionDocument")
                .field(request)
                .finish(),
            Self::GeometricPlan(request) => formatter
                .debug_tuple("GeometricPlan")
                .field(request)
                .finish(),
        }
    }
}

/// Whether a search result is complete, empty, or truncated by the service limit.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum SearchCompletion {
    /// The server returned a complete, non-empty result.
    Complete,
    /// No matching data was returned.
    Empty,
    /// Message 310 reports that the service result limit was exceeded.
    LimitExceeded,
}

/// Search items and their service-derived completion state.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct SearchResult<T> {
    /// Returned records. A natural-key lookup remains a collection even for one match.
    pub items: Vec<T>,
    /// Completion state refined from service messages by the client integration.
    pub completion: SearchCompletion,
}

impl<T> SearchResult<T> {
    /// Creates the response-only state; non-empty items are complete until refined.
    pub fn from_items(items: Vec<T>) -> Self {
        let completion = if items.is_empty() {
            SearchCompletion::Empty
        } else {
            SearchCompletion::Complete
        };
        Self { items, completion }
    }

    /// Applies message 310 and 392 semantics without inventing pagination.
    pub fn refine_completion(&mut self, messages: &[ServiceMessage]) {
        self.completion = if messages
            .iter()
            .any(|message| message.code == MessageCode::ResultLimitExceeded)
        {
            SearchCompletion::LimitExceeded
        } else if self.items.is_empty()
            || messages
                .iter()
                .any(|message| message.code == MessageCode::NoData)
        {
            SearchCompletion::Empty
        } else {
            SearchCompletion::Complete
        };
    }
}

/// Typed result of one of the eight search operations.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum SearchResponse {
    /// Parcel records.
    Parcels(SearchResult<Parcel>),
    /// Unit records.
    Units(SearchResult<Unit>),
    /// Building records.
    Buildings(SearchResult<Building>),
    /// Authorized-subject records.
    Subjects(SearchResult<AuthorizedSubject>),
    /// Building-right records.
    BuildingRights(SearchResult<BuildingRight>),
    /// Proceeding records.
    Proceedings(SearchResult<Proceeding>),
    /// Collection-document records.
    CollectionDocuments(SearchResult<CollectionDocument>),
    /// Geometric-plan identifiers.
    GeometricPlans(SearchResult<GeometricPlan>),
}

impl SearchResponse {
    /// Refines every search completion state from the messages retained by `Response`.
    pub fn refine_completion(&mut self, messages: &[ServiceMessage]) {
        match self {
            Self::Parcels(result) => result.refine_completion(messages),
            Self::Units(result) => result.refine_completion(messages),
            Self::Buildings(result) => result.refine_completion(messages),
            Self::Subjects(result) => result.refine_completion(messages),
            Self::BuildingRights(result) => result.refine_completion(messages),
            Self::Proceedings(result) => result.refine_completion(messages),
            Self::CollectionDocuments(result) => result.refine_completion(messages),
            Self::GeometricPlans(result) => result.refine_completion(messages),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{MessageLevel, ServiceMessage};

    #[test]
    fn xml_date_retains_naive_and_offset_forms() {
        for raw in [
            "2026-11-20",
            "2026-11-20Z",
            "2026-11-20+01:00",
            "2024-02-29-14:00",
            " \t2026-11-20+14:00\r\n",
            "-0001-01-01Z",
            "10000-01-01",
        ] {
            assert_eq!(XmlDate::new(raw).unwrap().as_str(), raw);
        }
        for raw in [
            "20.11.2026",
            "2026-02-29",
            "2026-11-20z",
            "2026-11-20+14:01",
            "2026-11-20+15:00",
            "2026-11-20+01:00:01",
            "0000-01-01",
        ] {
            assert!(XmlDate::new(raw).is_err(), "{raw}");
        }
    }

    #[test]
    fn completion_uses_limit_and_no_data_messages() {
        let mut result = SearchResult::from_items(vec![1]);
        result.refine_completion(&[ServiceMessage {
            code: MessageCode::from_raw(" \t+000310\r\n"),
            level: MessageLevel::Warning,
            text: String::new(),
        }]);
        assert_eq!(result.completion, SearchCompletion::LimitExceeded);
        result.refine_completion(&[]);
        assert_eq!(result.completion, SearchCompletion::Complete);
        result.items.clear();
        result.refine_completion(&[]);
        assert_eq!(result.completion, SearchCompletion::Empty);
    }

    #[test]
    fn integer_lexical_forms_are_preserved_while_digit_limits_and_ranges_hold() {
        let building = BuildingTypeCode::new(" \t+0009\r\n").unwrap();
        assert_eq!(building.as_str(), " \t+0009\r\n");
        assert!(BuildingTypeCode::new("+10").is_err());
        assert!(BuildingTypeCode::new(" +0 ").is_err());
        assert!(BuildingTypeCode::new("++1").is_err());

        let raw = "123456789012345678901234567890";
        let fraction = FractionComponent::new(format!(" \t+{raw}\r\n")).unwrap();
        assert_eq!(fraction.as_str(), " \t+123456789012345678901234567890\r\n");
        assert!(FractionComponent::new(" +1234567890123456789012345678901 ").is_err());
        assert!(FractionComponent::new("+000").is_err());
    }

    #[cfg(feature = "serde")]
    #[test]
    fn search_integer_deserialization_uses_validating_constructors() {
        let code: BuildingTypeCode = serde_json::from_str("\" +0009 \"").unwrap();
        assert_eq!(code.as_str(), " +0009 ");
        assert!(serde_json::from_str::<BuildingTypeCode>("\"10\"").is_err());
        let component: FractionComponent = serde_json::from_str("\" +0001 \"").unwrap();
        assert_eq!(component.as_str(), " +0001 ");
        assert!(serde_json::from_str::<FractionComponent>("\"0\"").is_err());
    }

    #[test]
    fn directly_constructed_request_fields_recheck_all_constructor_invariants() {
        assert!(
            ParcelNumber {
                root: 100_000,
                subdivision: None,
            }
            .validate()
            .is_err()
        );
        assert!(
            ParcelNumber {
                root: 1,
                subdivision: Some(0),
            }
            .validate()
            .is_err()
        );
        let building = BuildingSearchKey {
            municipality_part: MunicipalityPartCode::new("1").unwrap(),
            building_type: BuildingTypeCode::new("1").unwrap(),
            house_number: 0,
        };
        assert!(building.validate().is_err());
        let unit = UnitSearchKey {
            building: BuildingSearchSelector::Number(building),
            number: Some(10_000_000_000),
        };
        assert!(unit.validate().is_err());
        let proceeding = ProceedingSearchKey {
            proceeding_type: String::new(),
            serial_number: 0,
            year: 10_000,
            workplace: WorkplaceCode::new("1").unwrap(),
        };
        assert!(proceeding.validate().is_err());
        assert!(
            GeometricPlanSearch {
                cadastral_area: CadastralAreaCode::new("1").unwrap(),
                survey_result_number: 100_000,
            }
            .validate()
            .is_err()
        );
        assert!(
            LegalPersonSearch {
                company_id: None,
                name: None,
            }
            .validate()
            .is_err()
        );
        assert!(
            LegalPersonSearch {
                company_id: None,
                name: Some("x".to_owned()),
            }
            .validate()
            .is_err()
        );
        assert!(
            PersonOrPartnershipSearch {
                given_name: Some("J".to_owned()),
                surname: None,
                birth: None,
                address: Some(SubjectAddressFilter {
                    house_number: Some(0),
                    ..SubjectAddressFilter::default()
                }),
            }
            .validate()
            .is_err()
        );
    }

    #[test]
    fn sensitive_subject_queries_are_redacted_at_every_debug_layer() {
        let person = PersonOrPartnershipSearch {
            given_name: Some("given-secret".to_owned()),
            surname: Some("surname-secret".to_owned()),
            birth: Some(PersonBirthSelector::BirthDate(
                XmlDate::new("2001-02-03").unwrap(),
            )),
            address: Some(SubjectAddressFilter {
                municipality: Some("municipality-secret".to_owned()),
                municipality_part: Some("part-secret".to_owned()),
                street: Some("street-secret".to_owned()),
                orientation_number: Some("77A".to_owned()),
                house_number: Some(13_579),
            }),
        };
        let selector = SubjectSearchSelector::PersonOrPartnership(person.clone());
        let subject = SubjectSearch {
            selector: selector.clone(),
            valid_at: None,
        };
        let request = SearchRequest::Subject(subject.clone());
        let debug = format!("{person:?} {selector:?} {subject:?} {request:?}");
        for sentinel in [
            "given-secret",
            "surname-secret",
            "2001-02-03",
            "municipality-secret",
            "part-secret",
            "street-secret",
            "77A",
            "13579",
        ] {
            assert!(!debug.contains(sentinel), "{debug}");
        }

        let legal = LegalPersonSearch::new(
            Some(CompanyId::new("12345678").unwrap()),
            Some("legal-secret".to_owned()),
        )
        .unwrap();
        let subject = SubjectSearch {
            selector: SubjectSearchSelector::LegalPerson(legal.clone()),
            valid_at: None,
        };
        let request = SearchRequest::Subject(subject.clone());
        let debug = format!("{legal:?} {subject:?} {request:?}");
        assert!(!debug.contains("legal-secret"));
        assert!(!debug.contains("12345678"));
    }

    #[test]
    fn personal_identifiers_are_debug_redacted() {
        let short = ShortPersonalIdentifier::new("123456").unwrap();
        assert!(!format!("{short:?}").contains("123456"));
        let full = PersonalIdentifier::new("123456789").unwrap();
        let selector = PersonBirthSelector::PersonalIdentifier(full);
        assert!(!format!("{selector:?}").contains("123456789"));
    }
}