soap-server 0.1.1

A WSDL-driven SOAP 1.1/1.2 server library for Rust — document/RPC dispatch, WS-Security UsernameToken, axum-based (the transport under onvif-server)
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
// SOAP dispatch — route body element QName to registered SoapHandler
// Also provides XSD-11 payload validation (validate_request).

use crate::fault::SoapFault;
use crate::handler::SoapHandler;
use crate::qname::QName;
use crate::wsdl::definitions::BindingStyle;
use crate::wsdl::resolver::ResolvedWsdl;
use crate::xsd::types::{ComplexContent, TypeRegistry};
use std::collections::{HashMap, HashSet};
use std::sync::Arc;

/// A single routing entry — holds the handler plus metadata needed by the pipeline.
pub struct DispatchEntry {
    pub handler: Arc<dyn SoapHandler>,
    /// Whether this operation requires authentication (controlled by auth_bypass set at startup).
    pub auth_required: bool,
    /// QName used for routing (body first-child element QName for document/literal,
    /// synthesized wrapper QName for RPC).  This is the key used for dispatch lookup.
    pub input_type: Option<QName>,
    /// QName to look up in the TypeRegistry for structural XSD validation.
    ///
    /// For RPC style or inline-element ops, this equals `input_type`.
    /// For document/literal ops whose message-part element has a named `type=` attribute,
    /// this is the named type QName rather than the element QName.
    /// `None` means genuinely no schema is expected (empty/omitted input) — validation passes.
    pub validation_type: Option<QName>,
}

impl std::fmt::Debug for DispatchEntry {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("DispatchEntry")
            .field("auth_required", &self.auth_required)
            .field("input_type", &self.input_type)
            .field("validation_type", &self.validation_type)
            .finish_non_exhaustive()
    }
}

/// The runtime routing table: O(1) by body-element QName, with SOAPAction fallback.
/// Built once at startup from a ResolvedWsdl; never mutated per-request.
pub struct DispatchTable {
    by_element: HashMap<QName, DispatchEntry>,
    by_action: HashMap<String, DispatchEntry>,
    /// Optional catch-all handler for operations not explicitly registered.
    pub default_handler: Option<Arc<dyn SoapHandler>>,
}

impl DispatchTable {
    /// Create an empty dispatch table (no operations, no default handler).
    /// Used internally in multi-service mode as a placeholder.
    pub fn empty() -> Self {
        DispatchTable {
            by_element: HashMap::new(),
            by_action: HashMap::new(),
            default_handler: None,
        }
    }
}

/// Errors that can occur while building the dispatch table (startup-time validation).
#[derive(Debug, thiserror::Error)]
pub enum DispatchError {
    #[error("WSDL operation '{0}' has no registered handler")]
    UnregisteredOperation(String),
    #[error("Registered handler '{0}' has no matching operation in WSDL")]
    UnknownOperation(String),
    /// The operation references schema information (element/type) that is declared in the
    /// loaded schema but cannot be resolved to a concrete type at build time.
    /// Fail-closed: surfacing this at startup prevents silent skip of required validation.
    #[error("Operation '{op}' input element '{element}' references type '{type_ref}' which is not in the type registry")]
    UnresolvableInputType {
        op: String,
        element: String,
        type_ref: String,
    },
}

/// Build the dispatch table at startup.
///
/// `handlers` is keyed by operation name (e.g., "GetProfiles").
/// `auth_bypass` is the set of operation names that skip authentication.
/// `default_handler` is an optional catch-all used when no specific handler matches.
///   When `Some`, operations without a registered handler are silently skipped (no error).
///   When `None`, every WSDL operation must have a handler or `UnregisteredOperation` is returned.
///
/// Returns `Err(DispatchError::UnregisteredOperation)` if any WSDL operation has no handler and no default.
/// Returns `Err(DispatchError::UnknownOperation)` if any registered handler has no WSDL operation.
pub fn build_dispatch_table(
    resolved: &ResolvedWsdl,
    handlers: HashMap<String, Arc<dyn SoapHandler>>,
    auth_bypass: &HashSet<String>,
    default_handler: Option<Arc<dyn SoapHandler>>,
) -> Result<DispatchTable, DispatchError> {
    let unique_ops = collect_ops_for_service(None, resolved);
    build_dispatch_table_from_ops(unique_ops, resolved, handlers, auth_bypass, default_handler)
}

/// Build a dispatch table for a single named service.
///
/// Only operations reachable through `service_name`'s ports and bindings are included.
/// Useful when a WSDL defines multiple services and each service mounts on a distinct path.
///
/// Semantics are otherwise identical to `build_dispatch_table`.
pub fn build_dispatch_table_for_service(
    service_name: &str,
    resolved: &ResolvedWsdl,
    handlers: HashMap<String, Arc<dyn SoapHandler>>,
    auth_bypass: &HashSet<String>,
    default_handler: Option<Arc<dyn SoapHandler>>,
) -> Result<DispatchTable, DispatchError> {
    let unique_ops = collect_ops_for_service(Some(service_name), resolved);
    build_dispatch_table_from_ops(unique_ops, resolved, handlers, auth_bypass, default_handler)
}

/// Collect unique operations for all services (service_name = None) or a specific service.
/// Returns Vec of (op_name, soap_action, binding_style, rpc_namespace).
fn collect_ops_for_service(
    service_name: Option<&str>,
    resolved: &ResolvedWsdl,
) -> Vec<(String, String, BindingStyle, Option<String>)> {
    let mut all_binding_ops: Vec<(String, String, BindingStyle, Option<String>)> = Vec::new();

    let service_iter: Vec<&crate::wsdl::definitions::Service> = match service_name {
        Some(name) => resolved.definition.services.get(name).into_iter().collect(),
        None => resolved.definition.services.values().collect(),
    };

    for service in service_iter {
        for port in &service.ports {
            let binding_local = &port.binding.local_name;
            if let Some(binding) = resolved.definition.bindings.get(binding_local) {
                let style = binding.soap_binding.style.clone();
                for binding_op in &binding.operations {
                    let rpc_ns = if style == BindingStyle::Rpc {
                        binding_op
                            .input
                            .body
                            .namespace
                            .clone()
                            .or_else(|| Some(resolved.definition.target_namespace.clone()))
                    } else {
                        None
                    };
                    all_binding_ops.push((
                        binding_op.name.clone(),
                        binding_op.soap_action.clone(),
                        style.clone(),
                        rpc_ns,
                    ));
                }
            }
        }
    }

    // If no services defined (and collecting for all), fall back to all bindings directly.
    if all_binding_ops.is_empty() && service_name.is_none() {
        for binding in resolved.definition.bindings.values() {
            let style = binding.soap_binding.style.clone();
            for binding_op in &binding.operations {
                let rpc_ns = if style == BindingStyle::Rpc {
                    binding_op
                        .input
                        .body
                        .namespace
                        .clone()
                        .or_else(|| Some(resolved.definition.target_namespace.clone()))
                } else {
                    None
                };
                all_binding_ops.push((
                    binding_op.name.clone(),
                    binding_op.soap_action.clone(),
                    style.clone(),
                    rpc_ns,
                ));
            }
        }
    }

    // Deduplicate (same operation may appear in multiple ports/bindings).
    let mut seen_ops: HashSet<String> = HashSet::new();
    let mut unique_ops: Vec<(String, String, BindingStyle, Option<String>)> = Vec::new();
    for (op_name, soap_action, style, rpc_ns) in all_binding_ops {
        if seen_ops.insert(op_name.clone()) {
            unique_ops.push((op_name, soap_action, style, rpc_ns));
        }
    }

    unique_ops
}

/// Internal helper: build a DispatchTable from a pre-collected list of unique operations.
fn build_dispatch_table_from_ops(
    unique_ops: Vec<(String, String, BindingStyle, Option<String>)>,
    resolved: &ResolvedWsdl,
    handlers: HashMap<String, Arc<dyn SoapHandler>>,
    auth_bypass: &HashSet<String>,
    default_handler: Option<Arc<dyn SoapHandler>>,
) -> Result<DispatchTable, DispatchError> {
    let mut by_element: HashMap<QName, DispatchEntry> = HashMap::new();
    let mut by_action: HashMap<String, DispatchEntry> = HashMap::new();

    // Track which handler names are consumed (to detect handlers with no WSDL operation).
    let mut consumed_handlers: HashSet<String> = HashSet::new();

    for (op_name, soap_action, style, rpc_ns) in unique_ops {
        let handler = match handlers.get(&op_name) {
            Some(h) => h.clone(),
            None => match &default_handler {
                Some(d) => d.clone(),
                None => return Err(DispatchError::UnregisteredOperation(op_name.clone())),
            },
        };

        consumed_handlers.insert(op_name.clone());

        let auth_required = !auth_bypass.contains(&op_name);

        // Determine the input dispatch QName and validation type QName.
        //
        // RPC style: synthesize QName from (soap:body namespace or targetNamespace, operation name).
        //   validation_type == input_type (registry has been populated for RPC types)
        //
        // Document/literal style: resolve from message part element reference.
        //   input_type = element QName (used for routing)
        //   validation_type = resolved via element_type_map:
        //     - element has inline complexType → element QName (now registered in TypeRegistry)
        //     - element has type= reference → named type QName
        //     - element not in element_type_map (genuinely no schema) → None (skip validation)
        //     - element in map but type not in registry → fail-closed build error
        let (input_type, validation_type) = if style == BindingStyle::Rpc {
            let ns = rpc_ns
                .as_deref()
                .unwrap_or(&resolved.definition.target_namespace);
            let qn = Some(QName::new(ns, &op_name));
            (qn.clone(), qn)
        } else {
            let elem_qname = resolve_input_element(resolved, &op_name);
            let val_type = match &elem_qname {
                None => None, // No element reference in WSDL — no schema expected.
                Some(elem_qn) => {
                    match resolved.element_type_map.get(elem_qn) {
                        None => {
                            // Element QName is not in the element_type_map: either the element is
                            // declared in the schema with no type (empty/any — skip validation),
                            // or the element is not in the schema at all (external type — skip).
                            None
                        }
                        Some(type_qn) => {
                            // Element is in the schema and maps to a type.
                            // Fail-closed: if the type is not resolvable at this point, error.
                            if resolved.type_registry.lookup(type_qn).is_none() {
                                return Err(DispatchError::UnresolvableInputType {
                                    op: op_name.clone(),
                                    element: elem_qn.to_string(),
                                    type_ref: type_qn.to_string(),
                                });
                            }
                            Some(type_qn.clone())
                        }
                    }
                }
            };
            (elem_qname, val_type)
        };

        let entry_for_element = DispatchEntry {
            handler: handler.clone(),
            auth_required,
            input_type: input_type.clone(),
            validation_type: validation_type.clone(),
        };
        let entry_for_action = DispatchEntry {
            handler,
            auth_required,
            input_type,
            validation_type,
        };

        // Index by input element QName.
        if let Some(ref qn) = entry_for_element.input_type {
            by_element.insert(qn.clone(), entry_for_element);
        } else {
            // No element reference — still insert by soap action so we can route by SOAPAction.
            drop(entry_for_element);
        }

        // Index by SOAPAction (non-empty actions only).
        if !soap_action.is_empty() {
            by_action.insert(soap_action, entry_for_action);
        }
    }

    // Verify no extra handlers were registered that have no WSDL operation.
    for handler_name in handlers.keys() {
        if !consumed_handlers.contains(handler_name) {
            return Err(DispatchError::UnknownOperation(handler_name.clone()));
        }
    }

    Ok(DispatchTable {
        by_element,
        by_action,
        default_handler,
    })
}

/// Resolve the input element QName for a named operation.
/// Searches through port_types for an operation by name, then resolves its input message's
/// first part element reference.
fn resolve_input_element(resolved: &ResolvedWsdl, op_name: &str) -> Option<QName> {
    // Search all port_types for this operation.
    for port_type in resolved.definition.port_types.values() {
        for op in &port_type.operations {
            if op.name != op_name {
                continue;
            }
            let input_msg_ref = op.input.as_ref()?;
            // Resolve the message QName (local_name is the key in the messages map).
            let msg_local = &input_msg_ref.message.local_name;
            let message = resolved.definition.messages.get(msg_local)?;
            // Take the element attribute of the first part (document/literal style).
            let first_part = message.parts.first()?;
            return first_part.element.clone();
        }
    }
    None
}

/// Route an incoming request to its handler.
///
/// Tries `by_element` lookup first (document/literal dispatch by body first-child QName).
/// Falls back to `by_action` if `soap_action` is provided and body-QName lookup fails.
/// Returns `Err(SoapFault)` with `FaultCode::Sender` if no match is found.
pub fn route<'a>(
    table: &'a DispatchTable,
    body_first_child_qname: &QName,
    soap_action: Option<&str>,
) -> Result<&'a DispatchEntry, SoapFault> {
    // Primary: by element QName.
    if let Some(entry) = table.by_element.get(body_first_child_qname) {
        return Ok(entry);
    }

    // Fallback: by SOAPAction header.
    if let Some(action) = soap_action {
        if let Some(entry) = table.by_action.get(action) {
            return Ok(entry);
        }
    }

    Err(SoapFault::action_not_supported(
        &body_first_child_qname.to_string(),
    ))
    // Note: default_handler is not reachable via route() — it is used at build_dispatch_table()
    // time to fill entries for unregistered operations, so by dispatch time all entries exist.
}

/// XSD-11: Structural validation of the request body against the operation's input type.
///
/// Parses `body_bytes` as XML and checks that all elements with `min_occurs > 0` in the
/// resolved ComplexType are present as children of the root element.
///
/// Returns `Ok(())` if:
/// - `input_type` is `None` (no type information — skip validation)
/// - `input_type` is `Some(qname)` but `qname` is not in the registry (unknown type — skip)
/// - All required elements are present
///
/// Returns `Err(SoapFault::sender(...))` if a required child element is missing.
pub fn validate_request(
    body_bytes: &[u8],
    type_registry: &TypeRegistry,
    input_type: Option<&QName>,
) -> Result<(), SoapFault> {
    let Some(qname) = input_type else {
        return Ok(());
    };

    let Some(xsd_type) = type_registry.lookup(qname) else {
        return Ok(()); // Unknown type — skip validation (not an error)
    };

    // Extract required element names from the ComplexType.
    let required_names = collect_required_element_names(xsd_type);
    if required_names.is_empty() {
        return Ok(());
    }

    // Parse body_bytes and collect the local names of direct children of the root element.
    let present_children = parse_child_element_names(body_bytes)
        .map_err(|e| SoapFault::sender(format!("Schema validation failed: malformed XML: {e}")))?;

    for required in &required_names {
        if !present_children.contains(required) {
            return Err(SoapFault::sender(format!(
                "Schema validation failed: required element '{required}' is missing"
            )));
        }
    }

    Ok(())
}

/// Collect local names of elements with min_occurs > 0 from the top-level content model.
fn collect_required_element_names(xsd_type: &crate::xsd::types::XsdType) -> Vec<String> {
    use crate::xsd::types::XsdType;
    match xsd_type {
        XsdType::Complex(ct) => collect_required_from_content(&ct.content),
        XsdType::Simple(_) => vec![],
    }
}

fn collect_required_from_content(content: &ComplexContent) -> Vec<String> {
    let elements = match content {
        ComplexContent::Sequence(els) | ComplexContent::All(els) => els,
        // xs:choice: individual children are NOT independently required — the choice
        // as a whole may be required (minOccurs > 0 on the choice group itself), but
        // a valid request only provides ONE branch. Returning an empty required list
        // prevents the validator from demanding all branches simultaneously.
        ComplexContent::Choice(_) => return vec![],
        ComplexContent::ComplexExtension { content, .. } => {
            return collect_required_from_content(content)
        }
        ComplexContent::ComplexRestriction { content, .. } => {
            return collect_required_from_content(content)
        }
        ComplexContent::Empty | ComplexContent::SimpleContent(_) => return vec![],
    };

    elements
        .iter()
        .filter_map(|el| {
            if el.min_occurs > 0 {
                el.name.clone()
            } else {
                None
            }
        })
        .collect()
}

/// Use quick-xml to parse body_bytes and return the local names of direct children
/// of the root element (one level deep).
fn parse_child_element_names(body_bytes: &[u8]) -> Result<HashSet<String>, String> {
    use quick_xml::events::Event;
    use quick_xml::Reader;

    let mut reader = Reader::from_reader(body_bytes);
    reader.config_mut().trim_text(true);

    let mut depth: u32 = 0;
    let mut children: HashSet<String> = HashSet::new();

    loop {
        match reader.read_event() {
            Ok(Event::Start(e)) => {
                depth += 1;
                if depth == 2 {
                    // Direct child of root element
                    let local_name = e.local_name();
                    let name = std::str::from_utf8(local_name.as_ref())
                        .map_err(|e| e.to_string())?
                        .to_string();
                    children.insert(name);
                }
            }
            Ok(Event::Empty(e)) => {
                if depth == 1 {
                    // Self-closing direct child of root
                    let local_name = e.local_name();
                    let name = std::str::from_utf8(local_name.as_ref())
                        .map_err(|e| e.to_string())?
                        .to_string();
                    children.insert(name);
                }
            }
            Ok(Event::End(_)) => {
                if depth == 0 {
                    break;
                }
                depth -= 1;
            }
            Ok(Event::Eof) => break,
            Err(e) => return Err(e.to_string()),
            _ => {}
        }
    }

    Ok(children)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::fault::{FaultCode, SoapFault};
    use crate::handler::SoapHandler;
    use crate::qname::QName;
    use crate::wsdl::definitions::*;
    use crate::wsdl::resolver::ResolvedWsdl;
    use crate::xsd::elements::XsdElement;
    use crate::xsd::types::{ComplexContent, ComplexType, TypeRegistry, XsdType};
    use async_trait::async_trait;
    use bytes::Bytes;
    use std::sync::Arc;

    // ── Test handler ──────────────────────────────────────────────────────────

    struct MockHandler {
        name: &'static str,
    }

    #[async_trait]
    impl SoapHandler for MockHandler {
        async fn handle(&self, _body: Bytes) -> Result<Bytes, SoapFault> {
            Ok(Bytes::from(format!("<response>{}</response>", self.name)))
        }
    }

    fn mock_handler(name: &'static str) -> Arc<dyn SoapHandler> {
        Arc::new(MockHandler { name })
    }

    // ── Minimal ResolvedWsdl builder ──────────────────────────────────────────

    /// Build a minimal ResolvedWsdl with one service, one port, one binding, one operation.
    fn make_resolved_wsdl(
        op_name: &str,
        soap_action: &str,
        input_element_qname: Option<QName>,
    ) -> ResolvedWsdl {
        let target_ns = "http://example.com/service".to_string();
        let msg_name = format!("{op_name}Request");

        // Message: one part with the element reference
        let part = MessagePart {
            name: "parameters".to_string(),
            element: input_element_qname,
            type_ref: None,
        };
        let message = Message {
            name: msg_name.clone(),
            parts: vec![part],
        };

        // PortType operation
        let pt_op = Operation {
            name: op_name.to_string(),
            input: Some(OperationMessage {
                name: None,
                message: QName::local(&msg_name),
            }),
            output: None,
            faults: vec![],
            style: OperationStyle::RequestResponse,
        };
        let port_type = PortType {
            name: "TestPortType".to_string(),
            operations: vec![pt_op],
        };

        // Binding operation
        let binding_op = BindingOperation {
            name: op_name.to_string(),
            soap_action: soap_action.to_string(),
            input: BindingMessage {
                body: SoapBody {
                    use_attr: UseStyle::Literal,
                    namespace: None,
                    encoding_style: None,
                },
                headers: vec![],
            },
            output: BindingMessage {
                body: SoapBody {
                    use_attr: UseStyle::Literal,
                    namespace: None,
                    encoding_style: None,
                },
                headers: vec![],
            },
        };
        let binding = Binding {
            name: "TestBinding".to_string(),
            port_type: QName::local("TestPortType"),
            soap_binding: SoapBinding {
                style: BindingStyle::Document,
                transport: "http://schemas.xmlsoap.org/soap/http".to_string(),
                soap_version: SoapVersion::Soap12,
            },
            operations: vec![binding_op],
        };

        // Service + Port
        let port = Port {
            name: "TestPort".to_string(),
            binding: QName::local("TestBinding"),
            address: "http://localhost/service".to_string(),
        };
        let service = Service {
            name: "TestService".to_string(),
            ports: vec![port],
        };

        let mut messages = HashMap::new();
        messages.insert(msg_name, message);
        let mut port_types = HashMap::new();
        port_types.insert("TestPortType".to_string(), port_type);
        let mut bindings = HashMap::new();
        bindings.insert("TestBinding".to_string(), binding);
        let mut services = HashMap::new();
        services.insert("TestService".to_string(), service);

        let definition = WsdlDefinition {
            target_namespace: target_ns,
            imports: vec![],
            types: TypesSection::default(),
            messages,
            port_types,
            bindings,
            services,
        };

        ResolvedWsdl {
            definition,
            type_registry: TypeRegistry::new(),
            element_type_map: HashMap::new(),
            raw_bytes: vec![],
        }
    }

    // ── build_dispatch_table tests ────────────────────────────────────────────

    #[test]
    fn dispatch_table_routes_by_element_qname() {
        let elem_qname = QName::new("http://example.com", "GetProfiles");
        let resolved =
            make_resolved_wsdl("GetProfiles", "urn:GetProfiles", Some(elem_qname.clone()));

        let mut handlers = HashMap::new();
        handlers.insert("GetProfiles".to_string(), mock_handler("GetProfiles"));

        let table = build_dispatch_table(&resolved, handlers, &HashSet::new(), None).unwrap();
        let entry = route(&table, &elem_qname, None).unwrap();

        // Handler is present (we can verify by running it synchronously via block_on equivalent)
        assert!(entry.auth_required); // default: auth required
    }

    #[test]
    fn dispatch_table_unregistered_operation_fails_at_build() {
        let elem_qname = QName::new("http://example.com", "GetProfiles");
        let resolved = make_resolved_wsdl("GetProfiles", "urn:GetProfiles", Some(elem_qname));

        // No handlers provided at all — should fail at startup
        let handlers: HashMap<String, Arc<dyn SoapHandler>> = HashMap::new();
        let result = build_dispatch_table(&resolved, handlers, &HashSet::new(), None);

        assert!(
            matches!(result, Err(DispatchError::UnregisteredOperation(ref name)) if name == "GetProfiles")
        );
    }

    #[test]
    fn dispatch_table_unknown_handler_name_fails_at_build() {
        let elem_qname = QName::new("http://example.com", "GetProfiles");
        let resolved = make_resolved_wsdl("GetProfiles", "urn:GetProfiles", Some(elem_qname));

        let mut handlers = HashMap::new();
        handlers.insert("GetProfiles".to_string(), mock_handler("GetProfiles"));
        handlers.insert("NonExistentOp".to_string(), mock_handler("ghost")); // no WSDL op

        let result = build_dispatch_table(&resolved, handlers, &HashSet::new(), None);
        assert!(
            matches!(result, Err(DispatchError::UnknownOperation(ref name)) if name == "NonExistentOp")
        );
    }

    #[test]
    fn route_unknown_qname_no_soap_action_returns_sender_fault() {
        let elem_qname = QName::new("http://example.com", "GetProfiles");
        let resolved =
            make_resolved_wsdl("GetProfiles", "urn:GetProfiles", Some(elem_qname.clone()));

        let mut handlers = HashMap::new();
        handlers.insert("GetProfiles".to_string(), mock_handler("GetProfiles"));
        let table = build_dispatch_table(&resolved, handlers, &HashSet::new(), None).unwrap();

        let unknown = QName::new("http://example.com", "UnknownOperation");
        let result = route(&table, &unknown, None);

        assert!(result.is_err());
        let fault = result.unwrap_err();
        assert_eq!(fault.code, FaultCode::Sender);
        assert!(
            fault.reason.to_lowercase().contains("action")
                || fault.reason.to_lowercase().contains("supported")
        );
    }

    #[test]
    fn route_falls_back_to_soap_action_on_unknown_qname() {
        let elem_qname = QName::new("http://example.com", "GetProfiles");
        let resolved =
            make_resolved_wsdl("GetProfiles", "urn:GetProfiles", Some(elem_qname.clone()));

        let mut handlers = HashMap::new();
        handlers.insert("GetProfiles".to_string(), mock_handler("GetProfiles"));
        let table = build_dispatch_table(&resolved, handlers, &HashSet::new(), None).unwrap();

        // Unknown body QName but known SOAPAction
        let unknown = QName::local("SomethingElse");
        let result = route(&table, &unknown, Some("urn:GetProfiles"));
        assert!(result.is_ok(), "Expected fallback to SOAPAction to succeed");
    }

    #[test]
    fn route_unknown_qname_unknown_soap_action_returns_fault() {
        let elem_qname = QName::new("http://example.com", "GetProfiles");
        let resolved =
            make_resolved_wsdl("GetProfiles", "urn:GetProfiles", Some(elem_qname.clone()));

        let mut handlers = HashMap::new();
        handlers.insert("GetProfiles".to_string(), mock_handler("GetProfiles"));
        let table = build_dispatch_table(&resolved, handlers, &HashSet::new(), None).unwrap();

        let unknown = QName::local("SomethingElse");
        let result = route(&table, &unknown, Some("urn:UnknownAction"));
        assert!(result.is_err());
        assert_eq!(result.unwrap_err().code, FaultCode::Sender);
    }

    #[test]
    fn auth_bypass_marks_entry_auth_not_required() {
        let elem_qname = QName::new("http://example.com", "GetProfiles");
        let resolved =
            make_resolved_wsdl("GetProfiles", "urn:GetProfiles", Some(elem_qname.clone()));

        let mut handlers = HashMap::new();
        handlers.insert("GetProfiles".to_string(), mock_handler("GetProfiles"));

        let mut bypass = HashSet::new();
        bypass.insert("GetProfiles".to_string());

        let table = build_dispatch_table(&resolved, handlers, &bypass, None).unwrap();
        let entry = route(&table, &elem_qname, None).unwrap();
        assert!(!entry.auth_required); // bypassed — no auth required
    }

    #[test]
    fn auth_required_by_default_for_non_bypass_op() {
        let elem_qname = QName::new("http://example.com", "SetSomething");
        let resolved =
            make_resolved_wsdl("SetSomething", "urn:SetSomething", Some(elem_qname.clone()));

        let mut handlers = HashMap::new();
        handlers.insert("SetSomething".to_string(), mock_handler("SetSomething"));

        let table = build_dispatch_table(&resolved, handlers, &HashSet::new(), None).unwrap();
        let entry = route(&table, &elem_qname, None).unwrap();
        assert!(entry.auth_required);
    }

    // ── validate_request tests ────────────────────────────────────────────────

    fn make_type_registry_with_required_field(
        type_qname: &QName,
        required_field: &str,
    ) -> TypeRegistry {
        let element = XsdElement {
            name: Some(required_field.to_string()),
            min_occurs: 1,
            ..Default::default()
        };
        let ct = ComplexType {
            name: Some(type_qname.local_name.clone()),
            content: ComplexContent::Sequence(vec![element]),
            attributes: vec![],
        };
        let mut reg = TypeRegistry::new();
        reg.insert(type_qname.clone(), XsdType::Complex(Box::new(ct)));
        reg
    }

    #[test]
    fn validate_request_no_input_type_returns_ok() {
        let reg = TypeRegistry::new();
        let result = validate_request(b"<GetProfiles/>", &reg, None);
        assert!(result.is_ok());
    }

    #[test]
    fn validate_request_unknown_type_in_registry_returns_ok() {
        let reg = TypeRegistry::new(); // empty — unknown type
        let qname = QName::new("http://example.com", "GetProfilesRequest");
        let result = validate_request(b"<GetProfiles/>", &reg, Some(&qname));
        assert!(result.is_ok());
    }

    #[test]
    fn validate_request_valid_xml_with_required_element_returns_ok() {
        let qname = QName::new("http://example.com", "GetProfilesRequest");
        let reg = make_type_registry_with_required_field(&qname, "Token");

        let body = b"<GetProfiles xmlns=\"http://example.com\"><Token>1234</Token></GetProfiles>";
        let result = validate_request(body, &reg, Some(&qname));
        assert!(result.is_ok(), "Expected Ok, got: {result:?}");
    }

    #[test]
    fn validate_request_missing_required_element_returns_sender_fault() {
        let qname = QName::new("http://example.com", "GetProfilesRequest");
        let reg = make_type_registry_with_required_field(&qname, "Token");

        // Body has no <Token> child
        let body = b"<GetProfiles xmlns=\"http://example.com\"></GetProfiles>";
        let result = validate_request(body, &reg, Some(&qname));
        assert!(result.is_err());
        let fault = result.unwrap_err();
        assert_eq!(fault.code, FaultCode::Sender);
        assert!(fault.reason.contains("Schema validation failed"));
        assert!(fault.reason.contains("Token"));
    }

    #[test]
    fn validate_request_optional_element_missing_returns_ok() {
        let qname = QName::new("http://example.com", "GetProfilesRequest");
        let optional_el = XsdElement {
            name: Some("OptionalField".to_string()),
            min_occurs: 0,
            ..Default::default()
        };
        let ct = ComplexType {
            name: Some("GetProfilesRequest".to_string()),
            content: ComplexContent::Sequence(vec![optional_el]),
            attributes: vec![],
        };
        let mut reg = TypeRegistry::new();
        reg.insert(qname.clone(), XsdType::Complex(Box::new(ct)));

        let body = b"<GetProfiles xmlns=\"http://example.com\"></GetProfiles>";
        let result = validate_request(body, &reg, Some(&qname));
        assert!(result.is_ok());
    }

    #[test]
    fn handler_name_matches_wsdl_operation_name_get_profiles() {
        // Regression: "GetProfiles" key in handlers must match "GetProfiles" operation in WSDL
        let elem_qname = QName::new("http://onvif.org/ver10/media/wsdl", "GetProfiles");
        let resolved = make_resolved_wsdl(
            "GetProfiles",
            "http://www.onvif.org/ver10/media/wsdl/GetProfiles",
            Some(elem_qname.clone()),
        );

        let mut handlers = HashMap::new();
        handlers.insert("GetProfiles".to_string(), mock_handler("GetProfiles"));

        let table = build_dispatch_table(&resolved, handlers, &HashSet::new(), None).unwrap();
        let entry = route(&table, &elem_qname, None).unwrap();
        assert!(entry.auth_required);
    }

    // ── RPC binding tests ─────────────────────────────────────────────────────

    /// Build a minimal ResolvedWsdl with RPC-style binding.
    fn make_resolved_wsdl_rpc(
        op_name: &str,
        soap_action: &str,
        rpc_namespace: Option<&str>,
    ) -> ResolvedWsdl {
        let target_ns = "http://example.com/service".to_string();
        let msg_name = format!("{op_name}Request");

        // Message: one part with type_ref (RPC style — no element ref)
        let part = MessagePart {
            name: "parameters".to_string(),
            element: None,
            type_ref: Some(QName::new("http://www.w3.org/2001/XMLSchema", "string")),
        };
        let message = Message {
            name: msg_name.clone(),
            parts: vec![part],
        };

        // PortType operation
        let pt_op = Operation {
            name: op_name.to_string(),
            input: Some(OperationMessage {
                name: None,
                message: QName::local(&msg_name),
            }),
            output: None,
            faults: vec![],
            style: OperationStyle::RequestResponse,
        };
        let port_type = PortType {
            name: "TestPortType".to_string(),
            operations: vec![pt_op],
        };

        // Binding operation with RPC-specific namespace
        let binding_op = BindingOperation {
            name: op_name.to_string(),
            soap_action: soap_action.to_string(),
            input: BindingMessage {
                body: SoapBody {
                    use_attr: UseStyle::Encoded,
                    namespace: rpc_namespace.map(|s| s.to_string()),
                    encoding_style: None,
                },
                headers: vec![],
            },
            output: BindingMessage {
                body: SoapBody {
                    use_attr: UseStyle::Encoded,
                    namespace: rpc_namespace.map(|s| s.to_string()),
                    encoding_style: None,
                },
                headers: vec![],
            },
        };
        let binding = Binding {
            name: "TestBinding".to_string(),
            port_type: QName::local("TestPortType"),
            soap_binding: SoapBinding {
                style: BindingStyle::Rpc,
                transport: "http://schemas.xmlsoap.org/soap/http".to_string(),
                soap_version: SoapVersion::Soap12,
            },
            operations: vec![binding_op],
        };

        // Service + Port
        let port = Port {
            name: "TestPort".to_string(),
            binding: QName::local("TestBinding"),
            address: "http://localhost/service".to_string(),
        };
        let service = Service {
            name: "TestService".to_string(),
            ports: vec![port],
        };

        let mut messages = HashMap::new();
        messages.insert(msg_name, message);
        let mut port_types = HashMap::new();
        port_types.insert("TestPortType".to_string(), port_type);
        let mut bindings = HashMap::new();
        bindings.insert("TestBinding".to_string(), binding);
        let mut services = HashMap::new();
        services.insert("TestService".to_string(), service);

        let definition = WsdlDefinition {
            target_namespace: target_ns,
            imports: vec![],
            types: TypesSection::default(),
            messages,
            port_types,
            bindings,
            services,
        };

        ResolvedWsdl {
            definition,
            type_registry: crate::xsd::types::TypeRegistry::new(),
            element_type_map: HashMap::new(),
            raw_bytes: vec![],
        }
    }

    /// Build a ResolvedWsdl with two services (ServiceA and ServiceB), each with their own
    /// binding and operations.
    fn make_resolved_wsdl_two_services() -> ResolvedWsdl {
        let target_ns = "http://example.com/multi".to_string();

        // Messages
        let msg_a = Message {
            name: "OpARequest".to_string(),
            parts: vec![MessagePart {
                name: "parameters".to_string(),
                element: Some(QName::new("http://example.com/multi", "OpA")),
                type_ref: None,
            }],
        };
        let msg_b = Message {
            name: "OpBRequest".to_string(),
            parts: vec![MessagePart {
                name: "parameters".to_string(),
                element: Some(QName::new("http://example.com/multi", "OpB")),
                type_ref: None,
            }],
        };

        // PortTypes
        let pt_a = PortType {
            name: "PortTypeA".to_string(),
            operations: vec![Operation {
                name: "OpA".to_string(),
                input: Some(OperationMessage {
                    name: None,
                    message: QName::local("OpARequest"),
                }),
                output: None,
                faults: vec![],
                style: OperationStyle::RequestResponse,
            }],
        };
        let pt_b = PortType {
            name: "PortTypeB".to_string(),
            operations: vec![Operation {
                name: "OpB".to_string(),
                input: Some(OperationMessage {
                    name: None,
                    message: QName::local("OpBRequest"),
                }),
                output: None,
                faults: vec![],
                style: OperationStyle::RequestResponse,
            }],
        };

        // Bindings
        let binding_a = Binding {
            name: "BindingA".to_string(),
            port_type: QName::local("PortTypeA"),
            soap_binding: SoapBinding {
                style: BindingStyle::Document,
                transport: "http://schemas.xmlsoap.org/soap/http".to_string(),
                soap_version: SoapVersion::Soap12,
            },
            operations: vec![BindingOperation {
                name: "OpA".to_string(),
                soap_action: "urn:OpA".to_string(),
                input: BindingMessage {
                    body: SoapBody {
                        use_attr: UseStyle::Literal,
                        namespace: None,
                        encoding_style: None,
                    },
                    headers: vec![],
                },
                output: BindingMessage {
                    body: SoapBody {
                        use_attr: UseStyle::Literal,
                        namespace: None,
                        encoding_style: None,
                    },
                    headers: vec![],
                },
            }],
        };
        let binding_b = Binding {
            name: "BindingB".to_string(),
            port_type: QName::local("PortTypeB"),
            soap_binding: SoapBinding {
                style: BindingStyle::Document,
                transport: "http://schemas.xmlsoap.org/soap/http".to_string(),
                soap_version: SoapVersion::Soap12,
            },
            operations: vec![BindingOperation {
                name: "OpB".to_string(),
                soap_action: "urn:OpB".to_string(),
                input: BindingMessage {
                    body: SoapBody {
                        use_attr: UseStyle::Literal,
                        namespace: None,
                        encoding_style: None,
                    },
                    headers: vec![],
                },
                output: BindingMessage {
                    body: SoapBody {
                        use_attr: UseStyle::Literal,
                        namespace: None,
                        encoding_style: None,
                    },
                    headers: vec![],
                },
            }],
        };

        // Services
        let service_a = Service {
            name: "ServiceA".to_string(),
            ports: vec![Port {
                name: "PortA".to_string(),
                binding: QName::local("BindingA"),
                address: "http://localhost/soap/a".to_string(),
            }],
        };
        let service_b = Service {
            name: "ServiceB".to_string(),
            ports: vec![Port {
                name: "PortB".to_string(),
                binding: QName::local("BindingB"),
                address: "http://localhost/soap/b".to_string(),
            }],
        };

        let mut messages = HashMap::new();
        messages.insert("OpARequest".to_string(), msg_a);
        messages.insert("OpBRequest".to_string(), msg_b);
        let mut port_types = HashMap::new();
        port_types.insert("PortTypeA".to_string(), pt_a);
        port_types.insert("PortTypeB".to_string(), pt_b);
        let mut bindings = HashMap::new();
        bindings.insert("BindingA".to_string(), binding_a);
        bindings.insert("BindingB".to_string(), binding_b);
        let mut services = HashMap::new();
        services.insert("ServiceA".to_string(), service_a);
        services.insert("ServiceB".to_string(), service_b);

        let definition = WsdlDefinition {
            target_namespace: target_ns,
            imports: vec![],
            types: TypesSection::default(),
            messages,
            port_types,
            bindings,
            services,
        };

        ResolvedWsdl {
            definition,
            type_registry: crate::xsd::types::TypeRegistry::new(),
            element_type_map: HashMap::new(),
            raw_bytes: vec![],
        }
    }

    #[test]
    fn build_dispatch_table_rpc_binding() {
        let resolved = make_resolved_wsdl_rpc("GetOp", "urn:GetOp", Some("http://example.com/svc"));

        let mut handlers = HashMap::new();
        handlers.insert("GetOp".to_string(), mock_handler("GetOp"));

        let table = build_dispatch_table(&resolved, handlers, &HashSet::new(), None).unwrap();

        // RPC dispatch key: (soap:body namespace, operation name)
        let rpc_qname = QName::new("http://example.com/svc", "GetOp");
        let result = route(&table, &rpc_qname, None);
        assert!(
            result.is_ok(),
            "Expected RPC QName to route successfully, got: {result:?}"
        );
    }

    #[test]
    fn rpc_dispatch_by_wrapper_element() {
        let resolved = make_resolved_wsdl_rpc("GetOp", "urn:GetOp", Some("http://example.com/svc"));

        let mut handlers = HashMap::new();
        handlers.insert("GetOp".to_string(), mock_handler("GetOp"));

        let table = build_dispatch_table(&resolved, handlers, &HashSet::new(), None).unwrap();

        // Confirm the entry is in by_element keyed on the synthesized QName
        let rpc_qname = QName::new("http://example.com/svc", "GetOp");
        let result = route(&table, &rpc_qname, None);
        assert!(
            result.is_ok(),
            "route by synthesized RPC QName should return Ok"
        );
    }

    #[test]
    fn build_dispatch_table_rpc_missing_namespace_falls_back_to_target_ns() {
        // When soap:body.namespace is None for an RPC binding, fall back to WSDL targetNamespace
        let resolved = make_resolved_wsdl_rpc("GetOp", "urn:GetOp", None);
        let target_ns = resolved.definition.target_namespace.clone();

        let mut handlers = HashMap::new();
        handlers.insert("GetOp".to_string(), mock_handler("GetOp"));

        let table = build_dispatch_table(&resolved, handlers, &HashSet::new(), None).unwrap();

        // Should be keyed by (targetNamespace, opName)
        let fallback_qname = QName::new(&target_ns, "GetOp");
        let result = route(&table, &fallback_qname, None);
        assert!(
            result.is_ok(),
            "RPC without namespace should fall back to targetNamespace, got: {result:?}"
        );
    }

    #[test]
    fn build_dispatch_table_for_service_isolates_operations() {
        let resolved = make_resolved_wsdl_two_services();

        let op_a_qname = QName::new("http://example.com/multi", "OpA");
        let op_b_qname = QName::new("http://example.com/multi", "OpB");

        let mut handlers_a = HashMap::new();
        handlers_a.insert("OpA".to_string(), mock_handler("OpA"));

        let mut handlers_b = HashMap::new();
        handlers_b.insert("OpB".to_string(), mock_handler("OpB"));

        let table_a = build_dispatch_table_for_service(
            "ServiceA",
            &resolved,
            handlers_a,
            &HashSet::new(),
            None,
        )
        .unwrap();
        let table_b = build_dispatch_table_for_service(
            "ServiceB",
            &resolved,
            handlers_b,
            &HashSet::new(),
            None,
        )
        .unwrap();

        // ServiceA table contains OpA
        assert!(
            route(&table_a, &op_a_qname, None).is_ok(),
            "ServiceA should route OpA"
        );
        // ServiceB table contains OpB
        assert!(
            route(&table_b, &op_b_qname, None).is_ok(),
            "ServiceB should route OpB"
        );
        // ServiceA table does NOT contain OpB
        assert!(
            route(&table_a, &op_b_qname, None).is_err(),
            "ServiceA should NOT route OpB"
        );
    }

    // ── Finding #3: document/literal element validation tests ────────────────

    /// WSDL with a document/literal operation whose input element has an INLINE complexType
    /// containing a REQUIRED child element.
    const INLINE_ELEMENT_WSDL: &str = r#"<?xml version="1.0" encoding="UTF-8"?>
<definitions xmlns="http://schemas.xmlsoap.org/wsdl/"
  xmlns:soap12="http://schemas.xmlsoap.org/wsdl/soap12/"
  xmlns:tns="http://example.com/svc"
  xmlns:xs="http://www.w3.org/2001/XMLSchema"
  targetNamespace="http://example.com/svc">
  <types>
    <xs:schema targetNamespace="http://example.com/svc" xmlns:xs="http://www.w3.org/2001/XMLSchema">
      <xs:element name="GetFoo">
        <xs:complexType>
          <xs:sequence>
            <xs:element name="RequiredField" type="xs:string" minOccurs="1"/>
            <xs:element name="OptionalField" type="xs:string" minOccurs="0"/>
          </xs:sequence>
        </xs:complexType>
      </xs:element>
      <xs:element name="GetFooResponse">
        <xs:complexType><xs:sequence/></xs:complexType>
      </xs:element>
    </xs:schema>
  </types>
  <message name="GetFooRequest"><part name="parameters" element="tns:GetFoo"/></message>
  <message name="GetFooResponse"><part name="parameters" element="tns:GetFooResponse"/></message>
  <portType name="SvcPortType">
    <operation name="GetFoo">
      <input message="tns:GetFooRequest"/>
      <output message="tns:GetFooResponse"/>
    </operation>
  </portType>
  <binding name="SvcBinding" type="tns:SvcPortType">
    <soap12:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/>
    <operation name="GetFoo">
      <soap12:operation soapAction="urn:GetFoo"/>
      <input><soap12:body use="literal"/></input>
      <output><soap12:body use="literal"/></output>
    </operation>
  </binding>
  <service name="SvcService">
    <port name="SvcPort" binding="tns:SvcBinding">
      <soap12:address location="http://localhost/svc"/>
    </port>
  </service>
</definitions>"#;

    /// WSDL with a document/literal operation whose input element uses a named type reference.
    const NAMED_TYPE_REF_WSDL: &str = r#"<?xml version="1.0" encoding="UTF-8"?>
<definitions xmlns="http://schemas.xmlsoap.org/wsdl/"
  xmlns:soap12="http://schemas.xmlsoap.org/wsdl/soap12/"
  xmlns:tns="http://example.com/svc"
  xmlns:xs="http://www.w3.org/2001/XMLSchema"
  targetNamespace="http://example.com/svc">
  <types>
    <xs:schema targetNamespace="http://example.com/svc" xmlns:xs="http://www.w3.org/2001/XMLSchema">
      <xs:complexType name="GetBarType">
        <xs:sequence>
          <xs:element name="BarRequired" type="xs:string" minOccurs="1"/>
        </xs:sequence>
      </xs:complexType>
      <xs:element name="GetBar" type="tns:GetBarType"/>
      <xs:element name="GetBarResponse">
        <xs:complexType><xs:sequence/></xs:complexType>
      </xs:element>
    </xs:schema>
  </types>
  <message name="GetBarRequest"><part name="parameters" element="tns:GetBar"/></message>
  <message name="GetBarResponse"><part name="parameters" element="tns:GetBarResponse"/></message>
  <portType name="SvcPortType">
    <operation name="GetBar">
      <input message="tns:GetBarRequest"/>
      <output message="tns:GetBarResponse"/>
    </operation>
  </portType>
  <binding name="SvcBinding" type="tns:SvcPortType">
    <soap12:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/>
    <operation name="GetBar">
      <soap12:operation soapAction="urn:GetBar"/>
      <input><soap12:body use="literal"/></input>
      <output><soap12:body use="literal"/></output>
    </operation>
  </binding>
  <service name="SvcService">
    <port name="SvcPort" binding="tns:SvcBinding">
      <soap12:address location="http://localhost/svc"/>
    </port>
  </service>
</definitions>"#;

    fn resolve_test_wsdl(wsdl: &str) -> ResolvedWsdl {
        use crate::wsdl::parser::WsdlError;
        use crate::wsdl::resolver::{resolve_wsdl, WsdlLoader};
        struct NullLoader;
        impl WsdlLoader for NullLoader {
            fn load(&self, loc: &str) -> Result<Vec<u8>, WsdlError> {
                Err(WsdlError::MalformedXml(format!("NullLoader: {loc}")))
            }
        }
        let mut visited = HashSet::new();
        resolve_wsdl(wsdl.as_bytes(), &NullLoader, &mut visited)
            .expect("WSDL resolution should succeed")
    }

    /// Document/literal op with inline complexType: request missing required field must be REJECTED.
    #[test]
    fn doc_literal_inline_type_missing_required_field_rejected() {
        let resolved = resolve_test_wsdl(INLINE_ELEMENT_WSDL);

        let elem_qname = QName::new("http://example.com/svc", "GetFoo");

        // The validation_type for GetFoo should now be the element QName itself
        // (because we register inline element types under element QName in TypeRegistry).
        assert!(
            resolved.type_registry.lookup(&elem_qname).is_some(),
            "Inline element type must be in TypeRegistry after resolve_wsdl"
        );

        // Build a minimal table and check validation rejects missing required field.
        let mut handlers = HashMap::new();
        handlers.insert("GetFoo".to_string(), mock_handler("GetFoo"));
        let table = build_dispatch_table(&resolved, handlers, &HashSet::new(), None).unwrap();

        let entry = route(&table, &elem_qname, None).unwrap();
        // validation_type must be set (not None) for validation to work
        assert!(
            entry.validation_type.is_some(),
            "validation_type must be Some for document/literal op with inline type"
        );

        // Request omitting RequiredField must be rejected
        let body_missing = br#"<tns:GetFoo xmlns:tns="http://example.com/svc"/>"#;
        let result = validate_request(
            body_missing,
            &resolved.type_registry,
            entry.validation_type.as_ref(),
        );
        assert!(
            result.is_err(),
            "Request missing RequiredField must produce a validation error"
        );
        let fault = result.unwrap_err();
        assert_eq!(fault.code, crate::fault::FaultCode::Sender);
        assert!(
            fault.reason.contains("RequiredField"),
            "Fault reason must mention the missing field, got: {}",
            fault.reason
        );

        // Request including RequiredField must pass
        let body_ok = br#"<tns:GetFoo xmlns:tns="http://example.com/svc"><tns:RequiredField>val</tns:RequiredField></tns:GetFoo>"#;
        let result_ok = validate_request(
            body_ok,
            &resolved.type_registry,
            entry.validation_type.as_ref(),
        );
        assert!(
            result_ok.is_ok(),
            "Request with RequiredField must pass validation, got: {result_ok:?}"
        );
    }

    /// Document/literal op with named type reference: missing required field must also be REJECTED.
    #[test]
    fn doc_literal_named_type_ref_missing_required_field_rejected() {
        let resolved = resolve_test_wsdl(NAMED_TYPE_REF_WSDL);

        let elem_qname = QName::new("http://example.com/svc", "GetBar");
        let type_qname = QName::new("http://example.com/svc", "GetBarType");

        // The named type must be in registry.
        assert!(
            resolved.type_registry.lookup(&type_qname).is_some(),
            "Named type GetBarType must be in TypeRegistry"
        );

        // Build table — element_type_map for GetBar should point to GetBarType.
        let mut handlers = HashMap::new();
        handlers.insert("GetBar".to_string(), mock_handler("GetBar"));
        let table = build_dispatch_table(&resolved, handlers, &HashSet::new(), None).unwrap();

        let entry = route(&table, &elem_qname, None).unwrap();
        assert!(
            entry.validation_type.is_some(),
            "validation_type must be Some for document/literal op with named type ref"
        );
        // validation_type should be GetBarType, not GetBar
        assert_eq!(
            entry.validation_type.as_ref().unwrap(),
            &type_qname,
            "validation_type must be the named type QName, not the element QName"
        );

        // Request omitting BarRequired must be rejected
        let body_missing = br#"<tns:GetBar xmlns:tns="http://example.com/svc"/>"#;
        let result = validate_request(
            body_missing,
            &resolved.type_registry,
            entry.validation_type.as_ref(),
        );
        assert!(
            result.is_err(),
            "Request missing BarRequired must produce a validation error"
        );
        let fault = result.unwrap_err();
        assert_eq!(fault.code, crate::fault::FaultCode::Sender);
        assert!(
            fault.reason.contains("BarRequired"),
            "Fault reason must mention the missing field, got: {}",
            fault.reason
        );

        // Request including BarRequired must pass
        let body_ok = br#"<tns:GetBar xmlns:tns="http://example.com/svc"><tns:BarRequired>val</tns:BarRequired></tns:GetBar>"#;
        let result_ok = validate_request(
            body_ok,
            &resolved.type_registry,
            entry.validation_type.as_ref(),
        );
        assert!(
            result_ok.is_ok(),
            "Request with BarRequired must pass validation, got: {result_ok:?}"
        );
    }
}