oxirs-samm 0.2.2

Semantic Aspect Meta Model (SAMM) implementation for OxiRS
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
//! SAMM Operation → REST/MQTT API Mapping
//!
//! This module transforms SAMM (Semantic Aspect Meta Model) operation definitions
//! into concrete REST endpoint and MQTT topic specifications, and can generate
//! OpenAPI 3.0 and AsyncAPI YAML fragments.
//!
//! # Overview
//!
//! A SAMM `Operation` describes a function that can be invoked on an Aspect.
//! This mapper derives:
//!
//! - A REST endpoint (HTTP method + path + query params + JSON schemas)
//! - An MQTT topic (topic pattern + QoS + payload schema)
//! - Or both combined into an `ApiMapping`
//!
//! # OpenAPI / AsyncAPI generation
//!
//! The generated YAML fragments can be embedded directly into larger API
//! specifications. They follow standard OpenAPI 3.0 / AsyncAPI 2.x conventions.

use std::fmt;

// ─── Domain types ─────────────────────────────────────────────────────────────

/// HTTP method for a REST endpoint.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum HttpMethod {
    /// HTTP GET
    Get,
    /// HTTP POST
    Post,
    /// HTTP PUT
    Put,
    /// HTTP DELETE
    Delete,
    /// HTTP PATCH
    Patch,
}

impl fmt::Display for HttpMethod {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Get => write!(f, "get"),
            Self::Post => write!(f, "post"),
            Self::Put => write!(f, "put"),
            Self::Delete => write!(f, "delete"),
            Self::Patch => write!(f, "patch"),
        }
    }
}

/// A reference to a property in a SAMM operation signature.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PropertyRef {
    /// Property name (camelCase recommended)
    pub name: String,
    /// XSD / JSON Schema data type (e.g. `"string"`, `"integer"`, `"boolean"`)
    pub data_type: String,
    /// Whether this property is optional
    pub optional: bool,
}

impl PropertyRef {
    /// Create a required property reference.
    pub fn required(name: impl Into<String>, data_type: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            data_type: data_type.into(),
            optional: false,
        }
    }

    /// Create an optional property reference.
    pub fn optional(name: impl Into<String>, data_type: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            data_type: data_type.into(),
            optional: true,
        }
    }
}

/// A SAMM operation definition.
#[derive(Debug, Clone)]
pub struct SammOperation {
    /// Operation name (used for path segment and topic name)
    pub name: String,
    /// Input properties (parameters)
    pub input_props: Vec<PropertyRef>,
    /// Output properties (response)
    pub output_props: Vec<PropertyRef>,
}

impl SammOperation {
    /// Create a new SAMM operation.
    pub fn new(
        name: impl Into<String>,
        input_props: Vec<PropertyRef>,
        output_props: Vec<PropertyRef>,
    ) -> Self {
        Self {
            name: name.into(),
            input_props,
            output_props,
        }
    }
}

/// A REST endpoint derived from a SAMM operation.
#[derive(Debug, Clone)]
pub struct RestEndpoint {
    /// HTTP method
    pub method: HttpMethod,
    /// URL path (e.g. `/operations/getTemperature`)
    pub path: String,
    /// Query parameter names (for GET operations)
    pub query_params: Vec<String>,
    /// JSON schema fragment for the request body (POST/PUT/PATCH only)
    pub body_schema: Option<String>,
    /// JSON schema fragment for the response body
    pub response_schema: String,
}

/// An MQTT topic derived from a SAMM operation.
#[derive(Debug, Clone)]
pub struct MqttTopic {
    /// Topic pattern (may include `+` and `#` wildcards)
    pub topic_pattern: String,
    /// MQTT QoS level (0, 1, or 2)
    pub qos: u8,
    /// JSON schema fragment for the message payload
    pub payload_schema: String,
}

/// A combined API mapping: REST, MQTT, or both.
#[derive(Debug, Clone)]
pub enum ApiMapping {
    /// REST endpoint only
    Rest(RestEndpoint),
    /// MQTT topic only
    Mqtt(MqttTopic),
    /// Both REST and MQTT
    Both(RestEndpoint, MqttTopic),
}

// ─── JSON schema generation helpers ──────────────────────────────────────────

/// Build a minimal inline JSON Schema object fragment from a list of properties.
fn build_json_schema(props: &[PropertyRef]) -> String {
    if props.is_empty() {
        return r#"{"type":"object","properties":{}}"#.to_string();
    }

    let mut required: Vec<&str> = Vec::new();
    let mut properties = Vec::new();

    for p in props {
        let json_type = xsd_to_json_type(&p.data_type);
        properties.push(format!(r#""{}":{{"type":"{}"}}"#, p.name, json_type));
        if !p.optional {
            required.push(p.name.as_str());
        }
    }

    let props_str = properties.join(",");
    if required.is_empty() {
        format!(r#"{{"type":"object","properties":{{{props_str}}}}}"#)
    } else {
        let req_str = required
            .iter()
            .map(|r| format!("\"{r}\""))
            .collect::<Vec<_>>()
            .join(",");
        format!(r#"{{"type":"object","properties":{{{props_str}}},"required":[{req_str}]}}"#)
    }
}

/// Map XSD / SAMM data types to JSON Schema types.
fn xsd_to_json_type(dt: &str) -> &'static str {
    match dt.to_lowercase().as_str() {
        "string" | "xsd:string" | "http://www.w3.org/2001/xmlschema#string" => "string",
        "integer" | "int" | "xsd:integer" | "xsd:int" | "long" | "short" => "integer",
        "float" | "double" | "decimal" | "xsd:float" | "xsd:double" | "xsd:decimal" => "number",
        "boolean" | "xsd:boolean" => "boolean",
        _ => "string", // safe default
    }
}

/// Convert an operation name to kebab-case path segment.
fn to_kebab_case(s: &str) -> String {
    let mut out = String::new();
    for (i, ch) in s.chars().enumerate() {
        if ch.is_uppercase() && i > 0 {
            out.push('-');
        }
        out.push(ch.to_lowercase().next().unwrap_or(ch));
    }
    out
}

/// Convert an operation name to snake_case for MQTT.
fn to_snake_case(s: &str) -> String {
    let mut out = String::new();
    for (i, ch) in s.chars().enumerate() {
        if ch.is_uppercase() && i > 0 {
            out.push('_');
        }
        out.push(ch.to_lowercase().next().unwrap_or(ch));
    }
    out
}

// ─── Mapper ───────────────────────────────────────────────────────────────────

/// Maps SAMM operations to REST and/or MQTT API definitions.
#[derive(Debug, Default)]
pub struct OperationMapper {
    /// Default QoS level for generated MQTT topics
    pub default_qos: u8,
}

impl OperationMapper {
    /// Create a new mapper with QoS 1 default.
    pub fn new() -> Self {
        Self { default_qos: 1 }
    }

    /// Create a mapper with a specific default QoS.
    pub fn with_qos(qos: u8) -> Self {
        Self {
            default_qos: qos.min(2),
        }
    }

    /// Map a SAMM operation to a REST endpoint.
    ///
    /// Mapping logic:
    /// - Read-only operations (no input or only query params) → GET with query params
    /// - Write operations with input → POST with JSON body
    /// - The path is `/operations/{kebab-name}`
    pub fn map_to_rest(&self, op: &SammOperation) -> RestEndpoint {
        let path = format!("/operations/{}", to_kebab_case(&op.name));
        let response_schema = build_json_schema(&op.output_props);

        if op.input_props.is_empty() {
            // Pure read: GET with no params
            RestEndpoint {
                method: HttpMethod::Get,
                path,
                query_params: Vec::new(),
                body_schema: None,
                response_schema,
            }
        } else {
            // Check if all inputs can be expressed as simple query params
            // (no nested objects: only string/integer/boolean types)
            let all_simple = op.input_props.iter().all(|p| {
                matches!(
                    xsd_to_json_type(&p.data_type),
                    "string" | "integer" | "boolean"
                )
            });

            if all_simple && op.input_props.len() <= 5 {
                // Use GET with query parameters for simple inputs
                let query_params = op.input_props.iter().map(|p| p.name.clone()).collect();
                RestEndpoint {
                    method: HttpMethod::Get,
                    path,
                    query_params,
                    body_schema: None,
                    response_schema,
                }
            } else {
                // Use POST with a JSON body for complex / many inputs
                let body_schema = Some(build_json_schema(&op.input_props));
                RestEndpoint {
                    method: HttpMethod::Post,
                    path,
                    query_params: Vec::new(),
                    body_schema,
                    response_schema,
                }
            }
        }
    }

    /// Map a SAMM operation to an MQTT topic.
    ///
    /// - Request topic: `{base_topic}/{snake_name}/request`
    /// - Response topic: `{base_topic}/{snake_name}/response`
    ///
    /// The returned `MqttTopic` uses the request topic pattern and combines both
    /// schemas into a single payload schema for the message envelope.
    pub fn map_to_mqtt(&self, op: &SammOperation, base_topic: &str) -> MqttTopic {
        let snake = to_snake_case(&op.name);
        let base = base_topic.trim_end_matches('/');
        let topic_pattern = format!("{base}/{snake}/request");

        let input_schema = build_json_schema(&op.input_props);
        let output_schema = build_json_schema(&op.output_props);

        // Combine into an envelope schema
        let payload_schema = format!(
            r#"{{"type":"object","properties":{{"request":{input_schema},"response":{output_schema}}}}}"#
        );

        MqttTopic {
            topic_pattern,
            qos: self.default_qos,
            payload_schema,
        }
    }

    /// Generate an OpenAPI 3.0 YAML path fragment for a list of operations.
    ///
    /// The generated YAML contains only the `paths:` section and can be merged
    /// into a larger OpenAPI document.
    pub fn generate_openapi(&self, ops: &[SammOperation], base_url: &str) -> String {
        let mut yaml = format!(
            "openapi: \"3.0.3\"\ninfo:\n  title: SAMM API\n  version: \"1.0.0\"\nservers:\n  - url: \"{base_url}\"\npaths:\n"
        );

        for op in ops {
            let endpoint = self.map_to_rest(op);
            let path = &endpoint.path;
            let method = endpoint.method.to_string();

            yaml.push_str(&format!("  \"{path}\":\n"));
            yaml.push_str(&format!("    {method}:\n"));
            yaml.push_str(&format!(
                "      summary: \"Invoke {} operation\"\n",
                op.name
            ));
            yaml.push_str(&format!("      operationId: \"{}\"\n", op.name));

            if !endpoint.query_params.is_empty() {
                yaml.push_str("      parameters:\n");
                for qp in &endpoint.query_params {
                    let prop = op.input_props.iter().find(|p| p.name == *qp);
                    let json_type = prop
                        .map(|p| xsd_to_json_type(&p.data_type))
                        .unwrap_or("string");
                    let required = prop.map(|p| !p.optional).unwrap_or(true);
                    yaml.push_str(&format!(
                        "        - name: \"{qp}\"\n          in: query\n          required: {required}\n          schema:\n            type: \"{json_type}\"\n"
                    ));
                }
            }

            if let Some(body) = &endpoint.body_schema {
                yaml.push_str("      requestBody:\n");
                yaml.push_str("        required: true\n");
                yaml.push_str("        content:\n");
                yaml.push_str("          application/json:\n");
                yaml.push_str(&format!("            schema: {body}\n"));
            }

            yaml.push_str("      responses:\n");
            yaml.push_str("        '200':\n");
            yaml.push_str("          description: \"Successful response\"\n");
            yaml.push_str("          content:\n");
            yaml.push_str("            application/json:\n");
            yaml.push_str(&format!(
                "              schema: {}\n",
                endpoint.response_schema
            ));
        }

        yaml
    }

    /// Generate an AsyncAPI 2.x YAML fragment for a list of operations.
    ///
    /// Returns a document with an `asyncapi:` header, server info, and channels.
    pub fn generate_asyncapi(&self, ops: &[SammOperation], server: &str) -> String {
        let mut yaml = format!(
            "asyncapi: \"2.6.0\"\ninfo:\n  title: SAMM MQTT API\n  version: \"1.0.0\"\nservers:\n  production:\n    url: \"{server}\"\n    protocol: mqtt\nchannels:\n"
        );

        for op in ops {
            let mqtt = self.map_to_mqtt(op, "samm");
            let topic = &mqtt.topic_pattern;
            let qos = mqtt.qos;

            yaml.push_str(&format!("  \"{topic}\":\n"));
            yaml.push_str(&format!(
                "    description: \"Request channel for {} operation\"\n",
                op.name
            ));
            yaml.push_str("    publish:\n");
            yaml.push_str(&format!("      operationId: \"publish{}\"\n", op.name));
            yaml.push_str("      message:\n");
            yaml.push_str("        payload:\n");
            // Embed the payload schema inline (simplified)
            yaml.push_str("          type: object\n");
            yaml.push_str("    bindings:\n");
            yaml.push_str("      mqtt:\n");
            yaml.push_str(&format!("        qos: {qos}\n"));
        }

        yaml
    }

    /// Map a SAMM operation to both REST and MQTT.
    pub fn map_to_both(&self, op: &SammOperation, base_topic: &str) -> ApiMapping {
        let rest = self.map_to_rest(op);
        let mqtt = self.map_to_mqtt(op, base_topic);
        ApiMapping::Both(rest, mqtt)
    }
}

// ─── Tests ──────────────────────────────────────────────────────────────────

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

    fn mapper() -> OperationMapper {
        OperationMapper::new()
    }

    fn simple_op() -> SammOperation {
        SammOperation::new(
            "getTemperature",
            vec![PropertyRef::required("deviceId", "string")],
            vec![PropertyRef::required("temperature", "double")],
        )
    }

    fn write_op() -> SammOperation {
        SammOperation::new(
            "setConfiguration",
            vec![
                PropertyRef::required("key", "string"),
                PropertyRef::required("value", "string"),
                PropertyRef::optional("ttl", "integer"),
            ],
            vec![PropertyRef::required("success", "boolean")],
        )
    }

    fn no_input_op() -> SammOperation {
        SammOperation::new(
            "getStatus",
            vec![],
            vec![PropertyRef::required("status", "string")],
        )
    }

    // ── PropertyRef ──────────────────────────────────────────────────────────

    #[test]
    fn test_property_ref_required() {
        let p = PropertyRef::required("name", "string");
        assert!(!p.optional);
        assert_eq!(p.name, "name");
    }

    #[test]
    fn test_property_ref_optional() {
        let p = PropertyRef::optional("ttl", "integer");
        assert!(p.optional);
    }

    // ── HttpMethod ───────────────────────────────────────────────────────────

    #[test]
    fn test_http_method_display() {
        assert_eq!(HttpMethod::Get.to_string(), "get");
        assert_eq!(HttpMethod::Post.to_string(), "post");
        assert_eq!(HttpMethod::Put.to_string(), "put");
        assert_eq!(HttpMethod::Delete.to_string(), "delete");
        assert_eq!(HttpMethod::Patch.to_string(), "patch");
    }

    // ── REST mapping ─────────────────────────────────────────────────────────

    #[test]
    fn test_map_to_rest_get_with_query_param() {
        let op = simple_op();
        let ep = mapper().map_to_rest(&op);
        assert_eq!(ep.method, HttpMethod::Get);
        assert!(ep.path.contains("get-temperature"));
        assert!(ep.query_params.contains(&"deviceId".to_string()));
        assert!(ep.body_schema.is_none());
    }

    #[test]
    fn test_map_to_rest_no_input_is_get() {
        let op = no_input_op();
        let ep = mapper().map_to_rest(&op);
        assert_eq!(ep.method, HttpMethod::Get);
        assert!(ep.query_params.is_empty());
    }

    #[test]
    fn test_map_to_rest_many_inputs_is_post() {
        let op = SammOperation::new(
            "complexOp",
            (0..7)
                .map(|i| PropertyRef::required(format!("param{i}"), "string"))
                .collect(),
            vec![PropertyRef::required("result", "boolean")],
        );
        let ep = mapper().map_to_rest(&op);
        assert_eq!(ep.method, HttpMethod::Post);
        assert!(ep.body_schema.is_some());
    }

    #[test]
    fn test_map_to_rest_path_format() {
        let op = simple_op();
        let ep = mapper().map_to_rest(&op);
        assert!(ep.path.starts_with("/operations/"));
    }

    #[test]
    fn test_map_to_rest_response_schema_has_type() {
        let op = simple_op();
        let ep = mapper().map_to_rest(&op);
        assert!(ep.response_schema.contains("temperature"));
        assert!(ep.response_schema.contains("number"));
    }

    #[test]
    fn test_map_to_rest_body_schema_content() {
        let op = write_op();
        let ep = mapper().map_to_rest(&op);
        // write_op has 3 simple string/integer params but > 0 required
        // all_simple=true, len <= 5 → GET with query params
        // Actually setConfiguration has 3 params, all simple → GET
        // But wait: 3 params, all_simple=true, len<=5 → GET
        // Let's verify
        if ep.method == HttpMethod::Post {
            let body = ep.body_schema.as_ref().expect("body schema");
            assert!(body.contains("key"));
            assert!(body.contains("value"));
        } else {
            assert_eq!(ep.method, HttpMethod::Get);
            assert!(ep.query_params.contains(&"key".to_string()));
        }
    }

    #[test]
    fn test_map_to_rest_kebab_case_path() {
        let op = SammOperation::new("getMyData", vec![], vec![]);
        let ep = mapper().map_to_rest(&op);
        assert!(ep.path.contains("get-my-data"));
    }

    // ── MQTT mapping ─────────────────────────────────────────────────────────

    #[test]
    fn test_map_to_mqtt_topic_pattern() {
        let op = simple_op();
        let topic = mapper().map_to_mqtt(&op, "factory/device");
        assert!(topic.topic_pattern.starts_with("factory/device/"));
        assert!(topic.topic_pattern.ends_with("/request"));
    }

    #[test]
    fn test_map_to_mqtt_qos_default() {
        let op = simple_op();
        let topic = mapper().map_to_mqtt(&op, "base");
        assert_eq!(topic.qos, 1);
    }

    #[test]
    fn test_map_to_mqtt_qos_custom() {
        let m = OperationMapper::with_qos(2);
        let op = simple_op();
        let topic = m.map_to_mqtt(&op, "base");
        assert_eq!(topic.qos, 2);
    }

    #[test]
    fn test_map_to_mqtt_qos_capped() {
        let m = OperationMapper::with_qos(5);
        let op = simple_op();
        let topic = m.map_to_mqtt(&op, "base");
        assert!(topic.qos <= 2);
    }

    #[test]
    fn test_map_to_mqtt_payload_schema() {
        let op = simple_op();
        let topic = mapper().map_to_mqtt(&op, "base");
        assert!(topic.payload_schema.contains("request"));
        assert!(topic.payload_schema.contains("response"));
    }

    #[test]
    fn test_map_to_mqtt_snake_case_topic() {
        let op = SammOperation::new("getTemperature", vec![], vec![]);
        let topic = mapper().map_to_mqtt(&op, "base");
        assert!(topic.topic_pattern.contains("get_temperature"));
    }

    #[test]
    fn test_map_to_mqtt_base_topic_trailing_slash() {
        let op = simple_op();
        let topic = mapper().map_to_mqtt(&op, "factory/");
        // Should not double the slash
        assert!(!topic.topic_pattern.contains("//"));
    }

    // ── OpenAPI generation ────────────────────────────────────────────────────

    #[test]
    fn test_generate_openapi_contains_openapi_version() {
        let ops = vec![simple_op()];
        let yaml = mapper().generate_openapi(&ops, "https://api.example.org");
        assert!(yaml.contains("openapi:"));
        assert!(yaml.contains("3.0.3"));
    }

    #[test]
    fn test_generate_openapi_contains_path() {
        let ops = vec![simple_op()];
        let yaml = mapper().generate_openapi(&ops, "https://api.example.org");
        assert!(yaml.contains("get-temperature"));
    }

    #[test]
    fn test_generate_openapi_contains_operation_id() {
        let ops = vec![simple_op()];
        let yaml = mapper().generate_openapi(&ops, "https://api.example.org");
        assert!(yaml.contains("getTemperature"));
    }

    #[test]
    fn test_generate_openapi_contains_base_url() {
        let ops = vec![simple_op()];
        let yaml = mapper().generate_openapi(&ops, "https://api.example.org");
        assert!(yaml.contains("https://api.example.org"));
    }

    #[test]
    fn test_generate_openapi_multiple_ops() {
        let ops = vec![simple_op(), no_input_op()];
        let yaml = mapper().generate_openapi(&ops, "https://api.example.org");
        assert!(yaml.contains("get-temperature"));
        assert!(yaml.contains("get-status"));
    }

    #[test]
    fn test_generate_openapi_200_response() {
        let ops = vec![simple_op()];
        let yaml = mapper().generate_openapi(&ops, "https://api.example.org");
        assert!(yaml.contains("'200'"));
    }

    #[test]
    fn test_generate_openapi_query_parameter() {
        let ops = vec![simple_op()];
        let yaml = mapper().generate_openapi(&ops, "https://api.example.org");
        // simple_op has deviceId as GET query param
        assert!(yaml.contains("deviceId"));
        assert!(yaml.contains("in: query"));
    }

    // ── AsyncAPI generation ────────────────────────────────────────────────────

    #[test]
    fn test_generate_asyncapi_contains_version() {
        let ops = vec![simple_op()];
        let yaml = mapper().generate_asyncapi(&ops, "mqtt://broker.example.org:1883");
        assert!(yaml.contains("asyncapi:"));
        assert!(yaml.contains("2.6.0"));
    }

    #[test]
    fn test_generate_asyncapi_contains_server() {
        let ops = vec![simple_op()];
        let yaml = mapper().generate_asyncapi(&ops, "mqtt://broker.example.org:1883");
        assert!(yaml.contains("mqtt://broker.example.org:1883"));
    }

    #[test]
    fn test_generate_asyncapi_contains_channel() {
        let ops = vec![simple_op()];
        let yaml = mapper().generate_asyncapi(&ops, "mqtt://broker.example.org:1883");
        assert!(yaml.contains("get_temperature"));
        assert!(yaml.contains("request"));
    }

    #[test]
    fn test_generate_asyncapi_qos() {
        let ops = vec![simple_op()];
        let yaml = mapper().generate_asyncapi(&ops, "mqtt://broker.example.org:1883");
        assert!(yaml.contains("qos:"));
    }

    // ── Combined mapping ──────────────────────────────────────────────────────

    #[test]
    fn test_map_to_both() {
        let op = simple_op();
        let mapping = mapper().map_to_both(&op, "factory");
        assert!(matches!(mapping, ApiMapping::Both(_, _)));
    }

    // ── JSON schema helpers ───────────────────────────────────────────────────

    #[test]
    fn test_json_schema_empty_props() {
        let schema = build_json_schema(&[]);
        assert!(schema.contains("object"));
        assert!(schema.contains("properties"));
    }

    #[test]
    fn test_json_schema_required_field() {
        let props = vec![PropertyRef::required("name", "string")];
        let schema = build_json_schema(&props);
        assert!(schema.contains("required"));
        assert!(schema.contains("name"));
    }

    #[test]
    fn test_json_schema_optional_not_in_required() {
        let props = vec![PropertyRef::optional("ttl", "integer")];
        let schema = build_json_schema(&props);
        // optional prop should not appear in required array
        assert!(!schema.contains("\"required\""));
    }

    #[test]
    fn test_xsd_to_json_type_string() {
        assert_eq!(xsd_to_json_type("string"), "string");
        assert_eq!(xsd_to_json_type("xsd:string"), "string");
    }

    #[test]
    fn test_xsd_to_json_type_integer() {
        assert_eq!(xsd_to_json_type("integer"), "integer");
        assert_eq!(xsd_to_json_type("int"), "integer");
    }

    #[test]
    fn test_xsd_to_json_type_double() {
        assert_eq!(xsd_to_json_type("double"), "number");
        assert_eq!(xsd_to_json_type("float"), "number");
        assert_eq!(xsd_to_json_type("decimal"), "number");
    }

    #[test]
    fn test_xsd_to_json_type_boolean() {
        assert_eq!(xsd_to_json_type("boolean"), "boolean");
    }

    #[test]
    fn test_xsd_to_json_type_unknown() {
        assert_eq!(xsd_to_json_type("myCustomType"), "string");
    }

    #[test]
    fn test_to_kebab_case() {
        assert_eq!(to_kebab_case("getTemperature"), "get-temperature");
        assert_eq!(to_kebab_case("setMyValue"), "set-my-value");
        assert_eq!(to_kebab_case("simple"), "simple");
    }

    #[test]
    fn test_to_snake_case() {
        assert_eq!(to_snake_case("getTemperature"), "get_temperature");
        assert_eq!(to_snake_case("setMyValue"), "set_my_value");
    }

    #[test]
    fn test_samm_operation_new() {
        let op = SammOperation::new("myOp", vec![], vec![]);
        assert_eq!(op.name, "myOp");
        assert!(op.input_props.is_empty());
        assert!(op.output_props.is_empty());
    }
}