use std::sync::Arc;

use rustelo_components_leptos::contact::facade::server::{BoxFuture, ContactFormFacade};

use super::{EmailService, FormSubmission};

/// Concrete adapter connecting `ContactFormFacade` (defined in
/// `rustelo_components_leptos`) to the `EmailService` (defined here in
/// `rustelo_server`).
///
/// Registered at startup via
/// `axum::Extension(ContactFormExtension(Arc::new(adapter)))`.
pub struct ContactFormAdapter {
    pub email_service: Arc<EmailService>,
    /// Destination address for all incoming contact/work-request submissions.
    pub recipient: String,
}

impl ContactFormFacade for ContactFormAdapter {
    fn send(
        &self,
        name: String,
        email: String,
        subject: String,
        message: String,
    ) -> BoxFuture<Result<(), String>> {
        let svc = self.email_service.clone();
        let recipient = self.recipient.clone();
        Box::pin(async move {
            let submission = FormSubmission::new("contact", &name, &email, &subject, &message);
            svc.send_form_submission_with_language(&submission, &recipient, "en")
                .await
                .map(|_| ())
                .map_err(|e| e.to_string())
        })
    }
}
