use sqlx::PgPool;
use crate::error::{ApiError, Result};
use crate::models::Contact;
use crate::utils::sanitize::strip_html_tags;

pub async fn save_contact(pool: &PgPool, contact: Contact) -> Result<i32> {
    let rec = sqlx::query!(
        r#"
        INSERT INTO contact_submissions 
            (first_name, last_name, email, phone, message, status)
        VALUES ($1, $2, $3, $4, $5, 'pending')
        RETURNING id
        "#,
        strip_html_tags(&contact.first_name),
        strip_html_tags(&contact.last_name),
        strip_html_tags(&contact.email),
        contact.phone.as_ref().map(|s| strip_html_tags(s)),
        strip_html_tags(&contact.message),
    )
    .fetch_one(pool)
    .await
    .map_err(|e| ApiError::DatabaseError(e))?;

    Ok(rec.id)
}

pub async fn update_status(pool: &PgPool, id: i32, status: &str) -> Result<()> {
    sqlx::query!(
        "UPDATE contact_submissions SET status = $1 WHERE id = $2",
        status,
        id
    )
    .execute(pool)
    .await
    .map_err(|e| ApiError::DatabaseError(e))?;

    Ok(())
}
