ferro-cli 0.2.6

CLI for scaffolding Ferro web applications
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
use chrono::Local;
use console::style;
use std::fs;
use std::path::Path;

// ---------------------------------------------------------------------------
// Template generators
// ---------------------------------------------------------------------------

fn stripe_mod_template(connect: bool) -> String {
    let connect_mod = if connect {
        "\npub mod connect_webhook;"
    } else {
        ""
    };

    format!(
        r#"pub mod webhook;
pub mod listeners;{connect_mod}

use ferro::Stripe;

/// Initialize Stripe. Call from bootstrap.rs.
pub fn init() {{
    let config = ferro::StripeConfig::from_env()
        .expect("Stripe configuration missing. Set STRIPE_SECRET_KEY and STRIPE_WEBHOOK_SECRET.");
    Stripe::init(config);
}}
"#
    )
}

fn stripe_webhook_template() -> String {
    r#"use ferro::{handler, HttpResponse, Request, Response, Stripe};
use ferro::ProcessStripeWebhook;

#[handler]
pub async fn stripe_webhook(req: Request) -> Response {
    let sig = req
        .header("stripe-signature")
        .ok_or_else(|| HttpResponse::text("Missing stripe-signature").status(400))?;
    let body = req
        .body_string()
        .await
        .map_err(|_| HttpResponse::text("Failed to read body").status(400))?;

    let event = ferro::verify_webhook(&body, &sig, &Stripe::config().webhook_secret)
        .map_err(|_| HttpResponse::text("Invalid signature").status(400))?;

    let job = ProcessStripeWebhook {
        event_type: event.type_.to_string(),
        event_json: body.clone(),
        connect_account_id: None,
    };
    ferro::queue_dispatch(job)
        .await
        .map_err(|e| HttpResponse::text(format!("Queue error: {e}")).status(500))?;

    Ok(HttpResponse::json(serde_json::json!({"received": true})))
}
"#
    .to_string()
}

fn stripe_connect_webhook_template() -> String {
    r#"use ferro::{handler, HttpResponse, Request, Response, Stripe};
use ferro::ProcessStripeWebhook;

#[handler]
pub async fn stripe_connect_webhook(req: Request) -> Response {
    let sig = req
        .header("stripe-signature")
        .ok_or_else(|| HttpResponse::text("Missing stripe-signature").status(400))?;
    let body = req
        .body_string()
        .await
        .map_err(|_| HttpResponse::text("Failed to read body").status(400))?;

    let event = ferro::verify_webhook(
        &body,
        &sig,
        Stripe::config()
            .connect_webhook_secret
            .as_deref()
            .unwrap_or_default(),
    )
    .map_err(|_| HttpResponse::text("Invalid signature").status(400))?;

    let job = ProcessStripeWebhook {
        event_type: event.type_.to_string(),
        event_json: body.clone(),
        connect_account_id: event.account.map(|id| id.to_string()),
    };
    ferro::queue_dispatch(job)
        .await
        .map_err(|e| HttpResponse::text(format!("Queue error: {e}")).status(500))?;

    Ok(HttpResponse::json(serde_json::json!({"received": true})))
}
"#
    .to_string()
}

fn stripe_listeners_template() -> String {
    r#"use ferro::{async_trait, EventError, Listener};
use ferro::{StripeCheckoutCompleted, StripeSubscriptionDeleted, StripeSubscriptionUpdated};

pub struct SyncSubscriptionPlan;

#[async_trait]
impl Listener<StripeSubscriptionUpdated> for SyncSubscriptionPlan {
    async fn handle(&self, event: &StripeSubscriptionUpdated) -> Result<(), EventError> {
        // TODO: Update tenant_billing table with new subscription state.
        // TODO: Invalidate tenant cache: lookup.invalidate(&slug, tenant_id)
        println!("Subscription updated: {}", event.subscription_id);
        Ok(())
    }
}

pub struct HandleSubscriptionDeleted;

#[async_trait]
impl Listener<StripeSubscriptionDeleted> for HandleSubscriptionDeleted {
    async fn handle(&self, event: &StripeSubscriptionDeleted) -> Result<(), EventError> {
        // TODO: Mark tenant_billing as cancelled.
        println!("Subscription deleted: {}", event.subscription_id);
        Ok(())
    }
}

pub struct HandleCheckoutCompleted;

#[async_trait]
impl Listener<StripeCheckoutCompleted> for HandleCheckoutCompleted {
    async fn handle(&self, event: &StripeCheckoutCompleted) -> Result<(), EventError> {
        // TODO: Provision access for the new subscriber.
        println!("Checkout completed: {}", event.session_id);
        Ok(())
    }
}
"#
    .to_string()
}

fn stripe_migration_template(timestamp: &str) -> String {
    format!(
        r#"use sea_orm_migration::prelude::*;

pub struct Migration;

impl MigrationName for Migration {{
    fn name(&self) -> &str {{
        "m{timestamp}_create_tenant_billing_table"
    }}
}}

#[async_trait::async_trait]
impl MigrationTrait for Migration {{
    async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {{
        manager
            .get_connection()
            .execute_unprepared(
                "CREATE TABLE tenant_billing (
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    tenant_id INTEGER NOT NULL UNIQUE,
                    stripe_customer_id TEXT NOT NULL,
                    stripe_subscription_id TEXT,
                    plan TEXT NOT NULL DEFAULT 'free',
                    subscription_status TEXT NOT NULL DEFAULT 'active',
                    trial_ends_at TIMESTAMP,
                    current_period_end TIMESTAMP,
                    cancel_at_period_end BOOLEAN NOT NULL DEFAULT 0,
                    stripe_connect_account_id TEXT,
                    created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
                    updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
                );
                CREATE INDEX idx_tenant_billing_tenant_id ON tenant_billing(tenant_id);",
            )
            .await?;
        Ok(())
    }}

    async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {{
        manager
            .get_connection()
            .execute_unprepared(
                "DROP INDEX IF EXISTS idx_tenant_billing_tenant_id;
                DROP TABLE IF EXISTS tenant_billing;",
            )
            .await?;
        Ok(())
    }}
}}
"#
    )
}

// ---------------------------------------------------------------------------
// File generation helpers
// ---------------------------------------------------------------------------

/// Write a file only if it does not already exist.
/// Returns true if the file was created, false if skipped.
fn write_if_not_exists(path: &Path, content: &str, label: &str) -> bool {
    if path.exists() {
        println!(
            "{} {} already exists, skipping",
            style("Skip:").yellow().bold(),
            label
        );
        return false;
    }
    if let Err(e) = fs::write(path, content) {
        eprintln!(
            "{} Failed to write {}: {}",
            style("Error:").red().bold(),
            label,
            e
        );
        return false;
    }
    println!("{} {}", style("Created:").green().bold(), label);
    true
}

fn ensure_dir(path: &Path) -> bool {
    if path.exists() {
        return true;
    }
    if let Err(e) = fs::create_dir_all(path) {
        eprintln!(
            "{} Failed to create directory {}: {}",
            style("Error:").red().bold(),
            path.display(),
            e
        );
        return false;
    }
    println!(
        "{} Created directory {}",
        style("Created:").green().bold(),
        path.display()
    );
    true
}

fn find_migrations_dir() -> Option<&'static Path> {
    if Path::new("src/migrations").exists() {
        Some(Path::new("src/migrations"))
    } else if Path::new("src/database/migrations").exists() {
        Some(Path::new("src/database/migrations"))
    } else {
        None
    }
}

// ---------------------------------------------------------------------------
// Public API
// ---------------------------------------------------------------------------

/// Execute `ferro make:stripe [--connect]`.
///
/// Generates the Stripe integration scaffold into the current Ferro project.
pub fn execute(connect: bool) {
    println!("Scaffolding Stripe integration...\n");

    let stripe_dir = Path::new("src/stripe");

    if !ensure_dir(stripe_dir) {
        std::process::exit(1);
    }

    // mod.rs
    write_if_not_exists(
        &stripe_dir.join("mod.rs"),
        &stripe_mod_template(connect),
        "src/stripe/mod.rs",
    );

    // webhook.rs
    write_if_not_exists(
        &stripe_dir.join("webhook.rs"),
        &stripe_webhook_template(),
        "src/stripe/webhook.rs",
    );

    // listeners.rs
    write_if_not_exists(
        &stripe_dir.join("listeners.rs"),
        &stripe_listeners_template(),
        "src/stripe/listeners.rs",
    );

    // connect_webhook.rs (only with --connect)
    if connect {
        write_if_not_exists(
            &stripe_dir.join("connect_webhook.rs"),
            &stripe_connect_webhook_template(),
            "src/stripe/connect_webhook.rs",
        );
    }

    // Migration
    generate_migration(connect);

    // Print env hints
    println!("\n{}", style("Add to your .env file:").bold());
    println!("  STRIPE_SECRET_KEY=sk_test_xxx");
    println!("  STRIPE_WEBHOOK_SECRET=whsec_xxx");
    if connect {
        println!("  STRIPE_CONNECT_WEBHOOK_SECRET=whsec_xxx");
        println!("  STRIPE_APPLICATION_FEE_PERCENT=10");
    }

    // Print next steps
    print_next_steps(connect);
}

fn generate_migration(connect: bool) {
    let migrations_dir = match find_migrations_dir() {
        Some(dir) => dir,
        None => {
            println!(
                "{} No migrations directory found — skipping migration generation.",
                style("Note:").yellow().bold()
            );
            println!(
                "{}",
                style("  Create src/migrations/ and re-run make:stripe to generate the migration.")
                    .dim()
            );
            return;
        }
    };

    // Check if billing migration already exists
    if let Ok(entries) = fs::read_dir(migrations_dir) {
        for entry in entries.flatten() {
            let name = entry.file_name().to_string_lossy().to_string();
            if name.contains("tenant_billing") {
                println!(
                    "{} Billing migration already exists: {}",
                    style("Skip:").yellow().bold(),
                    name
                );
                return;
            }
        }
    }

    let timestamp = Local::now().format("%Y%m%d_%H%M%S").to_string();
    let migration_name = format!("m{timestamp}_create_tenant_billing_table");
    let file_path = migrations_dir.join(format!("{migration_name}.rs"));
    let content = stripe_migration_template(&timestamp);

    write_if_not_exists(&file_path, &content, &format!("{}", file_path.display()));

    // Register in mod.rs
    register_migration(migrations_dir, &migration_name, connect);
}

fn register_migration(migrations_dir: &Path, migration_name: &str, _connect: bool) {
    let mod_path = migrations_dir.join("mod.rs");

    if !mod_path.exists() {
        return;
    }

    let content = match fs::read_to_string(&mod_path) {
        Ok(c) => c,
        Err(_) => return,
    };

    let mod_decl = format!("mod {migration_name};");
    if content.contains(&mod_decl) {
        return;
    }

    let mut lines: Vec<String> = content.lines().map(|s| s.to_string()).collect();

    // Find last mod declaration
    let mut last_mod_idx = None;
    for (i, line) in lines.iter().enumerate() {
        if (line.trim().starts_with("mod ") || line.trim().starts_with("pub mod m"))
            && !line.contains("mod tests")
        {
            last_mod_idx = Some(i);
        }
    }

    let insert_idx = match last_mod_idx {
        Some(idx) => idx + 1,
        None => {
            let mut idx = 0;
            for (i, line) in lines.iter().enumerate() {
                if line.contains("sea_orm_migration") || line.is_empty() {
                    idx = i + 1;
                } else if line.starts_with("mod ") || line.starts_with("pub struct") {
                    break;
                }
            }
            idx
        }
    };
    lines.insert(insert_idx, mod_decl);

    // Add to migrations() vec
    let box_new_line = format!("            Box::new({migration_name}::Migration),");
    let mut insert_vec_idx = None;

    for (i, line) in lines.iter().enumerate() {
        if line.contains("vec![]") {
            lines[i] = line.replace("vec![]", &format!("vec![\n{box_new_line}\n        ]"));
            let _ = fs::write(&mod_path, lines.join("\n"));
            return;
        }
        if line.contains("vec![") && !line.contains("vec![]") {
            for (j, inner_line) in lines.iter().enumerate().skip(i + 1) {
                if inner_line.trim() == "]" || inner_line.trim().starts_with(']') {
                    insert_vec_idx = Some(j);
                    break;
                }
            }
            break;
        }
    }

    if let Some(idx) = insert_vec_idx {
        lines.insert(idx, box_new_line);
    }

    let _ = fs::write(&mod_path, lines.join("\n"));
}

fn print_next_steps(connect: bool) {
    println!("\n{}", style("Next steps:").bold());
    println!(
        "\n  {} Call Stripe::init() from your bootstrap.rs:",
        style("1.").dim()
    );
    println!("     {}", style("crate::stripe::init();").cyan());

    println!(
        "\n  {} Register webhook routes in src/routes.rs:",
        style("2.").dim()
    );
    println!(
        "     {}",
        style("use crate::stripe::webhook::stripe_webhook;").cyan()
    );
    println!(
        "     {}",
        style("post!(\"/stripe/webhook\", stripe_webhook)").cyan()
    );
    if connect {
        println!(
            "     {}",
            style("use crate::stripe::connect_webhook::stripe_connect_webhook;").cyan()
        );
        println!(
            "     {}",
            style("post!(\"/stripe/connect/webhook\", stripe_connect_webhook)").cyan()
        );
    }

    println!("\n  {} Run the migration:", style("3.").dim());
    println!("     {}", style("ferro db:migrate").cyan());
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

/// Generate the scaffold files in a temp directory for testing.
#[cfg(test)]
pub fn generate_in_dir(base_dir: &Path, connect: bool) {
    let stripe_dir = base_dir.join("src/stripe");
    fs::create_dir_all(&stripe_dir).unwrap();

    fs::write(stripe_dir.join("mod.rs"), stripe_mod_template(connect)).unwrap();
    fs::write(stripe_dir.join("webhook.rs"), stripe_webhook_template()).unwrap();
    fs::write(stripe_dir.join("listeners.rs"), stripe_listeners_template()).unwrap();

    if connect {
        fs::write(
            stripe_dir.join("connect_webhook.rs"),
            stripe_connect_webhook_template(),
        )
        .unwrap();
    }

    let migrations_dir = base_dir.join("src/migrations");
    fs::create_dir_all(&migrations_dir).unwrap();
    let timestamp = "20260101_000000";
    let migration_name = format!("m{timestamp}_create_tenant_billing_table");
    fs::write(
        migrations_dir.join(format!("{migration_name}.rs")),
        stripe_migration_template(timestamp),
    )
    .unwrap();
}

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

    fn read_file(path: &Path) -> String {
        fs::read_to_string(path).unwrap_or_else(|e| panic!("Failed to read {path:?}: {e}"))
    }

    // --- mod.rs template tests ---

    #[test]
    fn test_mod_template_without_connect() {
        let tmpl = stripe_mod_template(false);
        assert!(tmpl.contains("pub mod webhook;"));
        assert!(tmpl.contains("pub mod listeners;"));
        assert!(!tmpl.contains("pub mod connect_webhook;"));
        assert!(tmpl.contains("use ferro::Stripe;"));
        assert!(tmpl.contains("pub fn init()"));
        assert!(tmpl.contains("ferro::StripeConfig::from_env()"));
        assert!(tmpl.contains("Stripe::init(config);"));
    }

    #[test]
    fn test_mod_template_with_connect() {
        let tmpl = stripe_mod_template(true);
        assert!(tmpl.contains("pub mod webhook;"));
        assert!(tmpl.contains("pub mod listeners;"));
        assert!(tmpl.contains("pub mod connect_webhook;"));
    }

    // --- webhook.rs template tests ---

    #[test]
    fn test_webhook_template_uses_queue_dispatch() {
        let tmpl = stripe_webhook_template();
        // Must use queue_dispatch (not dispatch_event) per locked decision
        assert!(tmpl.contains("ferro::queue_dispatch(job)"));
        assert!(!tmpl.contains("dispatch_event"));
        assert!(tmpl.contains("ferro::verify_webhook("));
        assert!(tmpl.contains("stripe-signature"));
        assert!(tmpl.contains(r#"{"received": true}"#));
    }

    #[test]
    fn test_webhook_template_uses_ferro_imports() {
        let tmpl = stripe_webhook_template();
        assert!(tmpl.contains("use ferro::{"));
        assert!(tmpl.contains("use ferro::ProcessStripeWebhook;"));
    }

    // --- connect_webhook template tests ---

    #[test]
    fn test_connect_webhook_template() {
        let tmpl = stripe_connect_webhook_template();
        assert!(tmpl.contains("stripe_connect_webhook"));
        assert!(tmpl.contains("ProcessStripeWebhook {"));
        assert!(tmpl.contains("ferro::queue_dispatch(job)"));
        assert!(tmpl.contains("connect_webhook_secret"));
    }

    // --- listeners.rs template tests ---

    #[test]
    fn test_listeners_template() {
        let tmpl = stripe_listeners_template();
        assert!(tmpl.contains("StripeSubscriptionUpdated"));
        assert!(tmpl.contains("StripeSubscriptionDeleted"));
        assert!(tmpl.contains("StripeCheckoutCompleted"));
        assert!(tmpl.contains("impl Listener<StripeSubscriptionUpdated> for SyncSubscriptionPlan"));
        assert!(tmpl.contains("async fn handle("));
        assert!(tmpl.contains("use ferro::{async_trait, EventError, Listener};"));
    }

    // --- migration template tests ---

    #[test]
    fn test_migration_sql_schema() {
        let tmpl = stripe_migration_template("20260101_000000");
        assert!(tmpl.contains("CREATE TABLE tenant_billing"));
        assert!(tmpl.contains("tenant_id INTEGER NOT NULL UNIQUE"));
        assert!(tmpl.contains("stripe_customer_id TEXT NOT NULL"));
        assert!(tmpl.contains("stripe_subscription_id TEXT"));
        assert!(tmpl.contains("plan TEXT NOT NULL DEFAULT 'free'"));
        assert!(tmpl.contains("subscription_status TEXT NOT NULL DEFAULT 'active'"));
        assert!(tmpl.contains("trial_ends_at TIMESTAMP"));
        assert!(tmpl.contains("current_period_end TIMESTAMP"));
        assert!(tmpl.contains("cancel_at_period_end BOOLEAN NOT NULL DEFAULT 0"));
        assert!(tmpl.contains("stripe_connect_account_id TEXT"));
        assert!(tmpl.contains("created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP"));
        assert!(tmpl.contains("updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP"));
        assert!(
            tmpl.contains("CREATE INDEX idx_tenant_billing_tenant_id ON tenant_billing(tenant_id)")
        );
        // Must have a down migration
        assert!(tmpl.contains("DROP TABLE IF EXISTS tenant_billing"));
    }

    #[test]
    fn test_migration_uses_timestamp() {
        let ts = "20260315_120000";
        let tmpl = stripe_migration_template(ts);
        assert!(tmpl.contains(&format!("m{ts}_create_tenant_billing_table")));
    }

    // --- file generation tests ---

    #[test]
    fn test_generates_required_files_without_connect() {
        let tmp = TempDir::new().unwrap();
        generate_in_dir(tmp.path(), false);

        let stripe_dir = tmp.path().join("src/stripe");
        assert!(
            stripe_dir.exists(),
            "src/stripe directory should be created"
        );
        assert!(
            stripe_dir.join("mod.rs").exists(),
            "mod.rs should be created"
        );
        assert!(
            stripe_dir.join("webhook.rs").exists(),
            "webhook.rs should be created"
        );
        assert!(
            stripe_dir.join("listeners.rs").exists(),
            "listeners.rs should be created"
        );
        assert!(
            !stripe_dir.join("connect_webhook.rs").exists(),
            "connect_webhook.rs should NOT be created without --connect"
        );
    }

    #[test]
    fn test_generates_connect_webhook_with_connect_flag() {
        let tmp = TempDir::new().unwrap();
        generate_in_dir(tmp.path(), true);

        let stripe_dir = tmp.path().join("src/stripe");
        assert!(
            stripe_dir.join("connect_webhook.rs").exists(),
            "connect_webhook.rs should be created with --connect"
        );

        // Verify connect webhook content
        let content = read_file(&stripe_dir.join("connect_webhook.rs"));
        assert!(content.contains("stripe_connect_webhook"));
        assert!(content.contains("ProcessStripeWebhook {"));
    }

    #[test]
    fn test_does_not_overwrite_existing_files() {
        let tmp = TempDir::new().unwrap();
        let stripe_dir = tmp.path().join("src/stripe");
        fs::create_dir_all(&stripe_dir).unwrap();

        // Write an existing mod.rs with custom content
        let existing_content = "// Custom user content that should not be overwritten\n";
        fs::write(stripe_dir.join("mod.rs"), existing_content).unwrap();

        // Generate — should skip mod.rs
        generate_in_dir(tmp.path(), false);

        // mod.rs should still have original content
        let content = read_file(&stripe_dir.join("mod.rs"));
        // Since generate_in_dir writes unconditionally for tests (it's a test helper),
        // we test the write_if_not_exists logic directly:
        let out_path = tmp.path().join("test_file.txt");
        write_if_not_exists(&out_path, "new content", "test_file.txt");
        assert_eq!(fs::read_to_string(&out_path).unwrap(), "new content");

        // Writing again should not change the content
        write_if_not_exists(&out_path, "overwritten content", "test_file.txt");
        assert_eq!(
            fs::read_to_string(&out_path).unwrap(),
            "new content",
            "write_if_not_exists must not overwrite existing files"
        );
        drop(content); // use the variable
    }

    #[test]
    fn test_migration_created() {
        let tmp = TempDir::new().unwrap();
        generate_in_dir(tmp.path(), false);

        let migrations_dir = tmp.path().join("src/migrations");
        assert!(migrations_dir.exists());

        // Verify at least one migration file exists with tenant_billing content
        let entries: Vec<_> = fs::read_dir(&migrations_dir)
            .unwrap()
            .filter_map(|e| e.ok())
            .collect();
        assert!(
            !entries.is_empty(),
            "At least one migration file should be created"
        );

        let has_billing = entries.iter().any(|e| {
            let name = e.file_name().to_string_lossy().to_string();
            name.contains("tenant_billing")
        });
        assert!(has_billing, "A tenant_billing migration should be created");
    }

    #[test]
    fn test_generated_webhook_uses_queue_not_events() {
        let tmp = TempDir::new().unwrap();
        generate_in_dir(tmp.path(), false);

        let webhook_path = tmp.path().join("src/stripe/webhook.rs");
        let content = read_file(&webhook_path);

        // Must use queue_dispatch, not dispatch_event
        assert!(
            content.contains("queue_dispatch"),
            "webhook.rs must use queue_dispatch (not dispatch_event)"
        );
        assert!(
            !content.contains("dispatch_event"),
            "webhook.rs must NOT use dispatch_event"
        );
    }
}