elif-openapi 0.2.1

OpenAPI 3.0 specification generation for elif.rs framework
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
/*!
Utility functions for OpenAPI generation.
*/

use crate::{
    error::{OpenApiError, OpenApiResult},
    specification::OpenApiSpec,
};
use std::fs;
use std::path::Path;

/// Utility functions for OpenAPI operations
pub struct OpenApiUtils;

impl OpenApiUtils {
    /// Validate an OpenAPI specification
    pub fn validate_spec(spec: &OpenApiSpec) -> OpenApiResult<Vec<ValidationWarning>> {
        let mut warnings = Vec::new();

        // Check required fields
        if spec.info.title.is_empty() {
            warnings.push(ValidationWarning::new(
                "info.title is required but empty",
                ValidationLevel::Error,
            ));
        }

        if spec.info.version.is_empty() {
            warnings.push(ValidationWarning::new(
                "info.version is required but empty",
                ValidationLevel::Error,
            ));
        }

        // Check OpenAPI version
        if spec.openapi != "3.0.3" && !spec.openapi.starts_with("3.0") {
            warnings.push(ValidationWarning::new(
                &format!(
                    "OpenAPI version {} may not be fully supported",
                    spec.openapi
                ),
                ValidationLevel::Warning,
            ));
        }

        // Check paths
        if spec.paths.is_empty() {
            warnings.push(ValidationWarning::new(
                "No paths defined in specification",
                ValidationLevel::Warning,
            ));
        }

        // Validate path operations
        for (path, path_item) in &spec.paths {
            if !path.starts_with('/') {
                warnings.push(ValidationWarning::new(
                    &format!("Path '{}' should start with '/'", path),
                    ValidationLevel::Warning,
                ));
            }

            // Check if path has at least one operation
            let has_operations = path_item.get.is_some()
                || path_item.post.is_some()
                || path_item.put.is_some()
                || path_item.delete.is_some()
                || path_item.patch.is_some()
                || path_item.options.is_some()
                || path_item.head.is_some()
                || path_item.trace.is_some();

            if !has_operations {
                warnings.push(ValidationWarning::new(
                    &format!("Path '{}' has no operations defined", path),
                    ValidationLevel::Warning,
                ));
            }

            // Validate operations
            let operations = vec![
                ("GET", &path_item.get),
                ("POST", &path_item.post),
                ("PUT", &path_item.put),
                ("DELETE", &path_item.delete),
                ("PATCH", &path_item.patch),
                ("OPTIONS", &path_item.options),
                ("HEAD", &path_item.head),
                ("TRACE", &path_item.trace),
            ];

            for (method, operation) in operations {
                if let Some(op) = operation {
                    if op.responses.is_empty() {
                        warnings.push(ValidationWarning::new(
                            &format!("{} {} has no responses defined", method, path),
                            ValidationLevel::Error,
                        ));
                    }

                    // Check for operation ID uniqueness would require global tracking
                    if let Some(op_id) = &op.operation_id {
                        if op_id.is_empty() {
                            warnings.push(ValidationWarning::new(
                                &format!("{} {} has empty operationId", method, path),
                                ValidationLevel::Warning,
                            ));
                        }
                    }
                }
            }
        }

        // Validate components
        if let Some(components) = &spec.components {
            // Check for unused schemas
            for schema_name in components.schemas.keys() {
                let reference = format!("#/components/schemas/{}", schema_name);
                let is_used = Self::is_schema_referenced(spec, &reference);
                if !is_used {
                    warnings.push(ValidationWarning::new(
                        &format!("Schema '{}' is defined but never referenced", schema_name),
                        ValidationLevel::Info,
                    ));
                }
            }
        }

        Ok(warnings)
    }

    /// Check if a schema is referenced anywhere in the spec using proper recursive traversal
    fn is_schema_referenced(spec: &OpenApiSpec, reference: &str) -> bool {
        // Check in paths and operations
        for path_item in spec.paths.values() {
            if Self::is_schema_in_path_item(path_item, reference) {
                return true;
            }
        }

        // Check in components
        if let Some(components) = &spec.components {
            // Check in schema definitions themselves (for nested references)
            for schema in components.schemas.values() {
                if Self::is_schema_in_schema(schema, reference) {
                    return true;
                }
            }

            // Check in responses
            for response in components.responses.values() {
                if Self::is_schema_in_response(response, reference) {
                    return true;
                }
            }

            // Check in request bodies
            for request_body in components.request_bodies.values() {
                if Self::is_schema_in_request_body(request_body, reference) {
                    return true;
                }
            }

            // Check in parameters
            for parameter in components.parameters.values() {
                if Self::is_schema_in_parameter(parameter, reference) {
                    return true;
                }
            }

            // Check in headers
            for header in components.headers.values() {
                if Self::is_schema_in_header(header, reference) {
                    return true;
                }
            }
        }

        false
    }

    /// Check if schema is referenced in a path item
    fn is_schema_in_path_item(path_item: &crate::specification::PathItem, reference: &str) -> bool {
        let operations = vec![
            &path_item.get,
            &path_item.post,
            &path_item.put,
            &path_item.delete,
            &path_item.patch,
            &path_item.options,
            &path_item.head,
            &path_item.trace,
        ];

        for operation in operations.into_iter().flatten() {
            if Self::is_schema_in_operation(operation, reference) {
                return true;
            }
        }

        // Check path-level parameters
        for parameter in &path_item.parameters {
            if Self::is_schema_in_parameter(parameter, reference) {
                return true;
            }
        }

        false
    }

    /// Check if schema is referenced in an operation
    fn is_schema_in_operation(
        operation: &crate::specification::Operation,
        reference: &str,
    ) -> bool {
        // Check parameters
        for parameter in &operation.parameters {
            if Self::is_schema_in_parameter(parameter, reference) {
                return true;
            }
        }

        // Check request body
        if let Some(request_body) = &operation.request_body {
            if Self::is_schema_in_request_body(request_body, reference) {
                return true;
            }
        }

        // Check responses
        for response in operation.responses.values() {
            if Self::is_schema_in_response(response, reference) {
                return true;
            }
        }

        false
    }

    /// Check if schema is referenced in a parameter
    fn is_schema_in_parameter(
        parameter: &crate::specification::Parameter,
        reference: &str,
    ) -> bool {
        if let Some(schema) = &parameter.schema {
            Self::is_schema_in_schema(schema, reference)
        } else {
            false
        }
    }

    /// Check if schema is referenced in a request body
    fn is_schema_in_request_body(
        request_body: &crate::specification::RequestBody,
        reference: &str,
    ) -> bool {
        for media_type in request_body.content.values() {
            if let Some(schema) = &media_type.schema {
                if Self::is_schema_in_schema(schema, reference) {
                    return true;
                }
            }
        }
        false
    }

    /// Check if schema is referenced in a response
    fn is_schema_in_response(response: &crate::specification::Response, reference: &str) -> bool {
        // Check response content
        for media_type in response.content.values() {
            if let Some(schema) = &media_type.schema {
                if Self::is_schema_in_schema(schema, reference) {
                    return true;
                }
            }
        }

        // Check response headers
        for header in response.headers.values() {
            if Self::is_schema_in_header(header, reference) {
                return true;
            }
        }

        false
    }

    /// Check if schema is referenced in a header
    fn is_schema_in_header(header: &crate::specification::Header, reference: &str) -> bool {
        if let Some(schema) = &header.schema {
            Self::is_schema_in_schema(schema, reference)
        } else {
            false
        }
    }

    /// Check if schema is referenced within another schema (recursive)
    fn is_schema_in_schema(schema: &crate::specification::Schema, reference: &str) -> bool {
        // Check direct reference
        if let Some(ref_str) = &schema.reference {
            if ref_str == reference {
                return true;
            }
        }

        // Check properties (for object schemas)
        for property_schema in schema.properties.values() {
            if Self::is_schema_in_schema(property_schema, reference) {
                return true;
            }
        }

        // Check additional properties
        if let Some(additional_properties) = &schema.additional_properties {
            if Self::is_schema_in_schema(additional_properties, reference) {
                return true;
            }
        }

        // Check items (for array schemas)
        if let Some(items_schema) = &schema.items {
            if Self::is_schema_in_schema(items_schema, reference) {
                return true;
            }
        }

        // Check composition schemas (allOf, anyOf, oneOf)
        for composed_schema in &schema.all_of {
            if Self::is_schema_in_schema(composed_schema, reference) {
                return true;
            }
        }

        for composed_schema in &schema.any_of {
            if Self::is_schema_in_schema(composed_schema, reference) {
                return true;
            }
        }

        for composed_schema in &schema.one_of {
            if Self::is_schema_in_schema(composed_schema, reference) {
                return true;
            }
        }

        false
    }

    /// Save OpenAPI specification to file
    pub fn save_spec_to_file<P: AsRef<Path>>(
        spec: &OpenApiSpec,
        path: P,
        format: OutputFormat,
        pretty: bool,
    ) -> OpenApiResult<()> {
        let content = match format {
            OutputFormat::Json => {
                if pretty {
                    serde_json::to_string_pretty(spec)?
                } else {
                    serde_json::to_string(spec)?
                }
            }
            OutputFormat::Yaml => serde_yaml::to_string(spec)?,
        };

        fs::write(path.as_ref(), content).map_err(OpenApiError::Io)?;

        Ok(())
    }

    /// Load OpenAPI specification from file
    pub fn load_spec_from_file<P: AsRef<Path>>(path: P) -> OpenApiResult<OpenApiSpec> {
        let content = fs::read_to_string(path.as_ref()).map_err(OpenApiError::Io)?;

        let extension = path
            .as_ref()
            .extension()
            .and_then(|ext| ext.to_str())
            .unwrap_or("");

        match extension.to_lowercase().as_str() {
            "json" => serde_json::from_str(&content).map_err(OpenApiError::from),
            "yaml" | "yml" => serde_yaml::from_str(&content).map_err(OpenApiError::from),
            _ => {
                // Try to detect format from content
                if content.trim_start().starts_with('{') {
                    serde_json::from_str(&content).map_err(OpenApiError::from)
                } else {
                    serde_yaml::from_str(&content).map_err(OpenApiError::from)
                }
            }
        }
    }

    /// Merge two OpenAPI specifications
    pub fn merge_specs(base: &mut OpenApiSpec, other: &OpenApiSpec) -> OpenApiResult<()> {
        // Merge paths
        for (path, path_item) in &other.paths {
            if base.paths.contains_key(path) {
                return Err(OpenApiError::validation_error(format!(
                    "Path '{}' already exists in base specification",
                    path
                )));
            }
            base.paths.insert(path.clone(), path_item.clone());
        }

        // Merge components
        if let Some(other_components) = &other.components {
            let base_components = base.components.get_or_insert_with(Default::default);

            // Merge schemas
            for (name, schema) in &other_components.schemas {
                if base_components.schemas.contains_key(name) {
                    return Err(OpenApiError::validation_error(format!(
                        "Schema '{}' already exists in base specification",
                        name
                    )));
                }
                base_components.schemas.insert(name.clone(), schema.clone());
            }

            // Merge other components...
            for (name, response) in &other_components.responses {
                base_components
                    .responses
                    .insert(name.clone(), response.clone());
            }
        }

        // Merge tags
        for tag in &other.tags {
            if !base.tags.iter().any(|t| t.name == tag.name) {
                base.tags.push(tag.clone());
            }
        }

        Ok(())
    }

    /// Generate example request/response from schema
    pub fn generate_example_from_schema(
        schema: &crate::specification::Schema,
    ) -> OpenApiResult<serde_json::Value> {
        use serde_json::{Map, Value};

        match schema.schema_type.as_deref() {
            Some("object") => {
                let mut obj = Map::new();
                for (prop_name, prop_schema) in &schema.properties {
                    let example = Self::generate_example_from_schema(prop_schema)?;
                    obj.insert(prop_name.clone(), example);
                }
                Ok(Value::Object(obj))
            }
            Some("array") => {
                if let Some(items_schema) = &schema.items {
                    let item_example = Self::generate_example_from_schema(items_schema)?;
                    Ok(Value::Array(vec![item_example]))
                } else {
                    Ok(Value::Array(vec![]))
                }
            }
            Some("string") => {
                if !schema.enum_values.is_empty() {
                    Ok(schema.enum_values[0].clone())
                } else {
                    match schema.format.as_deref() {
                        Some("email") => Ok(Value::String("user@example.com".to_string())),
                        Some("uri") => Ok(Value::String("https://example.com".to_string())),
                        Some("date") => Ok(Value::String("2023-12-01".to_string())),
                        Some("date-time") => Ok(Value::String("2023-12-01T12:00:00Z".to_string())),
                        Some("uuid") => Ok(Value::String(
                            "123e4567-e89b-12d3-a456-426614174000".to_string(),
                        )),
                        _ => Ok(Value::String("string".to_string())),
                    }
                }
            }
            Some("integer") => match schema.format.as_deref() {
                Some("int64") => Ok(Value::Number(serde_json::Number::from(42i64))),
                _ => Ok(Value::Number(serde_json::Number::from(42i32))),
            },
            Some("number") => Ok(Value::Number(
                serde_json::Number::from_f64(std::f64::consts::PI).unwrap(),
            )),
            Some("boolean") => Ok(Value::Bool(true)),
            _ => {
                if let Some(example) = &schema.example {
                    Ok(example.clone())
                } else {
                    Ok(Value::Null)
                }
            }
        }
    }

    /// Extract operation summary from function name
    pub fn generate_operation_summary(method: &str, path: &str) -> String {
        let verb = method.to_lowercase();
        let resource = Self::extract_resource_from_path(path);

        match verb.as_str() {
            "get" => {
                if path.contains('{') {
                    format!("Get {}", resource)
                } else {
                    format!("List {}", Self::pluralize(&resource))
                }
            }
            "post" => format!("Create {}", resource),
            "put" => format!("Update {}", resource),
            "patch" => format!("Partially update {}", resource),
            "delete" => format!("Delete {}", resource),
            _ => format!("{} {}", verb, resource),
        }
    }

    /// Extract resource name from path
    fn extract_resource_from_path(path: &str) -> String {
        let parts: Vec<&str> = path.split('/').filter(|p| !p.is_empty()).collect();

        if let Some(last_part) = parts.last() {
            if last_part.starts_with('{') {
                // Path parameter, use previous part
                if parts.len() > 1 {
                    Self::singularize(parts[parts.len() - 2])
                } else {
                    "resource".to_string()
                }
            } else {
                Self::singularize(last_part)
            }
        } else {
            "resource".to_string()
        }
    }

    /// Simple singularization
    fn singularize(word: &str) -> String {
        if word.ends_with("ies") {
            word.trim_end_matches("ies").to_string() + "y"
        } else if word.ends_with('s') && !word.ends_with("ss") {
            word.trim_end_matches('s').to_string()
        } else {
            word.to_string()
        }
    }

    /// Simple pluralization
    fn pluralize(word: &str) -> String {
        if word.ends_with('y') {
            word.trim_end_matches('y').to_string() + "ies"
        } else if word.ends_with("s") || word.ends_with("sh") || word.ends_with("ch") {
            word.to_string() + "es"
        } else {
            word.to_string() + "s"
        }
    }
}

/// Output format for saving specifications
#[derive(Debug, Clone)]
pub enum OutputFormat {
    Json,
    Yaml,
}

/// Validation warning levels
#[derive(Debug, Clone, PartialEq)]
pub enum ValidationLevel {
    Error,
    Warning,
    Info,
}

/// Validation warning
#[derive(Debug, Clone)]
pub struct ValidationWarning {
    pub message: String,
    pub level: ValidationLevel,
}

impl ValidationWarning {
    pub fn new(message: &str, level: ValidationLevel) -> Self {
        Self {
            message: message.to_string(),
            level,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::specification::Schema;
    use std::collections::HashMap;

    #[test]
    fn test_operation_summary_generation() {
        assert_eq!(
            OpenApiUtils::generate_operation_summary("GET", "/users"),
            "List users"
        );
        assert_eq!(
            OpenApiUtils::generate_operation_summary("GET", "/users/{id}"),
            "Get user"
        );
        assert_eq!(
            OpenApiUtils::generate_operation_summary("POST", "/users"),
            "Create user"
        );
        assert_eq!(
            OpenApiUtils::generate_operation_summary("PUT", "/users/{id}"),
            "Update user"
        );
        assert_eq!(
            OpenApiUtils::generate_operation_summary("DELETE", "/users/{id}"),
            "Delete user"
        );
    }

    #[test]
    fn test_resource_extraction() {
        assert_eq!(OpenApiUtils::extract_resource_from_path("/users"), "user");
        assert_eq!(
            OpenApiUtils::extract_resource_from_path("/users/{id}"),
            "user"
        );
        assert_eq!(
            OpenApiUtils::extract_resource_from_path("/api/v1/posts/{id}/comments"),
            "comment"
        );
        assert_eq!(OpenApiUtils::extract_resource_from_path("/"), "resource");
    }

    #[test]
    fn test_singularization() {
        assert_eq!(OpenApiUtils::singularize("users"), "user");
        assert_eq!(OpenApiUtils::singularize("posts"), "post");
        assert_eq!(OpenApiUtils::singularize("categories"), "category");
        assert_eq!(OpenApiUtils::singularize("companies"), "company");
        assert_eq!(OpenApiUtils::singularize("class"), "class"); // shouldn't change
    }

    #[test]
    fn test_pluralization() {
        assert_eq!(OpenApiUtils::pluralize("user"), "users");
        assert_eq!(OpenApiUtils::pluralize("post"), "posts");
        assert_eq!(OpenApiUtils::pluralize("category"), "categories");
        assert_eq!(OpenApiUtils::pluralize("company"), "companies");
        assert_eq!(OpenApiUtils::pluralize("class"), "classes");
    }

    #[test]
    fn test_example_generation() {
        let string_schema = Schema {
            schema_type: Some("string".to_string()),
            ..Default::default()
        };
        let example = OpenApiUtils::generate_example_from_schema(&string_schema).unwrap();
        assert_eq!(example, serde_json::Value::String("string".to_string()));

        let integer_schema = Schema {
            schema_type: Some("integer".to_string()),
            ..Default::default()
        };
        let example = OpenApiUtils::generate_example_from_schema(&integer_schema).unwrap();
        assert_eq!(
            example,
            serde_json::Value::Number(serde_json::Number::from(42))
        );
    }

    #[test]
    fn test_spec_validation() {
        let mut spec = OpenApiSpec::new("Test API", "1.0.0");
        spec.paths = HashMap::new();

        let warnings = OpenApiUtils::validate_spec(&spec).unwrap();

        // Should have warning about no paths
        assert!(warnings
            .iter()
            .any(|w| w.message.contains("No paths defined")));
    }

    #[test]
    fn test_schema_reference_detection_accurate() {
        use crate::specification::*;

        // Create a spec with schemas and verify accurate detection
        let mut spec = OpenApiSpec::new("Test API", "1.0.0");

        // Add a User schema
        let user_schema = Schema {
            schema_type: Some("object".to_string()),
            properties: {
                let mut props = HashMap::new();
                props.insert(
                    "id".to_string(),
                    Schema {
                        schema_type: Some("integer".to_string()),
                        ..Default::default()
                    },
                );
                props.insert(
                    "name".to_string(),
                    Schema {
                        schema_type: Some("string".to_string()),
                        ..Default::default()
                    },
                );
                props
            },
            required: vec!["id".to_string(), "name".to_string()],
            ..Default::default()
        };

        // Add an Address schema that references User
        let address_schema = Schema {
            schema_type: Some("object".to_string()),
            properties: {
                let mut props = HashMap::new();
                props.insert(
                    "street".to_string(),
                    Schema {
                        schema_type: Some("string".to_string()),
                        ..Default::default()
                    },
                );
                props.insert(
                    "owner".to_string(),
                    Schema {
                        reference: Some("#/components/schemas/User".to_string()),
                        ..Default::default()
                    },
                );
                props
            },
            ..Default::default()
        };

        // Add an unused schema for testing
        let unused_schema = Schema {
            schema_type: Some("object".to_string()),
            properties: {
                let mut props = HashMap::new();
                props.insert(
                    "value".to_string(),
                    Schema {
                        schema_type: Some("string".to_string()),
                        ..Default::default()
                    },
                );
                props
            },
            ..Default::default()
        };

        // Set up components
        let mut components = Components::default();
        components.schemas.insert("User".to_string(), user_schema);
        components
            .schemas
            .insert("Address".to_string(), address_schema);
        components
            .schemas
            .insert("UnusedSchema".to_string(), unused_schema);
        spec.components = Some(components);

        // Test reference detection
        assert!(OpenApiUtils::is_schema_referenced(
            &spec,
            "#/components/schemas/User"
        ));
        assert!(!OpenApiUtils::is_schema_referenced(
            &spec,
            "#/components/schemas/UnusedSchema"
        ));
        assert!(!OpenApiUtils::is_schema_referenced(
            &spec,
            "#/components/schemas/NonExistent"
        ));
    }

    #[test]
    fn test_schema_reference_false_positive_prevention() {
        use crate::specification::*;

        // Create a spec where schema reference appears in description but not as actual reference
        let mut spec = OpenApiSpec::new("Test API", "1.0.0");

        // Add a schema with reference string in description (should NOT be detected as reference)
        let user_schema = Schema {
            schema_type: Some("object".to_string()),
            description: Some(
                "This schema represents a user. See also #/components/schemas/User for details."
                    .to_string(),
            ),
            properties: {
                let mut props = HashMap::new();
                props.insert(
                    "name".to_string(),
                    Schema {
                        schema_type: Some("string".to_string()),
                        ..Default::default()
                    },
                );
                props
            },
            ..Default::default()
        };

        // Add an example with schema reference in the example value
        let example_schema = Schema {
            schema_type: Some("string".to_string()),
            example: Some(serde_json::Value::String(
                "#/components/schemas/User".to_string(),
            )),
            ..Default::default()
        };

        let mut components = Components::default();
        components.schemas.insert("User".to_string(), user_schema);
        components
            .schemas
            .insert("Example".to_string(), example_schema);
        spec.components = Some(components);

        // The old string-based approach would incorrectly detect these as references
        // The new approach should correctly identify that User is not actually referenced
        assert!(!OpenApiUtils::is_schema_referenced(
            &spec,
            "#/components/schemas/User"
        ));
        assert!(!OpenApiUtils::is_schema_referenced(
            &spec,
            "#/components/schemas/Example"
        ));
    }

    #[test]
    fn test_schema_reference_in_operations() {
        use crate::specification::*;

        let mut spec = OpenApiSpec::new("Test API", "1.0.0");

        // Create a schema
        let user_schema = Schema {
            schema_type: Some("object".to_string()),
            ..Default::default()
        };

        // Create an operation that uses the schema in request body
        let request_body = RequestBody {
            description: Some("User data".to_string()),
            content: {
                let mut content = HashMap::new();
                content.insert(
                    "application/json".to_string(),
                    MediaType {
                        schema: Some(Schema {
                            reference: Some("#/components/schemas/User".to_string()),
                            ..Default::default()
                        }),
                        example: None,
                        examples: HashMap::new(),
                    },
                );
                content
            },
            required: Some(true),
        };

        let operation = Operation {
            request_body: Some(request_body),
            responses: {
                let mut responses = HashMap::new();
                responses.insert(
                    "200".to_string(),
                    Response {
                        description: "Success".to_string(),
                        content: {
                            let mut content = HashMap::new();
                            content.insert(
                                "application/json".to_string(),
                                MediaType {
                                    schema: Some(Schema {
                                        reference: Some("#/components/schemas/User".to_string()),
                                        ..Default::default()
                                    }),
                                    example: None,
                                    examples: HashMap::new(),
                                },
                            );
                            content
                        },
                        headers: HashMap::new(),
                        links: HashMap::new(),
                    },
                );
                responses
            },
            ..Default::default()
        };

        let path_item = PathItem {
            post: Some(operation),
            ..Default::default()
        };

        spec.paths.insert("/users".to_string(), path_item);

        let mut components = Components::default();
        components.schemas.insert("User".to_string(), user_schema);
        spec.components = Some(components);

        // User schema should be detected as referenced in the operation
        assert!(OpenApiUtils::is_schema_referenced(
            &spec,
            "#/components/schemas/User"
        ));
    }

    #[test]
    fn test_schema_reference_in_nested_schemas() {
        use crate::specification::*;

        let mut spec = OpenApiSpec::new("Test API", "1.0.0");

        // Create deeply nested schema structure
        let user_schema = Schema {
            schema_type: Some("object".to_string()),
            ..Default::default()
        };

        let profile_schema = Schema {
            schema_type: Some("object".to_string()),
            properties: {
                let mut props = HashMap::new();
                props.insert(
                    "user".to_string(),
                    Schema {
                        reference: Some("#/components/schemas/User".to_string()),
                        ..Default::default()
                    },
                );
                props
            },
            ..Default::default()
        };

        let response_schema = Schema {
            schema_type: Some("object".to_string()),
            properties: {
                let mut props = HashMap::new();
                props.insert(
                    "data".to_string(),
                    Schema {
                        schema_type: Some("array".to_string()),
                        items: Some(Box::new(Schema {
                            reference: Some("#/components/schemas/Profile".to_string()),
                            ..Default::default()
                        })),
                        ..Default::default()
                    },
                );
                props
            },
            ..Default::default()
        };

        let mut components = Components::default();
        components.schemas.insert("User".to_string(), user_schema);
        components
            .schemas
            .insert("Profile".to_string(), profile_schema);
        components
            .schemas
            .insert("Response".to_string(), response_schema);
        spec.components = Some(components);

        // Both User and Profile should be detected as referenced
        assert!(OpenApiUtils::is_schema_referenced(
            &spec,
            "#/components/schemas/User"
        ));
        assert!(OpenApiUtils::is_schema_referenced(
            &spec,
            "#/components/schemas/Profile"
        ));
    }

    #[test]
    fn test_schema_reference_in_composition() {
        use crate::specification::*;

        let mut spec = OpenApiSpec::new("Test API", "1.0.0");

        let base_schema = Schema {
            schema_type: Some("object".to_string()),
            ..Default::default()
        };

        let extended_schema = Schema {
            all_of: vec![
                Schema {
                    reference: Some("#/components/schemas/Base".to_string()),
                    ..Default::default()
                },
                Schema {
                    schema_type: Some("object".to_string()),
                    properties: {
                        let mut props = HashMap::new();
                        props.insert(
                            "extra".to_string(),
                            Schema {
                                schema_type: Some("string".to_string()),
                                ..Default::default()
                            },
                        );
                        props
                    },
                    ..Default::default()
                },
            ],
            ..Default::default()
        };

        let mut components = Components::default();
        components.schemas.insert("Base".to_string(), base_schema);
        components
            .schemas
            .insert("Extended".to_string(), extended_schema);
        spec.components = Some(components);

        // Base schema should be detected as referenced in allOf composition
        assert!(OpenApiUtils::is_schema_referenced(
            &spec,
            "#/components/schemas/Base"
        ));
    }
}