ferro-notifications 0.2.5

Multi-channel notification system for Ferro framework
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
//! Notification dispatcher for sending notifications through channels.

use crate::channel::Channel;
use crate::channels::{MailMessage, SlackMessage};
use crate::notifiable::Notifiable;
use crate::notification::Notification;
use crate::Error;
use serde::Serialize;
use std::env;
use std::sync::OnceLock;
use tracing::{error, info};

/// Global notification dispatcher configuration.
static CONFIG: OnceLock<NotificationConfig> = OnceLock::new();

/// Configuration for the notification dispatcher.
#[derive(Clone, Default)]
pub struct NotificationConfig {
    /// Mail configuration (supports SMTP and Resend drivers).
    pub mail: Option<MailConfig>,
    /// Slack webhook URL.
    pub slack_webhook: Option<String>,
}

/// Mail transport driver.
#[derive(Debug, Clone, Default)]
pub enum MailDriver {
    /// SMTP via lettre (default).
    #[default]
    Smtp,
    /// Resend HTTP API.
    Resend,
}

/// SMTP-specific configuration.
#[derive(Clone)]
pub struct SmtpConfig {
    /// SMTP host.
    pub host: String,
    /// SMTP port.
    pub port: u16,
    /// SMTP username.
    pub username: Option<String>,
    /// SMTP password.
    pub password: Option<String>,
    /// Use TLS.
    pub tls: bool,
}

/// Resend-specific configuration.
#[derive(Clone)]
pub struct ResendConfig {
    /// Resend API key.
    pub api_key: String,
}

/// Mail configuration supporting multiple drivers.
#[derive(Clone)]
pub struct MailConfig {
    /// Which driver to use.
    pub driver: MailDriver,
    /// Default from address (shared across all drivers).
    pub from: String,
    /// Default from name (shared across all drivers).
    pub from_name: Option<String>,
    /// SMTP-specific config (only when driver = Smtp).
    pub smtp: Option<SmtpConfig>,
    /// Resend-specific config (only when driver = Resend).
    pub resend: Option<ResendConfig>,
}

impl NotificationConfig {
    /// Create a new notification config.
    pub fn new() -> Self {
        Self::default()
    }

    /// Create configuration from environment variables.
    ///
    /// Reads the following environment variables:
    /// - Mail: `MAIL_HOST`, `MAIL_PORT`, `MAIL_USERNAME`, `MAIL_PASSWORD`,
    ///   `MAIL_FROM_ADDRESS`, `MAIL_FROM_NAME`, `MAIL_ENCRYPTION`
    /// - Slack: `SLACK_WEBHOOK_URL`
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use ferro_notifications::NotificationConfig;
    ///
    /// // In bootstrap.rs
    /// let config = NotificationConfig::from_env();
    /// NotificationDispatcher::configure(config);
    /// ```
    pub fn from_env() -> Self {
        Self {
            mail: MailConfig::from_env(),
            slack_webhook: env::var("SLACK_WEBHOOK_URL").ok().filter(|s| !s.is_empty()),
        }
    }

    /// Set the mail configuration.
    pub fn mail(mut self, config: MailConfig) -> Self {
        self.mail = Some(config);
        self
    }

    /// Set the Slack webhook URL.
    pub fn slack_webhook(mut self, url: impl Into<String>) -> Self {
        self.slack_webhook = Some(url.into());
        self
    }
}

impl MailConfig {
    /// Create a new SMTP mail config (backwards compatible).
    pub fn new(host: impl Into<String>, port: u16, from: impl Into<String>) -> Self {
        Self {
            driver: MailDriver::Smtp,
            from: from.into(),
            from_name: None,
            smtp: Some(SmtpConfig {
                host: host.into(),
                port,
                username: None,
                password: None,
                tls: true,
            }),
            resend: None,
        }
    }

    /// Create a new Resend mail config.
    pub fn resend(api_key: impl Into<String>, from: impl Into<String>) -> Self {
        Self {
            driver: MailDriver::Resend,
            from: from.into(),
            from_name: None,
            smtp: None,
            resend: Some(ResendConfig {
                api_key: api_key.into(),
            }),
        }
    }

    /// Create mail configuration from environment variables.
    ///
    /// Returns `None` if required variables are missing.
    ///
    /// Reads the following environment variables:
    /// - `MAIL_DRIVER`: "smtp" (default) or "resend"
    /// - `MAIL_FROM_ADDRESS`: Default from email address (required for all drivers)
    /// - `MAIL_FROM_NAME`: Default from name (optional)
    ///
    /// SMTP driver variables:
    /// - `MAIL_HOST`: SMTP server host (required)
    /// - `MAIL_PORT`: SMTP server port (default: 587)
    /// - `MAIL_USERNAME`: SMTP username (optional)
    /// - `MAIL_PASSWORD`: SMTP password (optional)
    /// - `MAIL_ENCRYPTION`: "tls" or "none" (default: "tls")
    ///
    /// Resend driver variables:
    /// - `RESEND_API_KEY`: Resend API key (required)
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use ferro_notifications::MailConfig;
    ///
    /// if let Some(config) = MailConfig::from_env() {
    ///     // Mail is configured
    /// }
    /// ```
    pub fn from_env() -> Option<Self> {
        let from = env::var("MAIL_FROM_ADDRESS")
            .ok()
            .filter(|s| !s.is_empty())?;
        let from_name = env::var("MAIL_FROM_NAME").ok().filter(|s| !s.is_empty());

        let driver_str = env::var("MAIL_DRIVER")
            .ok()
            .filter(|s| !s.is_empty())
            .unwrap_or_else(|| "smtp".into());

        match driver_str.to_lowercase().as_str() {
            "resend" => {
                let api_key = env::var("RESEND_API_KEY").ok().filter(|s| !s.is_empty())?;

                Some(Self {
                    driver: MailDriver::Resend,
                    from,
                    from_name,
                    smtp: None,
                    resend: Some(ResendConfig { api_key }),
                })
            }
            _ => {
                // Default: SMTP (backwards compatible)
                let host = env::var("MAIL_HOST").ok().filter(|s| !s.is_empty())?;

                let port = env::var("MAIL_PORT")
                    .ok()
                    .and_then(|p| p.parse().ok())
                    .unwrap_or(587);

                let username = env::var("MAIL_USERNAME").ok().filter(|s| !s.is_empty());
                let password = env::var("MAIL_PASSWORD").ok().filter(|s| !s.is_empty());

                let tls = env::var("MAIL_ENCRYPTION")
                    .map(|v| v.to_lowercase() != "none")
                    .unwrap_or(true);

                Some(Self {
                    driver: MailDriver::Smtp,
                    from,
                    from_name,
                    smtp: Some(SmtpConfig {
                        host,
                        port,
                        username,
                        password,
                        tls,
                    }),
                    resend: None,
                })
            }
        }
    }

    /// Set SMTP credentials.
    pub fn credentials(mut self, username: impl Into<String>, password: impl Into<String>) -> Self {
        let smtp = self.smtp.get_or_insert(SmtpConfig {
            host: String::new(),
            port: 587,
            username: None,
            password: None,
            tls: true,
        });
        smtp.username = Some(username.into());
        smtp.password = Some(password.into());
        self
    }

    /// Set the from name.
    pub fn from_name(mut self, name: impl Into<String>) -> Self {
        self.from_name = Some(name.into());
        self
    }

    /// Disable TLS (SMTP only).
    pub fn no_tls(mut self) -> Self {
        if let Some(ref mut smtp) = self.smtp {
            smtp.tls = false;
        }
        self
    }
}

/// Resend API email payload.
#[derive(Serialize)]
struct ResendEmailPayload {
    from: String,
    to: Vec<String>,
    subject: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    html: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    text: Option<String>,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    cc: Vec<String>,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    bcc: Vec<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    reply_to: Option<String>,
}

/// The notification dispatcher.
pub struct NotificationDispatcher;

impl NotificationDispatcher {
    /// Configure the global notification dispatcher.
    pub fn configure(config: NotificationConfig) {
        let _ = CONFIG.set(config);
    }

    /// Get the current configuration.
    pub fn config() -> Option<&'static NotificationConfig> {
        CONFIG.get()
    }

    /// Send a notification to a notifiable entity.
    pub async fn send<N, T>(notifiable: &N, notification: T) -> Result<(), Error>
    where
        N: Notifiable + ?Sized,
        T: Notification,
    {
        let channels = notification.via();
        let notification_type = notification.notification_type();

        info!(
            notification = notification_type,
            channels = ?channels,
            "Dispatching notification"
        );

        for channel in channels {
            match channel {
                Channel::Mail => {
                    if let Some(mail) = notification.to_mail() {
                        Self::send_mail(notifiable, &mail).await?;
                    }
                }
                Channel::Database => {
                    if let Some(db_msg) = notification.to_database() {
                        Self::send_database(notifiable, &db_msg).await?;
                    }
                }
                Channel::Slack => {
                    if let Some(slack) = notification.to_slack() {
                        Self::send_slack(notifiable, &slack).await?;
                    }
                }
                Channel::Sms | Channel::Push => {
                    // Not implemented yet
                    info!(channel = %channel, "Channel not implemented");
                }
            }
        }

        Ok(())
    }

    /// Send a mail notification, dispatching to the configured driver.
    async fn send_mail<N: Notifiable + ?Sized>(
        notifiable: &N,
        message: &MailMessage,
    ) -> Result<(), Error> {
        let to = notifiable
            .route_notification_for(Channel::Mail)
            .ok_or_else(|| Error::ChannelNotAvailable("No mail route configured".into()))?;

        let config = CONFIG
            .get()
            .and_then(|c| c.mail.as_ref())
            .ok_or_else(|| Error::ChannelNotAvailable("Mail not configured".into()))?;

        info!(to = %to, subject = %message.subject, "Sending mail notification");

        match config.driver {
            MailDriver::Smtp => Self::send_mail_smtp(&to, message, config).await,
            MailDriver::Resend => Self::send_mail_resend(&to, message, config).await,
        }
    }

    /// Send mail via SMTP using lettre.
    async fn send_mail_smtp(
        to: &str,
        message: &MailMessage,
        config: &MailConfig,
    ) -> Result<(), Error> {
        let smtp = config
            .smtp
            .as_ref()
            .ok_or_else(|| Error::mail("SMTP config missing for SMTP driver"))?;

        use lettre::message::{header::ContentType, Mailbox};
        use lettre::transport::smtp::authentication::Credentials;
        use lettre::{AsyncSmtpTransport, AsyncTransport, Message, Tokio1Executor};

        let from: Mailbox = if let Some(ref name) = config.from_name {
            format!("{} <{}>", name, config.from)
                .parse()
                .map_err(|e| Error::mail(format!("Invalid from address: {e}")))?
        } else {
            config
                .from
                .parse()
                .map_err(|e| Error::mail(format!("Invalid from address: {e}")))?
        };

        let to_mailbox: Mailbox = to
            .parse()
            .map_err(|e| Error::mail(format!("Invalid to address: {e}")))?;

        let mut email_builder = Message::builder()
            .from(from)
            .to(to_mailbox)
            .subject(&message.subject);

        if let Some(ref reply_to) = message.reply_to {
            let reply_to_mailbox: Mailbox = reply_to
                .parse()
                .map_err(|e| Error::mail(format!("Invalid reply-to address: {e}")))?;
            email_builder = email_builder.reply_to(reply_to_mailbox);
        }

        for cc in &message.cc {
            let cc_mailbox: Mailbox = cc
                .parse()
                .map_err(|e| Error::mail(format!("Invalid CC address: {e}")))?;
            email_builder = email_builder.cc(cc_mailbox);
        }

        for bcc in &message.bcc {
            let bcc_mailbox: Mailbox = bcc
                .parse()
                .map_err(|e| Error::mail(format!("Invalid BCC address: {e}")))?;
            email_builder = email_builder.bcc(bcc_mailbox);
        }

        let email = if let Some(ref html) = message.html {
            email_builder
                .header(ContentType::TEXT_HTML)
                .body(html.clone())
                .map_err(|e| Error::mail(format!("Failed to build email: {e}")))?
        } else {
            email_builder
                .header(ContentType::TEXT_PLAIN)
                .body(message.body.clone())
                .map_err(|e| Error::mail(format!("Failed to build email: {e}")))?
        };

        let transport = if smtp.tls {
            AsyncSmtpTransport::<Tokio1Executor>::relay(&smtp.host)
                .map_err(|e| Error::mail(format!("Failed to create transport: {e}")))?
        } else {
            AsyncSmtpTransport::<Tokio1Executor>::builder_dangerous(&smtp.host)
        };

        let transport = transport.port(smtp.port);

        let transport = if let (Some(ref user), Some(ref pass)) = (&smtp.username, &smtp.password) {
            transport.credentials(Credentials::new(user.clone(), pass.clone()))
        } else {
            transport
        };

        let mailer = transport.build();

        mailer
            .send(email)
            .await
            .map_err(|e| Error::mail(format!("Failed to send email: {e}")))?;

        info!(to = %to, "Mail notification sent via SMTP");
        Ok(())
    }

    /// Send mail via Resend HTTP API.
    async fn send_mail_resend(
        to: &str,
        message: &MailMessage,
        config: &MailConfig,
    ) -> Result<(), Error> {
        let resend = config
            .resend
            .as_ref()
            .ok_or_else(|| Error::mail("Resend config missing for Resend driver"))?;

        let from = message.from.clone().unwrap_or_else(|| {
            if let Some(ref name) = config.from_name {
                format!("{} <{}>", name, config.from)
            } else {
                config.from.clone()
            }
        });

        let payload = ResendEmailPayload {
            from,
            to: vec![to.to_string()],
            subject: message.subject.clone(),
            html: message.html.clone(),
            text: if message.html.is_some() {
                None
            } else {
                Some(message.body.clone())
            },
            cc: message.cc.clone(),
            bcc: message.bcc.clone(),
            reply_to: message.reply_to.clone(),
        };

        let client = reqwest::Client::new();
        let response = client
            .post("https://api.resend.com/emails")
            .bearer_auth(&resend.api_key)
            .json(&payload)
            .send()
            .await
            .map_err(|e| Error::mail(format!("Resend HTTP request failed: {e}")))?;

        if !response.status().is_success() {
            let status = response.status();
            let body = response.text().await.unwrap_or_default();
            error!(status = %status, body = %body, "Resend API error");
            return Err(Error::mail(format!("Resend API error {status}: {body}")));
        }

        info!(to = %to, "Mail notification sent via Resend");
        Ok(())
    }

    /// Send a database notification.
    async fn send_database<N: Notifiable + ?Sized>(
        notifiable: &N,
        message: &crate::channels::DatabaseMessage,
    ) -> Result<(), Error> {
        let notifiable_id = notifiable.notifiable_id();
        let notifiable_type = notifiable.notifiable_type();

        info!(
            notifiable_id = %notifiable_id,
            notification_type = %message.notification_type,
            "Storing database notification"
        );

        // In a real implementation, this would store to the database.
        // For now, we just log it. The user should implement DatabaseNotificationStore.
        info!(
            notifiable_id = %notifiable_id,
            notifiable_type = %notifiable_type,
            notification_type = %message.notification_type,
            data = ?message.data,
            "Database notification stored (placeholder)"
        );

        Ok(())
    }

    /// Send a Slack notification.
    async fn send_slack<N: Notifiable + ?Sized>(
        notifiable: &N,
        message: &SlackMessage,
    ) -> Result<(), Error> {
        let webhook_url = notifiable
            .route_notification_for(Channel::Slack)
            .or_else(|| CONFIG.get().and_then(|c| c.slack_webhook.clone()))
            .ok_or_else(|| Error::ChannelNotAvailable("No Slack webhook configured".into()))?;

        info!(channel = ?message.channel, "Sending Slack notification");

        let client = reqwest::Client::new();
        let response = client
            .post(&webhook_url)
            .json(message)
            .send()
            .await
            .map_err(|e| Error::slack(format!("HTTP request failed: {e}")))?;

        if !response.status().is_success() {
            let status = response.status();
            let body = response.text().await.unwrap_or_default();
            error!(status = %status, body = %body, "Slack webhook failed");
            return Err(Error::slack(format!("Slack returned {status}: {body}")));
        }

        info!("Slack notification sent");
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serial_test::serial;

    #[test]
    fn test_mail_config_smtp_builder() {
        let config = MailConfig::new("smtp.example.com", 587, "noreply@example.com")
            .credentials("user", "pass")
            .from_name("My App");

        assert!(matches!(config.driver, MailDriver::Smtp));
        assert_eq!(config.from, "noreply@example.com");
        assert_eq!(config.from_name, Some("My App".to_string()));

        let smtp = config.smtp.as_ref().unwrap();
        assert_eq!(smtp.host, "smtp.example.com");
        assert_eq!(smtp.port, 587);
        assert_eq!(smtp.username, Some("user".to_string()));
        assert_eq!(smtp.password, Some("pass".to_string()));
        assert!(smtp.tls);
        assert!(config.resend.is_none());
    }

    #[test]
    fn test_mail_config_resend_builder() {
        let config = MailConfig::resend("re_123456", "noreply@example.com").from_name("My App");

        assert!(matches!(config.driver, MailDriver::Resend));
        assert_eq!(config.from, "noreply@example.com");
        assert_eq!(config.from_name, Some("My App".to_string()));

        let resend = config.resend.as_ref().unwrap();
        assert_eq!(resend.api_key, "re_123456");
        assert!(config.smtp.is_none());
    }

    #[test]
    fn test_mail_config_no_tls() {
        let config = MailConfig::new("smtp.example.com", 587, "noreply@example.com").no_tls();

        let smtp = config.smtp.as_ref().unwrap();
        assert!(!smtp.tls);
    }

    #[test]
    fn test_notification_config_default() {
        let config = NotificationConfig::default();
        assert!(config.mail.is_none());
        assert!(config.slack_webhook.is_none());
    }

    /// Helper to run env-based tests with clean env var state.
    fn with_env_vars<F: FnOnce()>(vars: &[(&str, &str)], f: F) {
        // Set vars
        for (key, val) in vars {
            unsafe { env::set_var(key, val) };
        }
        f();
        // Clean up
        for (key, _) in vars {
            unsafe { env::remove_var(key) };
        }
    }

    /// Helper to ensure env vars are clean before a test.
    fn clean_mail_env() {
        let keys = [
            "MAIL_DRIVER",
            "MAIL_FROM_ADDRESS",
            "MAIL_FROM_NAME",
            "MAIL_HOST",
            "MAIL_PORT",
            "MAIL_USERNAME",
            "MAIL_PASSWORD",
            "MAIL_ENCRYPTION",
            "RESEND_API_KEY",
        ];
        for key in keys {
            unsafe { env::remove_var(key) };
        }
    }

    #[test]
    #[serial]
    fn test_mail_config_smtp_from_env() {
        clean_mail_env();
        with_env_vars(
            &[
                ("MAIL_FROM_ADDRESS", "noreply@example.com"),
                ("MAIL_FROM_NAME", "Test App"),
                ("MAIL_HOST", "smtp.example.com"),
                ("MAIL_PORT", "465"),
                ("MAIL_USERNAME", "user@example.com"),
                ("MAIL_PASSWORD", "secret"),
                ("MAIL_ENCRYPTION", "tls"),
            ],
            || {
                let config = MailConfig::from_env().expect("should parse SMTP config");
                assert!(matches!(config.driver, MailDriver::Smtp));
                assert_eq!(config.from, "noreply@example.com");
                assert_eq!(config.from_name, Some("Test App".to_string()));

                let smtp = config.smtp.as_ref().expect("smtp config present");
                assert_eq!(smtp.host, "smtp.example.com");
                assert_eq!(smtp.port, 465);
                assert_eq!(smtp.username, Some("user@example.com".to_string()));
                assert_eq!(smtp.password, Some("secret".to_string()));
                assert!(smtp.tls);
                assert!(config.resend.is_none());
            },
        );
    }

    #[test]
    #[serial]
    fn test_mail_config_resend_from_env() {
        clean_mail_env();
        with_env_vars(
            &[
                ("MAIL_DRIVER", "resend"),
                ("MAIL_FROM_ADDRESS", "noreply@example.com"),
                ("MAIL_FROM_NAME", "Test App"),
                ("RESEND_API_KEY", "re_test_123456"),
            ],
            || {
                let config = MailConfig::from_env().expect("should parse Resend config");
                assert!(matches!(config.driver, MailDriver::Resend));
                assert_eq!(config.from, "noreply@example.com");
                assert_eq!(config.from_name, Some("Test App".to_string()));

                let resend = config.resend.as_ref().expect("resend config present");
                assert_eq!(resend.api_key, "re_test_123456");
                assert!(config.smtp.is_none());
            },
        );
    }

    #[test]
    #[serial]
    fn test_mail_config_default_driver() {
        clean_mail_env();
        with_env_vars(
            &[
                ("MAIL_FROM_ADDRESS", "noreply@example.com"),
                ("MAIL_HOST", "smtp.example.com"),
            ],
            || {
                let config = MailConfig::from_env().expect("should default to SMTP");
                assert!(matches!(config.driver, MailDriver::Smtp));
                assert_eq!(config.smtp.as_ref().unwrap().host, "smtp.example.com");
                assert_eq!(config.smtp.as_ref().unwrap().port, 587); // default port
            },
        );
    }

    #[test]
    #[serial]
    fn test_mail_config_resend_missing_api_key() {
        clean_mail_env();
        with_env_vars(
            &[
                ("MAIL_DRIVER", "resend"),
                ("MAIL_FROM_ADDRESS", "noreply@example.com"),
            ],
            || {
                let config = MailConfig::from_env();
                assert!(
                    config.is_none(),
                    "should return None when RESEND_API_KEY missing"
                );
            },
        );
    }

    #[test]
    fn test_resend_payload_serialization() {
        let payload = ResendEmailPayload {
            from: "sender@example.com".into(),
            to: vec!["recipient@example.com".into()],
            subject: "Test".into(),
            html: Some("<p>Hello</p>".into()),
            text: None,
            cc: vec![],
            bcc: vec![],
            reply_to: None,
        };

        let json = serde_json::to_value(&payload).unwrap();
        assert_eq!(json["from"], "sender@example.com");
        assert_eq!(json["to"][0], "recipient@example.com");
        assert_eq!(json["subject"], "Test");
        assert_eq!(json["html"], "<p>Hello</p>");
        // skip_serializing_if fields should be absent
        assert!(json.get("text").is_none());
        assert!(json.get("cc").is_none());
        assert!(json.get("bcc").is_none());
        assert!(json.get("reply_to").is_none());
    }

    #[test]
    fn test_resend_payload_text_fallback() {
        let payload = ResendEmailPayload {
            from: "sender@example.com".into(),
            to: vec!["recipient@example.com".into()],
            subject: "Test".into(),
            html: None,
            text: Some("Plain text body".into()),
            cc: vec!["cc@example.com".into()],
            bcc: vec!["bcc@example.com".into()],
            reply_to: Some("reply@example.com".into()),
        };

        let json = serde_json::to_value(&payload).unwrap();
        assert!(json.get("html").is_none());
        assert_eq!(json["text"], "Plain text body");
        assert_eq!(json["cc"][0], "cc@example.com");
        assert_eq!(json["bcc"][0], "bcc@example.com");
        assert_eq!(json["reply_to"], "reply@example.com");
    }
}