vika-cli 1.4.0

Generate TypeScript types, Zod schemas, and Fetch-based API clients from OpenAPI/Swagger specifications
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
use crate::error::Result;
use crate::generator::swagger_parser::{get_schema_name_from_ref, resolve_ref};
use crate::generator::utils::{sanitize_property_name, to_pascal_case};
use crate::templates::context::{Field, TypeContext};
use crate::templates::engine::TemplateEngine;
use crate::templates::registry::TemplateId;
use openapiv3::{OpenAPI, ReferenceOr, Schema, SchemaKind, Type};
use std::collections::HashMap;

#[derive(Clone)]
pub struct TypeScriptType {
    pub content: String,
}

pub fn generate_typings(
    openapi: &OpenAPI,
    schemas: &HashMap<String, Schema>,
    schema_names: &[String],
) -> Result<Vec<TypeScriptType>> {
    generate_typings_with_registry(
        openapi,
        schemas,
        schema_names,
        &mut std::collections::HashMap::new(),
        &[],
    )
}

pub fn generate_typings_with_registry(
    openapi: &OpenAPI,
    schemas: &HashMap<String, Schema>,
    schema_names: &[String],
    enum_registry: &mut std::collections::HashMap<String, String>,
    common_schemas: &[String],
) -> Result<Vec<TypeScriptType>> {
    generate_typings_with_registry_and_engine(
        openapi,
        schemas,
        schema_names,
        enum_registry,
        common_schemas,
        None,
    )
}

pub fn generate_typings_with_registry_and_engine(
    openapi: &OpenAPI,
    schemas: &HashMap<String, Schema>,
    schema_names: &[String],
    enum_registry: &mut std::collections::HashMap<String, String>,
    common_schemas: &[String],
    template_engine: Option<&TemplateEngine>,
) -> Result<Vec<TypeScriptType>> {
    generate_typings_with_registry_and_engine_and_spec(
        openapi,
        schemas,
        schema_names,
        enum_registry,
        common_schemas,
        template_engine,
        None,
    )
}

pub fn generate_typings_with_registry_and_engine_and_spec(
    openapi: &OpenAPI,
    schemas: &HashMap<String, Schema>,
    schema_names: &[String],
    enum_registry: &mut std::collections::HashMap<String, String>,
    common_schemas: &[String],
    template_engine: Option<&TemplateEngine>,
    spec_name: Option<&str>,
) -> Result<Vec<TypeScriptType>> {
    let mut types = Vec::new();
    let mut processed = std::collections::HashSet::new();

    for schema_name in schema_names {
        if let Some(schema) = schemas.get(schema_name) {
            generate_type_for_schema(
                openapi,
                schema_name,
                schema,
                &mut types,
                &mut processed,
                enum_registry,
                None,
                common_schemas,
                template_engine,
                spec_name,
            )?;
        }
    }

    Ok(types)
}

#[allow(dead_code)]
pub fn organize_types_by_module(
    types: Vec<TypeScriptType>,
    module_schemas: &std::collections::HashMap<String, Vec<String>>,
) -> std::collections::HashMap<String, Vec<TypeScriptType>> {
    let mut organized: std::collections::HashMap<String, Vec<TypeScriptType>> =
        std::collections::HashMap::new();

    // Organize types by module. Currently, all types are included in each module
    // since schemas can be shared across modules. This could be enhanced to filter
    // types based on actual usage per module for better code organization.
    for module in module_schemas.keys() {
        organized.insert(module.clone(), types.clone());
    }

    organized
}

#[allow(clippy::too_many_arguments)]
fn generate_type_for_schema(
    openapi: &OpenAPI,
    name: &str,
    schema: &Schema,
    types: &mut Vec<TypeScriptType>,
    processed: &mut std::collections::HashSet<String>,
    enum_registry: &mut std::collections::HashMap<String, String>,
    parent_schema_name: Option<&str>,
    common_schemas: &[String],
    template_engine: Option<&TemplateEngine>,
    spec_name: Option<&str>,
) -> Result<()> {
    if processed.contains(name) {
        return Ok(());
    }
    processed.insert(name.to_string());

    let type_name = to_pascal_case(name);

    // Handle enums at top level (when schema itself is an enum)
    // Note: For property-level enums, they're handled in schema_to_typescript with context
    if let SchemaKind::Type(Type::String(string_type)) = &schema.schema_kind {
        if !string_type.enumeration.is_empty() {
            let mut enum_values: Vec<String> = string_type
                .enumeration
                .iter()
                .filter_map(|v| v.as_ref().cloned())
                .collect();
            if !enum_values.is_empty() {
                // Create a key from sorted enum values to check registry
                enum_values.sort();
                let enum_key = enum_values.join(",");

                // Use schema-specific context key so each schema can emit its own enum definition
                let schema_context_key = format!("schema_enum:{}", name);
                if enum_registry.get(&schema_context_key).is_some() {
                    return Ok(());
                }
                let context_key = if let Some(parent) = parent_schema_name {
                    if !parent.is_empty() {
                        format!("{}:{}", enum_key, parent)
                    } else {
                        schema_context_key.clone()
                    }
                } else {
                    schema_context_key.clone()
                };

                // Only skip if we've already generated an enum for this exact schema context
                if enum_registry.get(&context_key).is_some() {
                    return Ok(());
                }

                // Generate meaningful enum name
                let enum_name = if !name.is_empty() {
                    format!("{}Enum", to_pascal_case(name))
                } else if let Some(parent) = parent_schema_name {
                    if !parent.is_empty() {
                        let parent_clean = to_pascal_case(parent)
                            .trim_end_matches("ResponseDto")
                            .trim_end_matches("Dto")
                            .trim_end_matches("Response")
                            .to_string();
                        format!("{}Enum", parent_clean)
                    } else if !enum_values.is_empty() {
                        let first_value = &enum_values[0];
                        let base_name = first_value
                            .chars()
                            .take(1)
                            .collect::<String>()
                            .to_uppercase()
                            + &first_value.chars().skip(1).collect::<String>();
                        format!("{}Enum", to_pascal_case(&base_name))
                    } else {
                        "UnknownEnum".to_string()
                    }
                } else if !enum_values.is_empty() {
                    let first_value = &enum_values[0];
                    let base_name = first_value
                        .chars()
                        .take(1)
                        .collect::<String>()
                        .to_uppercase()
                        + &first_value.chars().skip(1).collect::<String>();
                    format!("{}Enum", to_pascal_case(&base_name))
                } else {
                    "UnknownEnum".to_string()
                };

                // Store in registry using schema context and base enum key (without overriding earlier entries)
                enum_registry.insert(context_key, enum_name.clone());
                enum_registry.insert(schema_context_key, enum_name.clone());
                if !enum_registry.contains_key(&enum_key) {
                    enum_registry.insert(enum_key.clone(), enum_name.clone());
                }
                // Also store mapping from schema name to enum name so $ref usages can resolve it
                if !name.is_empty() {
                    enum_registry.insert(format!("schema:{}", name), enum_name.clone());
                }

                if let Some(engine) = template_engine {
                    let description = schema.schema_data.description.clone();
                    let mut context = TypeContext::enum_type(
                        enum_name.clone(),
                        enum_values.clone(),
                        spec_name.map(|s| s.to_string()),
                    );
                    context.description = description;
                    let content = engine.render(TemplateId::TypeEnum, &context)?;
                    types.push(TypeScriptType { content });
                } else {
                    let enum_type = generate_enum_type(&enum_name, &enum_values);
                    let enum_with_desc = if let Some(desc) = schema.schema_data.description.as_ref()
                    {
                        TypeScriptType {
                            content: format!("/**\n * {}\n */\n{}", desc, enum_type.content),
                        }
                    } else {
                        enum_type
                    };
                    types.push(enum_with_desc);
                }
                return Ok(());
            }
        }
    }

    // Pass the current schema name as parent_schema_name for enum context
    let content = schema_to_typescript(
        openapi,
        schema,
        types,
        processed,
        0,
        enum_registry,
        None,
        Some(name),
        common_schemas,
        template_engine,
        spec_name,
    )?;

    // Only create interface if it's an object type
    if matches!(&schema.schema_kind, SchemaKind::Type(Type::Object(_))) {
        // Check if this is an empty object (should be a record type)
        if let SchemaKind::Type(Type::Object(obj)) = &schema.schema_kind {
            if obj.properties.is_empty() {
                // Empty object with additionalProperties - use type alias for Record
                if let Some(engine) = template_engine {
                    let context = TypeContext::alias(
                        type_name.clone(),
                        "Record<string, any>".to_string(),
                        spec_name.map(|s| s.to_string()),
                    );
                    let content = engine.render(TemplateId::TypeAlias, &context)?;
                    types.push(TypeScriptType { content });
                } else {
                    types.push(TypeScriptType {
                        content: format!("export type {} = Record<string, any>;", type_name),
                    });
                }
            } else {
                // Regular object with properties - build fields for template
                if let Some(engine) = template_engine {
                    let fields = build_fields_from_content(&content);
                    let description = schema.schema_data.description.clone();
                    let context = TypeContext::interface(
                        type_name.clone(),
                        fields,
                        description,
                        spec_name.map(|s| s.to_string()),
                    );
                    let content = engine.render(TemplateId::TypeInterface, &context)?;
                    types.push(TypeScriptType { content });
                } else {
                    types.push(TypeScriptType {
                        content: format!("export interface {} {{\n{}\n}}", type_name, content),
                    });
                }
            }
        }
    }

    Ok(())
}

#[allow(clippy::too_many_arguments)]
fn schema_to_typescript(
    openapi: &OpenAPI,
    schema: &Schema,
    types: &mut Vec<TypeScriptType>,
    processed: &mut std::collections::HashSet<String>,
    indent: usize,
    enum_registry: &mut std::collections::HashMap<String, String>,
    context: Option<(&str, &str)>, // (property_name, parent_schema_name)
    current_schema_name: Option<&str>, // Current schema being processed (for enum naming context)
    common_schemas: &[String],
    template_engine: Option<&TemplateEngine>,
    spec_name: Option<&str>,
) -> Result<String> {
    // Prevent infinite recursion with a reasonable depth limit
    if indent > 100 {
        return Ok("any".to_string());
    }
    let indent_str = "  ".repeat(indent);

    match &schema.schema_kind {
        SchemaKind::Type(type_) => {
            match type_ {
                Type::String(string_type) => {
                    // Check if it's an enum
                    if !string_type.enumeration.is_empty() {
                        let mut enum_values: Vec<String> = string_type
                            .enumeration
                            .iter()
                            .filter_map(|v| v.as_ref().cloned())
                            .collect();
                        enum_values.sort();
                        let enum_key = enum_values.join(",");

                        // For generic property names, include context in the key to avoid conflicts
                        let context_key = if let Some((prop_name, parent_schema)) = context {
                            let generic_names = ["status", "type", "state", "kind"];
                            if generic_names.contains(&prop_name.to_lowercase().as_str())
                                && !parent_schema.is_empty()
                            {
                                // Include parent schema in key for generic properties to avoid conflicts
                                format!("{}:{}", enum_key, parent_schema)
                            } else {
                                enum_key.clone()
                            }
                        } else {
                            enum_key.clone()
                        };

                        // Check registry for existing enum
                        // First check context_key (for context-aware enums)
                        // Then check base enum_key to deduplicate enums with same values
                        let existing_enum_name = enum_registry
                            .get(&context_key)
                            .or_else(|| enum_registry.get(&enum_key))
                            .cloned();

                        if let Some(enum_name) = existing_enum_name {
                            // Store in registry with context_key for future lookups
                            enum_registry.insert(context_key, enum_name.clone());
                            Ok(enum_name)
                        } else {
                            // Generate meaningful enum name using context (property name + parent schema) or fallback
                            let enum_name = if let Some((prop_name, parent_schema)) = context {
                                // Use property name + parent schema for meaningful name to avoid conflicts
                                // For generic names like "status", use parent schema to differentiate
                                // e.g., "status" in "KycStatusResponseDto" -> "KycStatusEnum" (parent already has "Status")
                                //      "status" in "TenantResponseDto" -> "TenantStatusEnum"
                                let prop_pascal = to_pascal_case(prop_name);

                                // If property name is generic (status, type, etc.), use parent schema
                                let generic_names = ["status", "type", "state", "kind"];
                                if generic_names.contains(&prop_name.to_lowercase().as_str())
                                    && !parent_schema.is_empty()
                                {
                                    let parent_pascal = to_pascal_case(parent_schema);
                                    // Remove common suffixes from parent schema name
                                    let parent_clean = parent_pascal
                                        .trim_end_matches("ResponseDto")
                                        .trim_end_matches("Dto")
                                        .trim_end_matches("Response")
                                        .to_string();

                                    // Check if parent already contains the property name (e.g., "KycStatus" contains "Status")
                                    // Use case-insensitive matching and check if property name is a suffix or contained
                                    let prop_lower = prop_pascal.to_lowercase();
                                    let parent_lower = parent_clean.to_lowercase();

                                    // Check if parent ends with property name (e.g., "KycStatus" ends with "Status")
                                    // or if property is contained in parent (case-insensitive)
                                    if parent_lower.ends_with(&prop_lower)
                                        || parent_lower.contains(&prop_lower)
                                    {
                                        // Parent already contains property name, just use parent + Enum
                                        format!("{}Enum", parent_clean)
                                    } else {
                                        // Combine parent + property
                                        format!("{}{}Enum", parent_clean, prop_pascal)
                                    }
                                } else {
                                    format!("{}Enum", prop_pascal)
                                }
                            } else if !enum_values.is_empty() {
                                // Fallback: use first value to create name
                                let first_value = &enum_values[0];
                                let base_name = first_value
                                    .chars()
                                    .take(1)
                                    .collect::<String>()
                                    .to_uppercase()
                                    + &first_value.chars().skip(1).collect::<String>();
                                format!("{}Enum", to_pascal_case(&base_name))
                            } else {
                                "UnknownEnum".to_string()
                            };
                            // Store in registry using context_key (includes context for generic properties)
                            // Also store with base enum_key for deduplication
                            enum_registry.insert(context_key.clone(), enum_name.clone());
                            enum_registry.insert(enum_key.clone(), enum_name.clone());

                            // Generate enum type
                            if let Some(engine) = template_engine {
                                let context = TypeContext::enum_type(
                                    enum_name.clone(),
                                    enum_values.clone(),
                                    spec_name.map(|s| s.to_string()),
                                );
                                let content = engine.render(TemplateId::TypeEnum, &context)?;
                                types.push(TypeScriptType { content });
                            } else {
                                let enum_type = generate_enum_type(&enum_name, &enum_values);
                                types.push(enum_type);
                            }

                            Ok(enum_name)
                        }
                    } else {
                        Ok("string".to_string())
                    }
                }
                Type::Number(_) => Ok("number".to_string()),
                Type::Integer(_) => Ok("number".to_string()),
                Type::Boolean(_) => Ok("boolean".to_string()),
                Type::Array(array) => {
                    let item_type = if let Some(items) = &array.items {
                        match items {
                            ReferenceOr::Reference { reference } => {
                                if let Some(ref_name) = get_schema_name_from_ref(reference) {
                                    // For $ref, always use the type name (don't inline)
                                    // Generate the referenced schema if not already processed
                                    if !processed.contains(&ref_name) {
                                        if let Ok(ReferenceOr::Item(ref_schema)) =
                                            resolve_ref(openapi, reference)
                                        {
                                            generate_type_for_schema(
                                                openapi,
                                                &ref_name,
                                                &ref_schema,
                                                types,
                                                processed,
                                                enum_registry,
                                                current_schema_name,
                                                common_schemas,
                                                template_engine,
                                                spec_name,
                                            )?;
                                        }
                                    }

                                    // If this $ref points to a top-level enum schema, use the enum type
                                    let schema_enum_key = format!("schema:{}", ref_name);
                                    if let Some(enum_name) = enum_registry.get(&schema_enum_key) {
                                        if common_schemas.contains(&ref_name) {
                                            format!("Common.{}", enum_name)
                                        } else {
                                            enum_name.clone()
                                        }
                                    } else if common_schemas.contains(&ref_name) {
                                        // Check if this is a common schema and prefix with Common.
                                        format!("Common.{}", to_pascal_case(&ref_name))
                                    } else {
                                        to_pascal_case(&ref_name)
                                    }
                                } else {
                                    "any".to_string()
                                }
                            }
                            ReferenceOr::Item(item_schema) => {
                                // If it's an object, wrap the fields in braces
                                if matches!(
                                    &item_schema.schema_kind,
                                    SchemaKind::Type(Type::Object(_))
                                ) {
                                    let fields = schema_to_typescript(
                                        openapi,
                                        item_schema,
                                        types,
                                        processed,
                                        indent,
                                        enum_registry,
                                        None,
                                        current_schema_name,
                                        common_schemas,
                                        template_engine,
                                        spec_name,
                                    )?;
                                    format!("{{\n{}{}\n{}}}", indent_str, fields, indent_str)
                                } else {
                                    schema_to_typescript(
                                        openapi,
                                        item_schema,
                                        types,
                                        processed,
                                        indent,
                                        enum_registry,
                                        None,
                                        current_schema_name,
                                        common_schemas,
                                        template_engine,
                                        spec_name,
                                    )?
                                }
                            }
                        }
                    } else {
                        "any".to_string()
                    };
                    Ok(format!("{}[]", item_type))
                }
                Type::Object(object_type) => {
                    if !object_type.properties.is_empty() {
                        let mut fields = Vec::new();
                        // Get parent schema name from context if available, otherwise use current_schema_name parameter
                        // For object properties, use the current schema name as parent
                        let parent_schema_for_props = context
                            .and_then(|(_, parent)| {
                                if !parent.is_empty() {
                                    Some(parent.to_string())
                                } else {
                                    None
                                }
                            })
                            .or_else(|| current_schema_name.map(|s| s.to_string()))
                            .unwrap_or_default();

                        for (prop_name, prop_schema_ref) in object_type.properties.iter() {
                            let prop_type = match prop_schema_ref {
                                ReferenceOr::Reference { reference } => {
                                    // For $ref properties, always use the type name (don't inline)
                                    if let Some(ref_name) = get_schema_name_from_ref(reference) {
                                        // Generate the referenced schema if not already processed
                                        if !processed.contains(&ref_name) {
                                            if let Ok(ReferenceOr::Item(ref_schema)) =
                                                resolve_ref(openapi, reference)
                                            {
                                                generate_type_for_schema(
                                                    openapi,
                                                    &ref_name,
                                                    &ref_schema,
                                                    types,
                                                    processed,
                                                    enum_registry,
                                                    Some(&parent_schema_for_props),
                                                    common_schemas,
                                                    template_engine,
                                                    spec_name,
                                                )?;
                                            }
                                        }

                                        // If this $ref points to a top-level enum schema, use the enum type
                                        let schema_enum_key = format!("schema:{}", ref_name);
                                        if let Some(enum_name) = enum_registry.get(&schema_enum_key)
                                        {
                                            if common_schemas.contains(&ref_name) {
                                                format!("Common.{}", enum_name)
                                            } else {
                                                enum_name.clone()
                                            }
                                        } else if common_schemas.contains(&ref_name) {
                                            // Check if this is a common schema and prefix with Common.
                                            format!("Common.{}", to_pascal_case(&ref_name))
                                        } else {
                                            to_pascal_case(&ref_name)
                                        }
                                    } else {
                                        "any".to_string()
                                    }
                                }
                                ReferenceOr::Item(prop_schema) => schema_to_typescript(
                                    openapi,
                                    prop_schema,
                                    types,
                                    processed,
                                    indent,
                                    enum_registry,
                                    Some((prop_name, &parent_schema_for_props)),
                                    current_schema_name,
                                    common_schemas,
                                    template_engine,
                                    spec_name,
                                )?,
                            };

                            let required = object_type.required.contains(prop_name);

                            let optional = if required { "" } else { "?" };
                            let nullable = prop_schema_ref
                                .as_item()
                                .map(|s| s.schema_data.nullable)
                                .unwrap_or(false);

                            let nullable_str = if nullable { " | null" } else { "" };

                            // Extract property description
                            let prop_description = prop_schema_ref
                                .as_item()
                                .and_then(|s| s.schema_data.description.clone());

                            // Build field string with description comment if available
                            let field_str = if let Some(desc) = &prop_description {
                                format!(
                                    "{}{}{}: {}{}; // {}",
                                    indent_str,
                                    sanitize_property_name(prop_name),
                                    optional,
                                    prop_type,
                                    nullable_str,
                                    desc
                                )
                            } else {
                                format!(
                                    "{}{}{}: {}{};",
                                    indent_str,
                                    sanitize_property_name(prop_name),
                                    optional,
                                    prop_type,
                                    nullable_str
                                )
                            };

                            fields.push(field_str);
                        }
                        Ok(fields.join("\n"))
                    } else {
                        Ok("Record<string, any>".to_string())
                    }
                }
            }
        }
        SchemaKind::Any(_) => Ok("any".to_string()),
        SchemaKind::OneOf { one_of, .. } => {
            let mut variant_types = Vec::new();
            for item in one_of {
                match item {
                    ReferenceOr::Reference { reference } => {
                        if let Some(ref_name) = get_schema_name_from_ref(reference) {
                            let schema_enum_key = format!("schema:{}", ref_name);
                            let type_name =
                                if let Some(enum_name) = enum_registry.get(&schema_enum_key) {
                                    if common_schemas.contains(&ref_name) {
                                        format!("Common.{}", enum_name)
                                    } else {
                                        enum_name.clone()
                                    }
                                } else if common_schemas.contains(&ref_name) {
                                    format!("Common.{}", to_pascal_case(&ref_name))
                                } else {
                                    to_pascal_case(&ref_name)
                                };
                            variant_types.push(type_name);
                        } else {
                            variant_types.push("any".to_string());
                        }
                    }
                    ReferenceOr::Item(item_schema) => {
                        let item_type = schema_to_typescript(
                            openapi,
                            item_schema,
                            types,
                            processed,
                            indent,
                            enum_registry,
                            None,
                            current_schema_name,
                            common_schemas,
                            template_engine,
                            spec_name,
                        )?;
                        variant_types.push(item_type);
                    }
                }
            }
            if variant_types.is_empty() {
                Ok("any".to_string())
            } else {
                Ok(variant_types.join(" | "))
            }
        }
        SchemaKind::AllOf { all_of, .. } => {
            let mut all_types = Vec::new();
            for item in all_of {
                match item {
                    ReferenceOr::Reference { reference } => {
                        if let Some(ref_name) = get_schema_name_from_ref(reference) {
                            let schema_enum_key = format!("schema:{}", ref_name);
                            let type_name =
                                if let Some(enum_name) = enum_registry.get(&schema_enum_key) {
                                    if common_schemas.contains(&ref_name) {
                                        format!("Common.{}", enum_name)
                                    } else {
                                        enum_name.clone()
                                    }
                                } else if common_schemas.contains(&ref_name) {
                                    format!("Common.{}", to_pascal_case(&ref_name))
                                } else {
                                    to_pascal_case(&ref_name)
                                };
                            all_types.push(type_name);
                        } else {
                            all_types.push("any".to_string());
                        }
                    }
                    ReferenceOr::Item(item_schema) => {
                        let item_type = schema_to_typescript(
                            openapi,
                            item_schema,
                            types,
                            processed,
                            indent,
                            enum_registry,
                            None,
                            current_schema_name,
                            common_schemas,
                            template_engine,
                            spec_name,
                        )?;
                        all_types.push(item_type);
                    }
                }
            }
            if all_types.is_empty() {
                Ok("any".to_string())
            } else {
                Ok(all_types.join(" & "))
            }
        }
        SchemaKind::AnyOf { any_of, .. } => {
            // AnyOf is treated same as OneOf (union type)
            let mut variant_types = Vec::new();
            for item in any_of {
                match item {
                    ReferenceOr::Reference { reference } => {
                        if let Some(ref_name) = get_schema_name_from_ref(reference) {
                            let schema_enum_key = format!("schema:{}", ref_name);
                            let type_name =
                                if let Some(enum_name) = enum_registry.get(&schema_enum_key) {
                                    if common_schemas.contains(&ref_name) {
                                        format!("Common.{}", enum_name)
                                    } else {
                                        enum_name.clone()
                                    }
                                } else if common_schemas.contains(&ref_name) {
                                    format!("Common.{}", to_pascal_case(&ref_name))
                                } else {
                                    to_pascal_case(&ref_name)
                                };
                            variant_types.push(type_name);
                        } else {
                            variant_types.push("any".to_string());
                        }
                    }
                    ReferenceOr::Item(item_schema) => {
                        let item_type = schema_to_typescript(
                            openapi,
                            item_schema,
                            types,
                            processed,
                            indent,
                            enum_registry,
                            None,
                            current_schema_name,
                            common_schemas,
                            template_engine,
                            spec_name,
                        )?;
                        variant_types.push(item_type);
                    }
                }
            }
            if variant_types.is_empty() {
                Ok("any".to_string())
            } else {
                Ok(variant_types.join(" | "))
            }
        }
        SchemaKind::Not { .. } => Ok("any".to_string()),
    }
    .map(|base_type| {
        if schema.schema_data.nullable {
            format!("{} | null", base_type)
        } else {
            base_type
        }
    })
}

pub fn generate_enum_type(name: &str, values: &[String]) -> TypeScriptType {
    let enum_values = values
        .iter()
        .map(|v| format!("  \"{}\"", v))
        .collect::<Vec<_>>()
        .join(" |\n");

    TypeScriptType {
        content: format!("export type {} =\n{};", to_pascal_case(name), enum_values),
    }
}

/// Parse field content string into Field structs.
/// Format: "  fieldName?: type; // description" or "  fieldName: type;"
fn build_fields_from_content(content: &str) -> Vec<Field> {
    let mut fields = Vec::new();

    for line in content.lines() {
        let line = line.trim();
        if line.is_empty() || line == "{" || line == "}" {
            continue;
        }

        // Parse: "fieldName?: type; // description" or "fieldName: type;"
        if let Some(colon_pos) = line.find(':') {
            let before_colon = &line[..colon_pos].trim();
            let after_colon = &line[colon_pos + 1..].trim();

            let optional = before_colon.ends_with('?');
            let field_name = if optional {
                before_colon[..before_colon.len() - 1].trim().to_string()
            } else {
                before_colon.to_string()
            };

            // Extract type and description
            let semicolon_pos = after_colon.find(';').unwrap_or(after_colon.len());
            let type_part = &after_colon[..semicolon_pos].trim();
            let rest = &after_colon[semicolon_pos + 1..].trim();

            let description = rest.strip_prefix("//").map(|s| s.trim().to_string());

            fields.push(Field::new(
                field_name,
                type_part.to_string(),
                optional,
                description,
            ));
        }
    }

    fields
}