use crate::{ config::Config, models::{ email::SendEmailRequest, error::ServiceError, template::TemplateEmailRequest, template::TemplateRegistry, }, services::gmail::GmailService, }; use actix_web::{web, HttpRequest, HttpResponse, Result}; pub async fn send_template_email( request: web::Json, config: web::Data, req: HttpRequest, ) -> Result { let request = request.into_inner(); let template_registry = TemplateRegistry::new(); // Get the template let template = template_registry.get_template(&request.template_id).ok_or_else(|| { ServiceError::InvalidEmail(format!("Template '{}' not found", request.template_id)) })?; // Render the template let (subject, body) = template .render(&request.variables) .map_err(|e| ServiceError::InvalidEmail(format!("Template rendering failed: {}", e)))?; // Convert to regular email request let email_request = SendEmailRequest { to: request.to, cc: request.cc, bcc: request.bcc, subject, body, content_type: Some("text/html".to_string()), from_name: None, attachments: None, }; // Set up Gmail service with impersonation let mut gmail_service = GmailService::new(&config); if let Some(user_email) = req .headers() .get("X-Impersonate-User") .and_then(|h| h.to_str().ok()) { gmail_service = gmail_service.with_user_email(user_email.to_string()); } // Send the email let email = gmail_service.send_email(email_request).await?; Ok(HttpResponse::Created().json(email)) } pub async fn list_templates() -> Result { let template_registry = TemplateRegistry::new(); let templates = template_registry.list_templates(); Ok(HttpResponse::Ok().json(templates)) } pub async fn get_template(path: web::Path) -> Result { let template_id = path.into_inner(); let template_registry = TemplateRegistry::new(); let template = template_registry .get_template(&template_id) .ok_or_else(|| ServiceError::NotFound)?; Ok(HttpResponse::Ok().json(template)) }