use crate::error::Result;
use crate::models::{ContactRequest, ContactRequestV2, ApiResponse};
use crate::utils::{
    response::success_response,
    validation::ValidationBuilder,
};
use axum::{
    extract::State,
    Json,
};
use crate::{handlers::contact::submit_contact as submit_contact_v1, AppState};

pub async fn submit_contact(
    State(state): State<AppState>,
    Json(req): Json<ContactRequestV2>,
) -> Result<Json<ApiResponse<String>>> {
    ValidationBuilder::new()
        .require(&req.name, "name")
        .require(&req.email, "email")
        .require(&req.message, "message")
        .validate_email(&req.email)
        .validate_length(&req.name, "name", 1, 100)
        .validate_length(&req.message, "message", 1, 2000)
        .validate_phone(&req.phone.as_deref().unwrap_or(""), "phone")
        .build()?;
    
    // Split name into first/last for v1 compatibility - simple approach
    let name_parts: Vec<&str> = req.name.trim().split_whitespace().collect();
    let first_name = name_parts.first().unwrap_or(&"").to_string();
    let last_name = if name_parts.len() > 1 {
        name_parts[1..].join(" ")
    } else {
        "".to_string()
    };
    
    // Convert to v1 format for backend compatibility
    let v1_req = ContactRequest {
        first_name,
        last_name,
        email: req.email,
        phone: req.phone,
        message: req.message,
        subject: req.subject,
    };
    
    let _response = submit_contact_v1(State(state), Json(v1_req)).await?;
    Ok(success_response("Contact form submitted successfully".to_string()))
}