use async_trait::async_trait;
use thiserror::Error;
use uuid::Uuid;
use crate::ErrorRepositorio;
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Correo {
pub para: String,
pub asunto: String,
pub html: String,
pub texto: Option<String>,
}
impl Correo {
pub fn new(
para: impl Into<String>,
asunto: impl Into<String>,
html: impl Into<String>,
) -> Self {
Self {
para: para.into(),
asunto: asunto.into(),
html: html.into(),
texto: None,
}
}
pub fn con_texto(mut self, texto: impl Into<String>) -> Self {
self.texto = Some(texto.into());
self
}
}
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Error)]
pub enum ErrorCorreo {
#[error("correo.transitorio: {0}")]
Transitorio(String),
#[error("correo.permanente: {0}")]
Permanente(String),
}
#[async_trait]
pub trait EnviadorCorreo: Send + Sync {
async fn enviar(&self, email: &Correo) -> Result<(), ErrorCorreo>;
}
#[async_trait]
pub trait CorreosEnviados: Send + Sync {
async fn fue_enviado(&self, id_evento: Uuid, correo: &str) -> Result<bool, ErrorRepositorio>;
async fn marcar_enviado(&self, id_evento: Uuid, correo: &str) -> Result<(), ErrorRepositorio>;
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn should_be_html_only_when_built_without_text() {
let email = Correo::new("ada@example.com", "Welcome", "<p>Hi Ada</p>");
assert_eq!(email.para, "ada@example.com");
assert_eq!(email.asunto, "Welcome");
assert_eq!(email.html, "<p>Hi Ada</p>");
assert_eq!(email.texto, None);
}
#[test]
fn should_carry_the_text_alternative_when_given_one() {
let email = Correo::new("ada@example.com", "Welcome", "<p>Hi</p>").con_texto("Hi");
assert_eq!(email.texto.as_deref(), Some("Hi"));
}
#[test]
fn should_keep_error_codes_stable_when_logged() {
assert_eq!(
ErrorCorreo::Transitorio("refused".into()).to_string(),
"correo.transitorio: refused"
);
assert_eq!(
ErrorCorreo::Permanente("550 no such user".into()).to_string(),
"correo.permanente: 550 no such user"
);
}
}