use crate::config::email::EmailConfig;
use anyhow::Result;
use lettre::{
    message::Mailbox, transport::smtp::authentication::Credentials, AsyncSmtpTransport,
    AsyncTransport, Message, Tokio1Executor,
};

pub async fn send_verification(config: &EmailConfig, recipient: &str, code: &str) -> Result<()> {
    let email = Message::builder()
        .from(format!("{} <{}>", config.from_name, config.from_email).parse::<Mailbox>()?)
        .to(recipient.parse::<Mailbox>()?)
        .subject("Verification code")
        .body(format!(
            "Your verification code is {code}. It expires soon."
        ))?;
    let credentials = Credentials::new(config.smtp_username.clone(), config.smtp_password.clone());
    let mailer = AsyncSmtpTransport::<Tokio1Executor>::starttls_relay(&config.smtp_host)?
        .port(config.smtp_port)
        .credentials(credentials)
        .build();
    mailer.send(email).await?;
    Ok(())
}
