use rustango::core::Column as _;
use rustango::sql::{ExecError, FetcherPool as _, Pool};
use super::model::NotificationTarget;
pub const MANAGED_BY_FORM: &str = "form_settings";
pub async fn sync_form_email(
pool: &Pool,
form_id: i64,
form_title: &str,
emails: &str,
) -> Result<(), ExecError> {
let existing: Vec<NotificationTarget> = NotificationTarget::objects()
.where_(NotificationTarget::source_id.eq(form_id))
.where_(NotificationTarget::kind.eq("email".to_owned()))
.fetch(pool)
.await?;
let mut managed = existing.into_iter().find(|t| {
t.config_map().get("managed_by").map(String::as_str) == Some(MANAGED_BY_FORM)
});
let clean: Vec<&str> = emails
.split(',')
.map(str::trim)
.filter(|s| !s.is_empty())
.collect();
if clean.is_empty() {
if let Some(t) = managed {
t.delete_pool(pool).await?;
}
return Ok(());
}
if std::env::var_os("RUSTANGO_SECRET_KEY").is_none() {
return Err(ExecError::Driver(rustango::sql::sqlx::Error::Configuration(
"RUSTANGO_SECRET_KEY is not set, so email notifications can't be stored".into(),
)));
}
let config = serde_json::json!({
"recipients": clean.join(", "),
"managed_by": MANAGED_BY_FORM,
})
.to_string();
let label = format!("{form_title} — email");
match managed.take() {
Some(mut t) => {
t.label = label;
t.config = config;
t.events = "form.submitted".to_owned();
t.enabled = true;
t.save_pool(pool).await?;
}
None => {
let mut row = NotificationTarget {
id: rustango::sql::Auto::Unset,
label,
kind: "email".to_owned(),
config,
secret: rustango::casts::Cast::new(String::new().into()),
events: "form.submitted".to_owned(),
source_id: form_id,
enabled: true,
created_at: rustango::sql::Auto::Unset,
};
row.insert_pool(pool).await?;
}
}
Ok(())
}