dwctl 8.39.0

The Doubleword Control Layer - A self-hostable observability and analytics platform for LLM applications
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
//! Email service for sending password reset emails and notifications

use crate::notifications::{BatchNotificationInfo, BatchOutcome};
use crate::{config::Config, errors::Error};
use lettre::{
    AsyncFileTransport, AsyncSmtpTransport, AsyncTransport, Message, Tokio1Executor,
    message::{Mailbox, header::ContentType},
    transport::smtp::authentication::Credentials,
};
use minijinja::{Environment, context};
use std::path::Path;

struct EmailTemplates {
    password_reset: String,
    batch_complete: String,
    first_batch: String,
    low_balance: String,
    auto_topup_success: String,
    auto_topup_failed: String,
    auto_topup_limit_reached: String,
    org_invite: String,
}

impl EmailTemplates {
    fn embedded() -> Self {
        Self {
            password_reset: include_str!("../default_templates/password_reset.html").to_string(),
            batch_complete: include_str!("../default_templates/batch_complete.html").to_string(),
            first_batch: include_str!("../default_templates/first_batch.html").to_string(),
            low_balance: include_str!("../default_templates/low_balance.html").to_string(),
            auto_topup_success: include_str!("../default_templates/auto_topup_success.html").to_string(),
            auto_topup_failed: include_str!("../default_templates/auto_topup_failed.html").to_string(),
            auto_topup_limit_reached: include_str!("../default_templates/auto_topup_limit_reached.html").to_string(),
            org_invite: include_str!("../default_templates/org_invite.html").to_string(),
        }
    }

    fn load_from_dir(dir: &Path) -> Self {
        let embedded = Self::embedded();

        let load = |name: &str, fallback: String| -> String {
            let path = dir.join(name);
            match std::fs::read_to_string(&path) {
                Ok(content) => content,
                Err(_) => {
                    tracing::debug!("Email template {name} not found in custom dir, using embedded default");
                    fallback
                }
            }
        };

        Self {
            password_reset: load("password_reset.html", embedded.password_reset),
            batch_complete: load("batch_complete.html", embedded.batch_complete),
            first_batch: load("first_batch.html", embedded.first_batch),
            low_balance: load("low_balance.html", embedded.low_balance),
            auto_topup_success: load("auto_topup_success.html", embedded.auto_topup_success),
            auto_topup_failed: load("auto_topup_failed.html", embedded.auto_topup_failed),
            auto_topup_limit_reached: load("auto_topup_limit_reached.html", embedded.auto_topup_limit_reached),
            org_invite: load("org_invite.html", embedded.org_invite),
        }
    }
}

pub struct EmailService {
    transport: EmailTransport,
    from_email: String,
    from_name: String,
    base_url: String,
    reply_to: Option<String>,
    templates: EmailTemplates,
}

enum EmailTransport {
    Smtp(AsyncSmtpTransport<Tokio1Executor>),
    File(AsyncFileTransport<Tokio1Executor>),
}

impl EmailService {
    pub fn new(config: &Config) -> Result<Self, Error> {
        let email_config = &config.email;

        let transport = match &email_config.transport {
            crate::config::EmailTransportConfig::Smtp {
                host,
                port,
                username,
                password,
                use_tls,
            } => {
                // Use SMTP transport
                if !use_tls {
                    tracing::warn!("SMTP TLS is disabled - this is not recommended for production");
                }

                let smtp_builder = if *use_tls {
                    AsyncSmtpTransport::<Tokio1Executor>::starttls_relay(host)
                } else {
                    Ok(AsyncSmtpTransport::<Tokio1Executor>::builder_dangerous(host))
                }
                .map_err(|e| Error::Internal {
                    operation: format!("create SMTP transport: {e}"),
                })?
                .port(*port)
                .credentials(Credentials::new(username.clone(), password.clone()));

                EmailTransport::Smtp(smtp_builder.build())
            }
            crate::config::EmailTransportConfig::File { path } => {
                // Use file transport for development/testing
                let emails_dir = Path::new(path);
                if !emails_dir.exists() {
                    std::fs::create_dir_all(emails_dir).map_err(|e| Error::Internal {
                        operation: format!("create emails directory: {e}"),
                    })?;
                }
                let file_transport = AsyncFileTransport::<Tokio1Executor>::new(emails_dir);
                EmailTransport::File(file_transport)
            }
        };

        let templates = match &email_config.templates_dir {
            Some(dir) => EmailTemplates::load_from_dir(Path::new(dir)),
            None => EmailTemplates::embedded(),
        };

        Ok(Self {
            transport,
            from_email: email_config.from_email.clone(),
            from_name: email_config.from_name.clone(),
            base_url: config.dashboard_url.clone(),
            reply_to: email_config.reply_to.clone(),
            templates,
        })
    }

    pub async fn send_password_reset_email(
        &self,
        to_email: &str,
        to_name: Option<&str>,
        token_id: &uuid::Uuid,
        token: &str,
    ) -> Result<(), Error> {
        let reset_link = format!("{}/reset-password?id={}&token={}", self.base_url, token_id, token);

        let subject = "Password Reset Request";
        let name = to_name.unwrap_or("User");
        let body = self.render_password_reset_body(name, &reset_link).map_err(|e| Error::Internal {
            operation: format!("render email template: {e}"),
        })?;

        self.send_email(to_email, to_name, subject, &body).await
    }

    async fn send_email(&self, to_email: &str, to_name: Option<&str>, subject: &str, body: &str) -> Result<(), Error> {
        // Create from mailbox
        let from_address = self.from_email.parse().map_err(|e| Error::Internal {
            operation: format!("Failed to parse from email: {e}"),
        })?;
        let from = Mailbox::new(Some(self.from_name.clone()), from_address);

        // Create to mailbox
        let to_address = to_email.parse().map_err(|e| Error::Internal {
            operation: format!("Failed to parse to email: {e}"),
        })?;
        let to = Mailbox::new(to_name.map(|n| n.to_string()), to_address);

        let mut builder = Message::builder().from(from).to(to).subject(subject).header(ContentType::TEXT_HTML);

        if let Some(ref reply_to_email) = self.reply_to {
            let reply_to_address = reply_to_email.parse().map_err(|e| Error::Internal {
                operation: format!("Failed to parse reply-to email: {e}"),
            })?;
            let reply_to = Mailbox::new(Some(self.from_name.clone()), reply_to_address);
            builder = builder.reply_to(reply_to);
        }

        let message = builder.body(body.to_string()).map_err(|e| Error::Internal {
            operation: format!("build email message: {e}"),
        })?;

        self.dispatch(message).await
    }

    /// Send a pre-built message via the configured transport.
    async fn dispatch(&self, message: Message) -> Result<(), Error> {
        match &self.transport {
            EmailTransport::Smtp(smtp) => {
                smtp.send(message).await.map_err(|e| Error::Internal {
                    operation: format!("send SMTP email: {e}"),
                })?;
            }
            EmailTransport::File(file) => {
                file.send(message).await.map_err(|e| Error::Internal {
                    operation: format!("send file email: {e}"),
                })?;
            }
        }

        Ok(())
    }

    pub async fn send_batch_completion_email(
        &self,
        to_email: &str,
        to_name: Option<&str>,
        info: &BatchNotificationInfo,
        first_batch: bool,
    ) -> Result<(), Error> {
        let status_text = match info.outcome {
            BatchOutcome::Completed => "completed",
            BatchOutcome::PartiallyCompleted => "completed with errors",
            BatchOutcome::Failed => "failed",
        };
        let subject = if first_batch {
            format!("Your first Doubleword batch has {status_text}")
        } else {
            format!("Batch {} — {}", &info.batch_id[..8.min(info.batch_id.len())], status_text)
        };
        let name = to_name.unwrap_or("User");
        let body = self
            .render_batch_completion_body(name.to_string(), info, first_batch)
            .map_err(|e| Error::Internal {
                operation: format!("render email template: {e}"),
            })?;
        self.send_email(to_email, to_name, &subject, &body).await
    }

    pub fn render_batch_completion_body(
        &self,
        to_name: String,
        info: &BatchNotificationInfo,
        first_batch: bool,
    ) -> Result<String, minijinja::Error> {
        let template_src = if first_batch {
            &self.templates.first_batch
        } else {
            &self.templates.batch_complete
        };
        let mut env = Environment::new();
        env.add_template("email", template_src)?;

        let (outcome_label, outcome_icon, header_color, outcome_message) = match info.outcome {
            BatchOutcome::Completed => ("Completed", "✓", "#16a34a", "Your batch has finished processing successfully."),
            BatchOutcome::PartiallyCompleted => (
                "Completed with some failures",
                "âš ",
                "#d97706",
                "Your batch has finished processing, but some requests failed.",
            ),
            BatchOutcome::Failed => ("Failed", "✗", "#dc2626", "There was a problem processing your batch."),
        };

        let duration = info
            .finished_at
            .map(|finished| {
                let dur = finished - info.created_at;
                let total_secs = dur.num_seconds();
                if total_secs < 60 {
                    format!("{total_secs}s")
                } else if total_secs < 3600 {
                    format!("{}m {}s", total_secs / 60, total_secs % 60)
                } else {
                    format!("{}h {}m", total_secs / 3600, (total_secs % 3600) / 60)
                }
            })
            .unwrap_or_default();

        let base = self.base_url.trim_end_matches('/');
        let dashboard_link = format!("{base}/batches/{}", info.batch_id);
        let profile_link = format!("{base}/profile");
        let priority = if info.completion_window == "1h" { "Priority" } else { "Standard" };

        env.get_template("email")?.render(context! {
            to_name,
            batch_id => &info.batch_id,
            model => &info.model,
            endpoint => &info.endpoint,
            outcome_label,
            outcome_icon,
            outcome_message,
            header_color,
            created_at => info.created_at.format("%b %d, %Y %H:%M UTC").to_string(),
            finished_at => info.finished_at.map(|t| t.format("%b %d, %Y %H:%M UTC").to_string()).unwrap_or_default(),
            duration,
            completed_requests => info.completed_requests,
            failed_requests => info.failed_requests,
            total_requests => info.total_requests,
            dashboard_link,
            profile_link,
            priority,
            completion_window => &info.completion_window,
            filename => info.filename.as_deref().unwrap_or(""),
            description => info.description.as_deref().unwrap_or(""),
            from_name => &self.from_name,
            reply_to => self.reply_to.as_deref().unwrap_or(&self.from_email),
        })
    }

    fn render_password_reset_body(&self, to_name: &str, reset_link: &str) -> Result<String, minijinja::Error> {
        let mut env = Environment::new();
        env.add_template("email", &self.templates.password_reset)?;

        env.get_template("email")?.render(context! {
            to_name,
            reset_link,
        })
    }

    pub async fn send_low_balance_email(
        &self,
        to_email: &str,
        to_name: Option<&str>,
        balance: &rust_decimal::Decimal,
    ) -> Result<(), Error> {
        let subject = "Your balance is running low";
        let name = to_name.unwrap_or("User");
        let body = self.render_low_balance_body(name, balance).map_err(|e| Error::Internal {
            operation: format!("render email template: {e}"),
        })?;
        self.send_email(to_email, to_name, subject, &body).await
    }

    fn render_low_balance_body(&self, to_name: &str, balance: &rust_decimal::Decimal) -> Result<String, minijinja::Error> {
        let mut env = Environment::new();
        env.add_template("email", &self.templates.low_balance)?;

        let base = self.base_url.trim_end_matches('/');
        let dashboard_link = format!("{base}/cost-management");
        let profile_link = format!("{base}/profile");

        env.get_template("email")?.render(context! {
            to_name,
            balance => format!("{:.2}", balance),
            dashboard_link,
            profile_link,
            from_name => &self.from_name,
            reply_to => self.reply_to.as_deref().unwrap_or(&self.from_email),
        })
    }

    pub async fn send_auto_topup_success_email(
        &self,
        to_email: &str,
        to_name: Option<&str>,
        amount: &rust_decimal::Decimal,
        threshold: &rust_decimal::Decimal,
        new_balance: &rust_decimal::Decimal,
    ) -> Result<(), Error> {
        let subject = format!("Auto top-up: ${:.2} added to your account", amount);
        let name = to_name.unwrap_or("User");
        let body = self
            .render_auto_topup_body(&self.templates.auto_topup_success, name, amount, threshold, Some(new_balance))
            .map_err(|e| Error::Internal {
                operation: format!("render email template: {e}"),
            })?;
        self.send_email(to_email, to_name, &subject, &body).await
    }

    pub async fn send_auto_topup_failed_email(
        &self,
        to_email: &str,
        to_name: Option<&str>,
        amount: &rust_decimal::Decimal,
        threshold: &rust_decimal::Decimal,
    ) -> Result<(), Error> {
        let subject = "Auto top-up failed — action required";
        let name = to_name.unwrap_or("User");
        let body = self
            .render_auto_topup_body(&self.templates.auto_topup_failed, name, amount, threshold, None)
            .map_err(|e| Error::Internal {
                operation: format!("render email template: {e}"),
            })?;
        self.send_email(to_email, to_name, subject, &body).await
    }

    pub async fn send_auto_topup_limit_reached_email(
        &self,
        to_email: &str,
        to_name: Option<&str>,
        monthly_limit: &rust_decimal::Decimal,
        balance: &rust_decimal::Decimal,
    ) -> Result<(), Error> {
        let subject = format!("Auto top-up monthly limit of ${:.2} reached", monthly_limit);
        let name = to_name.unwrap_or("User");

        let mut env = Environment::new();
        env.add_template("email", &self.templates.auto_topup_limit_reached)
            .map_err(|e| Error::Internal {
                operation: format!("add email template: {e}"),
            })?;

        let base = self.base_url.trim_end_matches('/');
        let dashboard_link = format!("{base}/cost-management");
        let profile_link = format!("{base}/profile");

        let body = env
            .get_template("email")
            .map_err(|e| Error::Internal {
                operation: format!("get email template: {e}"),
            })?
            .render(context! {
                to_name => name,
                monthly_limit => format!("{:.2}", monthly_limit),
                balance => format!("{:.2}", balance),
                dashboard_link,
                profile_link,
            })
            .map_err(|e| Error::Internal {
                operation: format!("render email template: {e}"),
            })?;

        self.send_email(to_email, to_name, &subject, &body).await
    }

    fn render_auto_topup_body(
        &self,
        template: &str,
        to_name: &str,
        amount: &rust_decimal::Decimal,
        threshold: &rust_decimal::Decimal,
        new_balance: Option<&rust_decimal::Decimal>,
    ) -> Result<String, minijinja::Error> {
        let mut env = Environment::new();
        env.add_template("email", template)?;

        let base = self.base_url.trim_end_matches('/');
        let dashboard_link = format!("{base}/cost-management");
        let profile_link = format!("{base}/profile");

        env.get_template("email")?.render(context! {
            to_name,
            amount => format!("{:.2}", amount),
            threshold => format!("{:.2}", threshold),
            new_balance => new_balance.map(|b| format!("{:.2}", b)).unwrap_or_default(),
            dashboard_link,
            profile_link,
        })
    }

    pub async fn send_org_invite_email(
        &self,
        to_email: &str,
        org_name: &str,
        inviter_name: &str,
        role: &str,
        invite_link: &str,
    ) -> Result<(), Error> {
        let subject = format!("You've been invited to join {org_name}");
        let body = self
            .render_org_invite_body(org_name, inviter_name, role, invite_link)
            .map_err(|e| Error::Internal {
                operation: format!("render email template: {e}"),
            })?;

        self.send_email(to_email, None, &subject, &body).await
    }

    /// Send a support request email to the configured support address, with reply-to set to the user's email.
    pub async fn send_support_request(
        &self,
        support_email: &str,
        user_email: &str,
        user_name: Option<&str>,
        subject: &str,
        message: &str,
    ) -> Result<(), Error> {
        // Build from mailbox
        let from_address = self.from_email.parse().map_err(|e| Error::Internal {
            operation: format!("Failed to parse from email: {e}"),
        })?;
        let from = Mailbox::new(Some(self.from_name.clone()), from_address);

        // Build to mailbox (support address)
        let to_address = support_email.parse().map_err(|e| Error::Internal {
            operation: format!("Failed to parse support email: {e}"),
        })?;
        let to = Mailbox::new(Some("Doubleword Support".to_string()), to_address);

        // Reply-to is the user's email
        let reply_to_address = user_email.parse().map_err(|e| Error::Internal {
            operation: format!("Failed to parse user email for reply-to: {e}"),
        })?;
        let reply_to = Mailbox::new(user_name.map(|n| n.to_string()), reply_to_address);

        let display_name = user_name.unwrap_or(user_email);
        let body = format!("Support request from {} ({}):\n\n{}", display_name, user_email, message,);

        let msg = Message::builder()
            .from(from)
            .to(to)
            .reply_to(reply_to)
            .subject(subject)
            .header(ContentType::TEXT_PLAIN)
            .body(body)
            .map_err(|e| Error::Internal {
                operation: format!("build support email message: {e}"),
            })?;

        self.dispatch(msg).await
    }

    fn render_org_invite_body(
        &self,
        org_name: &str,
        inviter_name: &str,
        role: &str,
        invite_link: &str,
    ) -> Result<String, minijinja::Error> {
        let mut env = Environment::new();
        env.add_template("email", &self.templates.org_invite)?;

        env.get_template("email")?.render(context! {
            org_name,
            inviter_name,
            role,
            invite_link,
        })
    }
}

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

    fn test_info(
        outcome: BatchOutcome,
        total: i64,
        completed: i64,
        failed: i64,
        filename: Option<&str>,
        description: Option<&str>,
    ) -> BatchNotificationInfo {
        BatchNotificationInfo {
            batch_id: "abcd1234-5678-90ab-cdef-1234567890ab".to_string(),
            batch_uuid: uuid::Uuid::nil(),
            user_id: uuid::Uuid::nil(),
            endpoint: "/v1/chat/completions".to_string(),
            model: "gpt-4o".to_string(),
            outcome,
            created_at: chrono::Utc::now(),
            finished_at: Some(chrono::Utc::now()),
            total_requests: total,
            completed_requests: completed,
            failed_requests: failed,
            cancelled_requests: 0,
            completion_window: "24h".to_string(),
            filename: filename.map(String::from),
            description: description.map(String::from),
            output_file_id: None,
            error_file_id: None,
        }
    }

    #[tokio::test]
    async fn test_email_service_creation() {
        let config = create_test_config();
        let email_service = EmailService::new(&config);
        assert!(email_service.is_ok());
    }

    #[tokio::test]
    async fn test_password_reset_email_body() {
        let config = create_test_config();
        let email_service = EmailService::new(&config).unwrap();

        let body = email_service
            .render_password_reset_body("John Doe", "https://example.com/reset?token=abc123")
            .unwrap();

        assert!(body.contains("Hello John Doe,"));
        assert!(body.contains("https://example.com/reset?token=abc123"));
        assert!(body.contains("Reset your password"));
    }

    #[tokio::test]
    async fn test_password_reset_email_body_no_name() {
        let config = create_test_config();
        let email_service = EmailService::new(&config).unwrap();

        let body = email_service
            .render_password_reset_body("User", "https://example.com/reset?token=abc123")
            .unwrap();

        assert!(body.contains("Hello User,"));
        assert!(body.contains("https://example.com/reset?token=abc123"));
    }

    #[tokio::test]
    async fn test_first_batch_email_body_completed() {
        let config = create_test_config();
        let email_service = EmailService::new(&config).unwrap();

        let info = test_info(BatchOutcome::Completed, 50, 50, 0, Some("first-run.jsonl"), None);

        let body = email_service.render_batch_completion_body("Bob".into(), &info, true).unwrap();

        assert!(body.contains("Hi Bob,"));
        assert!(body.contains("first batch has completed"));
        assert!(body.contains("http://localhost:3001/batches/abcd1234-5678-90ab-cdef-1234567890ab"));
    }

    #[tokio::test]
    async fn test_batch_completion_email_body_completed() {
        let config = create_test_config();
        let email_service = EmailService::new(&config).unwrap();

        let info = test_info(
            BatchOutcome::Completed,
            100,
            100,
            0,
            Some("input.jsonl"),
            Some("Weekly report generation"),
        );

        let body = email_service.render_batch_completion_body("Alice".into(), &info, false).unwrap();

        assert!(body.contains("Hi Alice,"));
        assert!(body.contains("Completed"));
        assert!(body.contains("finished processing successfully"));
        assert!(body.contains("/v1/chat/completions"));
        assert!(body.contains("gpt-4o"));
        assert!(body.contains("100"));
        assert!(body.contains("http://localhost:3001/batches/abcd1234-5678-90ab-cdef-1234567890ab"));
        assert!(body.contains("http://localhost:3001/profile"));
        assert!(body.contains("24h"));
        assert!(body.contains("input.jsonl"));
        assert!(body.contains("Weekly report generation"));
    }

    #[tokio::test]
    async fn test_batch_completion_email_body_partially_completed() {
        let config = create_test_config();
        let email_service = EmailService::new(&config).unwrap();

        let info = test_info(BatchOutcome::PartiallyCompleted, 100, 98, 2, Some("input.jsonl"), None);

        let body = email_service.render_batch_completion_body("Alice".into(), &info, false).unwrap();

        assert!(body.contains("Completed with some failures"));
        assert!(body.contains("some requests failed"));
        assert!(body.contains(">2<"));
    }

    /// Exercises the full send_email path (mailbox construction + message build + file transport)
    /// with various name/email combinations that could trip up RFC 5322 parsing.
    #[tokio::test]
    async fn test_send_email_with_various_recipient_names() {
        let config = create_test_config();
        let email_service = EmailService::new(&config).unwrap();

        let cases: Vec<(Option<&str>, &str)> = vec![
            // Normal name
            (Some("Alice Smith"), "alice@example.com"),
            // No display name
            (None, "alice@example.com"),
            // Email address as display name (the bug that hit production)
            (Some("josh.cowan@doubleword.ai"), "josh.cowan@doubleword.ai"),
            // Name with special RFC 5322 characters
            (Some("O'Brien, James"), "james@example.com"),
            // Name with parentheses
            (Some("Alice (Engineering)"), "alice@example.com"),
            // Name with quotes
            (Some("Alice \"The Boss\" Smith"), "alice@example.com"),
            // Unicode name
            (Some("Müller, François"), "francois@example.com"),
            // Single word
            (Some("admin"), "admin@example.com"),
            // Empty string display name
            (Some(""), "alice@example.com"),
        ];

        for (name, email) in cases {
            let result = email_service.send_email(email, name, "Test Subject", "<p>Hello</p>").await;
            assert!(
                result.is_ok(),
                "send_email failed for name={name:?}, email={email:?}: {:?}",
                result.unwrap_err()
            );
        }
    }

    #[tokio::test]
    async fn test_batch_completion_email_body_failed() {
        let config = create_test_config();
        let email_service = EmailService::new(&config).unwrap();

        let info = test_info(BatchOutcome::Failed, 100, 0, 100, None, None);

        let body = email_service.render_batch_completion_body("Alice".into(), &info, false).unwrap();

        assert!(body.contains("Failed"));
        assert!(body.contains("problem processing your batch"));
        assert!(body.contains(">100<"));
    }

    #[tokio::test]
    async fn test_auto_topup_success_email_body() {
        let config = create_test_config();
        let email_service = EmailService::new(&config).unwrap();

        let amount = rust_decimal::Decimal::new(2500, 2); // $25.00
        let threshold = rust_decimal::Decimal::new(500, 2); // $5.00
        let new_balance = rust_decimal::Decimal::new(3000, 2); // $30.00

        let body = email_service
            .render_auto_topup_body(
                &email_service.templates.auto_topup_success,
                "Alice",
                &amount,
                &threshold,
                Some(&new_balance),
            )
            .unwrap();

        assert!(body.contains("Alice"), "Should contain user name");
        assert!(body.contains("25.00"), "Should contain amount");
        assert!(body.contains("5.00"), "Should contain threshold");
        assert!(body.contains("30.00"), "Should contain new balance");
        assert!(body.contains("cost-management"), "Should contain dashboard link");
    }

    #[tokio::test]
    async fn test_auto_topup_failed_email_body() {
        let config = create_test_config();
        let email_service = EmailService::new(&config).unwrap();

        let amount = rust_decimal::Decimal::new(2500, 2); // $25.00
        let threshold = rust_decimal::Decimal::new(500, 2); // $5.00

        let body = email_service
            .render_auto_topup_body(&email_service.templates.auto_topup_failed, "Bob", &amount, &threshold, None)
            .unwrap();

        assert!(body.contains("Bob"), "Should contain user name");
        assert!(body.contains("25.00"), "Should contain amount");
        assert!(body.contains("5.00"), "Should contain threshold");
        assert!(body.contains("cost-management"), "Should contain dashboard link");
    }

    #[tokio::test]
    async fn test_send_support_request() {
        let config = create_test_config();
        let email_service = EmailService::new(&config).unwrap();

        let result = email_service
            .send_support_request(
                "support@doubleword.ai",
                "alice@example.com",
                Some("Alice Smith"),
                "Help with API keys",
                "I can't generate a new API key from the dashboard.",
            )
            .await;

        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_send_support_request_no_name() {
        let config = create_test_config();
        let email_service = EmailService::new(&config).unwrap();

        let result = email_service
            .send_support_request(
                "support@doubleword.ai",
                "alice@example.com",
                None,
                "Help with API keys",
                "I can't generate a new API key from the dashboard.",
            )
            .await;

        assert!(result.is_ok());
    }
}