use axum::{extract::State, response::Json};
use crate::error::Result;
use crate::models::{ApiResponse, ContactRequest, Contact, ContactEmail};
use crate::AppState;

pub async fn submit_contact(
    State(state): State<AppState>,
    Json(req): Json<ContactRequest>,
) -> Result<Json<ApiResponse<()>>> {
    // Save to database
    let contact = Contact {
        first_name: req.first_name.clone(),
        last_name: req.last_name.clone(),
        email: req.email.clone(),
        phone: req.phone.clone(),
        message: req.message.clone(),
    };
    
    let id = crate::db::contact::save_contact(&state.pool, contact).await?;

    // Clone what we need for the background task
    let pool = state.pool.clone();
    let mailer = state.mailer.clone();
    let email = ContactEmail {
        first_name: req.first_name,
        last_name: req.last_name,
        email: req.email,
        phone: req.phone,
        message: req.message,
        subject: req.subject,
    };

    // Spawn email sending and status update as a background task
    tokio::spawn(async move {
        if let Err(e) = mailer.send_contact_email(email).await {
            tracing::error!("Failed to send email: {:?}", e);
            if let Err(db_err) = crate::db::contact::update_status(&pool, id, "email_failed").await {
                tracing::error!("Failed to update status: {:?}", db_err);
            }
        } else {
            if let Err(db_err) = crate::db::contact::update_status(&pool, id, "completed").await {
                tracing::error!("Failed to update status: {:?}", db_err);
            }
        }
    });

    Ok(Json(ApiResponse {
        success: true,
        data: None,
        message: Some("Contact form submitted successfully".to_string()),
    }))
}
