mrapids 0.1.31

Your OpenAPI, but executable
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
// Modern project initialization with flat structure
use crate::cli::InitCommand;
use crate::core::parser::UnifiedSpec;
use anyhow::{Context, Result};
use colored::*;
use std::fs;
use std::path::Path;

/// Initialize a new MicroRapid project with flat structure
pub fn init_project(cmd: InitCommand) -> Result<()> {
    let project_path = Path::new(&cmd.name);

    println!(
        "{} Initializing MicroRapid project: {}",
        "🚀".bright_blue(),
        cmd.name.bright_yellow()
    );

    // Check if directory exists
    if project_path.exists() && project_path.read_dir()?.count() > 0 && !cmd.force {
        println!(
            "{} Directory '{}' is not empty. Use --force to overwrite.",
            "".red(),
            project_path.display()
        );
        return Ok(());
    }

    // Create project directory
    if !project_path.exists() {
        fs::create_dir_all(&project_path)?;
    }

    // Create the flat structure
    create_flat_structure(project_path)?;

    // If spec provided, download and process it
    if let Some(url) = &cmd.from_url {
        download_and_setup_spec(project_path, url, cmd.allow_insecure)?;
    } else if let Some(file) = &cmd.from_file {
        copy_and_setup_spec(project_path, file)?;
    }

    println!("\n{} Project initialized successfully!", "".green());
    print_next_steps(&cmd.name);

    Ok(())
}

/// Create the flat project structure
fn create_flat_structure(base: &Path) -> Result<()> {
    // Create directories
    fs::create_dir_all(base.join("specs"))?;
    fs::create_dir_all(base.join("config"))?;
    fs::create_dir_all(base.join("env"))?;
    fs::create_dir_all(base.join("collections"))?;
    fs::create_dir_all(base.join("tests"))?;
    fs::create_dir_all(base.join("scripts"))?;
    fs::create_dir_all(base.join("docs"))?;

    // Create mrapids.yaml (manifest)
    create_manifest_file(base)?;

    // Create config files
    create_config_files(base)?;

    // Create env files
    create_env_files(base)?;

    // Create default spec
    create_default_spec(base)?;

    // Create .gitignore
    create_gitignore(base)?;

    // Create README in docs folder
    create_readme(base)?;

    // Create smoke test
    create_smoke_test(base)?;

    Ok(())
}

/// Create mrapids.yaml manifest
fn create_manifest_file(base: &Path) -> Result<()> {
    let content = r#"# MicroRapid Project Manifest
name: my-api
version: 1.0.0
description: My API project
default_spec: specs/api.yaml
default_env: development

# Project metadata
author: Your Name
repository: https://github.com/yourusername/my-api
"#;

    fs::write(base.join("mrapids.yaml"), content)?;
    println!("  {} Created mrapids.yaml", "".green());
    Ok(())
}

/// Create config files for each environment
fn create_config_files(base: &Path) -> Result<()> {
    // Create default.yaml
    let default_config = r#"# Shared configuration for all environments
timeout_ms: 30000
retries: 2

# Common headers
headers:
  User-Agent: mrapids/1.0
  Accept: application/json
  Content-Type: application/json
"#;

    fs::write(base.join("config/default.yaml"), default_config)?;
    println!("  {} Created config/default.yaml", "".green());

    // Create development.yaml
    let dev_config = r#"# Development environment configuration
base_url: http://localhost:3000/api/v1
timeout_ms: 60000  # Longer timeout for debugging

headers:
  X-Environment: development
  X-Debug: true
  # Add auth headers as needed (uncomment one):
  # Authorization: Bearer ${DEV_API_TOKEN}
  # Authorization: Basic ${DEV_BASIC_AUTH}  # base64(username:password)
  # X-API-Key: ${DEV_API_KEY}
"#;

    fs::write(base.join("config/development.yaml"), dev_config)?;
    println!("  {} Created config/development.yaml", "".green());

    // Create staging.yaml
    let staging_config = r#"# Staging environment configuration
base_url: https://staging.api.example.com/v1

headers:
  X-Environment: staging
  # Add auth headers as needed (uncomment one):
  # Authorization: Bearer ${STAGING_API_TOKEN}
  # Authorization: Basic ${STAGING_BASIC_AUTH}  # base64(username:password)
  # X-API-Key: ${STAGING_API_KEY}
"#;

    fs::write(base.join("config/staging.yaml"), staging_config)?;
    println!("  {} Created config/staging.yaml", "".green());

    // Create production.yaml
    let prod_config = r#"# Production environment configuration
base_url: https://api.example.com/v1
timeout_ms: 10000  # Strict timeout for production
retries: 3

headers:
  X-Environment: production
  X-Request-ID: ${REQUEST_ID:-auto}
  # Add auth headers as needed (uncomment one):
  # Authorization: Bearer ${PROD_API_TOKEN}
  # Authorization: Basic ${PROD_BASIC_AUTH}  # base64(username:password)
  # X-API-Key: ${PROD_API_KEY}

# Stricter rate limiting for production
rate_limit:
  requests_per_second: 100
  burst: 200

# Production proxy (optional)
proxy: ${HTTPS_PROXY:-}
"#;

    fs::write(base.join("config/production.yaml"), prod_config)?;
    println!("  {} Created config/production.yaml", "".green());

    Ok(())
}

/// Create environment variable files
fn create_env_files(base: &Path) -> Result<()> {
    // Create .env.development
    let dev_env = r#"# Development environment variables
# Uncomment and set the auth method you need:

# For Bearer token:
# DEV_API_TOKEN=your-bearer-token-here

# For Basic auth (base64 encode username:password):
# DEV_BASIC_AUTH=dXNlcm5hbWU6cGFzc3dvcmQ=

# For API key:
# DEV_API_KEY=your-api-key-here

LOG_LEVEL=debug
DEBUG=true
"#;

    fs::write(base.join("env/.env.development"), dev_env)?;
    println!("  {} Created env/.env.development", "".green());

    // Create .env.staging
    let staging_env = r#"# Staging environment variables
# Uncomment and set the auth method you need:

# For Bearer token:
# STAGING_API_TOKEN=your-staging-token-here

# For Basic auth (base64 encode username:password):
# STAGING_BASIC_AUTH=dXNlcm5hbWU6cGFzc3dvcmQ=

# For API key:
# STAGING_API_KEY=your-staging-api-key-here

LOG_LEVEL=info
"#;

    fs::write(base.join("env/.env.staging"), staging_env)?;
    println!("  {} Created env/.env.staging", "".green());

    // Create .env.production
    let prod_env = r#"# Production environment variables
# NOTE: Real secrets should be injected by CI/CD, not committed

# For Bearer token:
# PROD_API_TOKEN=  # Set by CI/CD

# For Basic auth (base64 encode username:password):
# PROD_BASIC_AUTH=  # Set by CI/CD

# For API key:
# PROD_API_KEY=  # Set by CI/CD

LOG_LEVEL=error
"#;

    fs::write(base.join("env/.env.production"), prod_env)?;
    println!("  {} Created env/.env.production", "".green());

    Ok(())
}

/// Create default OpenAPI spec
fn create_default_spec(base: &Path) -> Result<()> {
    let content = r#"openapi: 3.0.3
info:
  title: Sample API
  version: 1.0.0
  description: |
    This is a sample API specification.
    Replace this with your actual API specification.

servers:
  - url: http://localhost:3000/api/v1
    description: Development server
  - url: https://api.example.com/v1
    description: Production server

paths:
  /health:
    get:
      operationId: healthCheck
      summary: Health check endpoint
      tags:
        - System
      responses:
        '200':
          description: Service is healthy
          content:
            application/json:
              schema:
                type: object
                properties:
                  status:
                    type: string
                    example: healthy
                  timestamp:
                    type: string
                    format: date-time
  
  /users:
    get:
      operationId: listUsers
      summary: List all users
      tags:
        - Users
      security:
        - bearerAuth: []
        - apiKey: []
      parameters:
        - name: limit
          in: query
          schema:
            type: integer
            default: 10
        - name: offset
          in: query
          schema:
            type: integer
            default: 0
      responses:
        '200':
          description: List of users
          content:
            application/json:
              schema:
                type: array
                items:
                  $ref: '#/components/schemas/User'

components:
  schemas:
    User:
      type: object
      properties:
        id:
          type: string
          format: uuid
        name:
          type: string
        email:
          type: string
          format: email
        createdAt:
          type: string
          format: date-time
  
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      bearerFormat: JWT
    apiKey:
      type: apiKey
      in: header
      name: X-API-Key
"#;

    fs::write(base.join("specs/api.yaml"), content)?;
    println!("  {} Created specs/api.yaml", "".green());
    Ok(())
}

/// Create .gitignore
fn create_gitignore(base: &Path) -> Result<()> {
    let content = r#"# Environment files (keep templates, ignore actual values)
env/.env.local
env/.env.*.local

# Test outputs
tests/results/
tests/.coverage/

# Generated files
scripts/generated/
*.generated.*

# IDE
.vscode/
.idea/
*.swp
*.swo
.DS_Store

# Dependencies
node_modules/
vendor/

# Logs
*.log
logs/

# Temporary files
tmp/
temp/
"#;

    fs::write(base.join(".gitignore"), content)?;
    println!("  {} Created .gitignore", "".green());
    Ok(())
}

/// Create README.md
fn create_readme(base: &Path) -> Result<()> {
    let content = r#"# My API Project

Generated with [MicroRapid](https://github.com/microrapid/mrapids)

## Project Structure

```
.
├── mrapids.yaml           # Project manifest
├── config/                # Environment configurations
│   ├── default.yaml       # Shared defaults
│   ├── development.yaml   # Development
│   ├── staging.yaml       # Staging
│   └── production.yaml    # Production
├── env/                   # Environment variables (gitignored)
│   ├── .env.development
│   ├── .env.staging
│   └── .env.production
├── specs/                 # API specifications
│   └── api.yaml
├── tests/                 # Test files
│   └── smoke.test.js      # Smoke tests
├── scripts/               # Generated scripts
└── docs/                  # Documentation
    └── README.md          # This file
```

## Quick Start

```bash
# Install MicroRapid
npm install -g mrapids

# Run in development
mrapids run --env development

# Run specific operation
mrapids run users/list --env staging

# Generate SDK
mrapids gen sdk --language typescript

# Run tests
mrapids test
```

## Configuration

Configuration follows this precedence (highest to lowest):
1. CLI arguments
2. Environment variables
3. `env/.env.{environment}`
4. `config/{environment}.yaml`
5. `config/default.yaml`
6. `mrapids.yaml` defaults

## Authentication

Authentication is handled via headers in the config files.

Example:
```yaml
# config/development.yaml
headers:
  X-Environment: development
  Authorization: Bearer ${DEV_API_TOKEN}  # From env/.env.development
  X-API-Key: ${DEV_API_KEY}               # From env/.env.development
```

## Environments

- **development**: Local development
- **staging**: Pre-production
- **production**: Production

Switch environments:
```bash
mrapids run --env production
# or
export MRAPIDS_ENV=production
mrapids run
```
"#;

    fs::write(base.join("docs/README.md"), content)?;
    println!("  {} Created docs/README.md", "".green());
    Ok(())
}

/// Download and setup OpenAPI spec
fn download_and_setup_spec(base: &Path, url: &str, allow_insecure: bool) -> Result<()> {
    use crate::utils::security::enforce_https;

    if !allow_insecure {
        enforce_https(url, false)?;
    }

    println!("{} Downloading spec from: {}", "📥".cyan(), url);

    // Download spec
    let client = reqwest::blocking::Client::new();
    let response = client.get(url).send().context("Failed to download spec")?;

    let content = response.text().context("Failed to read spec content")?;

    // Save to specs/api.yaml
    fs::write(base.join("specs/api.yaml"), &content)?;

    // Parse and extract auth info
    if let Ok(spec) = crate::core::parser::parse_spec(&content) {
        update_configs_from_spec(base, &spec)?;
    }

    Ok(())
}

/// Copy and setup local spec file
fn copy_and_setup_spec(base: &Path, file: &str) -> Result<()> {
    println!("{} Copying spec from: {}", "📄".cyan(), file);

    let content = fs::read_to_string(file).context("Failed to read spec file")?;

    fs::write(base.join("specs/api.yaml"), &content)?;

    // Parse and extract auth info
    if let Ok(spec) = crate::core::parser::parse_spec(&content) {
        update_configs_from_spec(base, &spec)?;
    }

    Ok(())
}

/// Update configs based on parsed spec
fn update_configs_from_spec(base: &Path, spec: &UnifiedSpec) -> Result<()> {
    // Update base URL in configs
    let base_url = spec.get_base_url();

    // Update development.yaml with actual base URL
    let dev_config_path = base.join("config/development.yaml");
    if dev_config_path.exists() {
        let content = fs::read_to_string(&dev_config_path)?;
        let updated = content.replace(
            "base_url: http://localhost:3000/api/v1",
            &format!("base_url: {}", base_url),
        );
        fs::write(dev_config_path, updated)?;
    }

    println!("  {} Updated configs with spec information", "".green());
    Ok(())
}

/// Create smoke test file
fn create_smoke_test(base: &Path) -> Result<()> {
    let content = r#"// Smoke tests for API endpoints
// Run with: mrapids test

const assert = require('assert');

describe('API Smoke Tests', () => {
  it('should check health endpoint', async () => {
    const response = await mrapids.run('healthCheck');
    assert.equal(response.status, 200);
    assert.equal(response.data.status, 'healthy');
  });

  it('should authenticate successfully', async () => {
    const response = await mrapids.auth.validate();
    assert.equal(response.success, true);
  });

  it('should list users with authentication', async () => {
    const response = await mrapids.run('listUsers', {
      params: { limit: 10 }
    });
    assert.equal(response.status, 200);
    assert(Array.isArray(response.data));
  });

  it('should handle errors gracefully', async () => {
    try {
      await mrapids.run('nonExistentEndpoint');
      assert.fail('Should have thrown an error');
    } catch (error) {
      assert(error.message.includes('not found'));
    }
  });
});

// Environment-specific tests
if (process.env.MRAPIDS_ENV === 'production') {
  describe('Production Tests', () => {
    it('should enforce rate limits', async () => {
      // Production-specific tests
    });
  });
}
"#;

    fs::write(base.join("tests/smoke.test.js"), content)?;
    println!("  {} Created tests/smoke.test.js", "".green());
    Ok(())
}

/// Print next steps after initialization
fn print_next_steps(project_name: &str) {
    println!("\n{}", "Next steps:".bold().cyan());
    println!("  1. cd {}", project_name);
    println!("  2. Edit config/development.yaml with your API settings");
    println!("  3. Update env/.env.development with your credentials");
    println!("  4. Run: mrapids run --env development");
    println!(
        "\n{} Tip: Use 'mrapids doctor' to check your setup",
        "💡".yellow()
    );
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use tempfile::TempDir;

    // ============================================================================
    // create_flat_structure tests
    // ============================================================================

    #[test]
    fn test_create_flat_structure_creates_all_directories() {
        let temp_dir = TempDir::new().unwrap();
        let base = temp_dir.path();

        let result = create_flat_structure(base);
        assert!(result.is_ok());

        // Verify directories exist
        assert!(base.join("specs").exists());
        assert!(base.join("config").exists());
        assert!(base.join("env").exists());
        assert!(base.join("collections").exists());
        assert!(base.join("tests").exists());
        assert!(base.join("scripts").exists());
        assert!(base.join("docs").exists());
    }

    #[test]
    fn test_create_flat_structure_creates_manifest() {
        let temp_dir = TempDir::new().unwrap();
        let base = temp_dir.path();

        create_flat_structure(base).unwrap();

        let manifest_path = base.join("mrapids.yaml");
        assert!(manifest_path.exists());

        let content = fs::read_to_string(manifest_path).unwrap();
        assert!(content.contains("name:"));
        assert!(content.contains("version:"));
        assert!(content.contains("default_spec:"));
    }

    #[test]
    fn test_create_flat_structure_creates_config_files() {
        let temp_dir = TempDir::new().unwrap();
        let base = temp_dir.path();

        create_flat_structure(base).unwrap();

        assert!(base.join("config/default.yaml").exists());
        assert!(base.join("config/development.yaml").exists());
        assert!(base.join("config/staging.yaml").exists());
        assert!(base.join("config/production.yaml").exists());
    }

    #[test]
    fn test_create_flat_structure_creates_env_files() {
        let temp_dir = TempDir::new().unwrap();
        let base = temp_dir.path();

        create_flat_structure(base).unwrap();

        assert!(base.join("env/.env.development").exists());
        assert!(base.join("env/.env.staging").exists());
        assert!(base.join("env/.env.production").exists());
    }

    #[test]
    fn test_create_flat_structure_creates_gitignore() {
        let temp_dir = TempDir::new().unwrap();
        let base = temp_dir.path();

        create_flat_structure(base).unwrap();

        let gitignore_path = base.join(".gitignore");
        assert!(gitignore_path.exists());

        let content = fs::read_to_string(gitignore_path).unwrap();
        assert!(content.contains(".env.local"));
        assert!(content.contains("node_modules/"));
    }

    #[test]
    fn test_create_flat_structure_creates_default_spec() {
        let temp_dir = TempDir::new().unwrap();
        let base = temp_dir.path();

        create_flat_structure(base).unwrap();

        let spec_path = base.join("specs/api.yaml");
        assert!(spec_path.exists());

        let content = fs::read_to_string(spec_path).unwrap();
        assert!(content.contains("openapi: 3.0.3"));
        assert!(content.contains("healthCheck"));
    }

    // ============================================================================
    // Config file content tests
    // ============================================================================

    #[test]
    fn test_development_config_has_localhost_base_url() {
        let temp_dir = TempDir::new().unwrap();
        let base = temp_dir.path();

        fs::create_dir_all(base.join("config")).unwrap();
        create_config_files(base).unwrap();

        let content = fs::read_to_string(base.join("config/development.yaml")).unwrap();
        assert!(content.contains("localhost"));
        assert!(content.contains("X-Debug: true"));
    }

    #[test]
    fn test_production_config_has_stricter_settings() {
        let temp_dir = TempDir::new().unwrap();
        let base = temp_dir.path();

        fs::create_dir_all(base.join("config")).unwrap();
        create_config_files(base).unwrap();

        let content = fs::read_to_string(base.join("config/production.yaml")).unwrap();
        assert!(content.contains("timeout_ms: 10000")); // Stricter timeout
        assert!(content.contains("retries: 3"));
        assert!(content.contains("rate_limit:"));
    }

    // ============================================================================
    // Manifest file tests
    // ============================================================================

    #[test]
    fn test_manifest_has_required_fields() {
        let temp_dir = TempDir::new().unwrap();
        let base = temp_dir.path();

        create_manifest_file(base).unwrap();

        let content = fs::read_to_string(base.join("mrapids.yaml")).unwrap();
        assert!(content.contains("name:"));
        assert!(content.contains("version:"));
        assert!(content.contains("default_spec: specs/api.yaml"));
        assert!(content.contains("default_env: development"));
    }

    // ============================================================================
    // Smoke test file tests
    // ============================================================================

    #[test]
    fn test_smoke_test_file_created() {
        let temp_dir = TempDir::new().unwrap();
        let base = temp_dir.path();

        fs::create_dir_all(base.join("tests")).unwrap();
        create_smoke_test(base).unwrap();

        let smoke_path = base.join("tests/smoke.test.js");
        assert!(smoke_path.exists());

        let content = fs::read_to_string(smoke_path).unwrap();
        assert!(content.contains("healthCheck"));
        assert!(content.contains("describe"));
        assert!(content.contains("assert"));
    }

    // ============================================================================
    // README file tests
    // ============================================================================

    #[test]
    fn test_readme_created_in_docs() {
        let temp_dir = TempDir::new().unwrap();
        let base = temp_dir.path();

        fs::create_dir_all(base.join("docs")).unwrap();
        create_readme(base).unwrap();

        let readme_path = base.join("docs/README.md");
        assert!(readme_path.exists());

        let content = fs::read_to_string(readme_path).unwrap();
        assert!(content.contains("MicroRapid"));
        assert!(content.contains("Quick Start"));
        assert!(content.contains("Project Structure"));
    }

    // ============================================================================
    // update_configs_from_spec tests
    // ============================================================================

    #[test]
    fn test_update_configs_from_spec() {
        let temp_dir = TempDir::new().unwrap();
        let base = temp_dir.path();

        // Create config directory and file
        fs::create_dir_all(base.join("config")).unwrap();
        create_config_files(base).unwrap();

        // Create a test spec
        let spec = UnifiedSpec {
            info: crate::core::parser::ApiInfo {
                title: "Test API".to_string(),
                version: "1.0.0".to_string(),
                description: None,
            },
            base_url: "https://api.test.com/v1".to_string(),
            operations: vec![],
            security_schemes: std::collections::HashMap::new(),
        };

        let result = update_configs_from_spec(base, &spec);
        assert!(result.is_ok());

        // Verify the base_url was updated
        let content = fs::read_to_string(base.join("config/development.yaml")).unwrap();
        assert!(content.contains("https://api.test.com/v1"));
    }

    // ============================================================================
    // copy_and_setup_spec tests
    // ============================================================================

    #[test]
    fn test_copy_and_setup_spec() {
        let temp_dir = TempDir::new().unwrap();
        let base = temp_dir.path();

        // Create the project structure first
        create_flat_structure(base).unwrap();

        // Create a source spec file
        let source_spec = r#"
openapi: "3.0.0"
info:
  title: Test API
  version: "1.0.0"
servers:
  - url: https://api.example.com
paths:
  /test:
    get:
      operationId: test
      responses:
        "200":
          description: OK
"#;
        let source_path = temp_dir.path().join("source_spec.yaml");
        fs::write(&source_path, source_spec).unwrap();

        let result = copy_and_setup_spec(base, source_path.to_str().unwrap());
        assert!(result.is_ok());

        // Verify spec was copied
        let copied_spec = fs::read_to_string(base.join("specs/api.yaml")).unwrap();
        assert!(copied_spec.contains("Test API"));
    }
}