use sqlx::PgPool;

use crate::{error::Result, models::ChurchConfig};
use crate::utils::sanitize::strip_html_tags;

pub async fn get_config(pool: &PgPool) -> Result<Option<ChurchConfig>> {
    let config = sqlx::query_as!(ChurchConfig, "SELECT * FROM church_config LIMIT 1")
        .fetch_optional(pool)
        .await?;

    Ok(config)
}

pub async fn update_config(pool: &PgPool, config: ChurchConfig) -> Result<ChurchConfig> {
    let updated = sqlx::query_as!(
        ChurchConfig,
        "UPDATE church_config SET 
         church_name = $1, contact_email = $2, contact_phone = $3, 
         church_address = $4, po_box = $5, google_maps_url = $6, 
         about_text = $7, api_keys = $8, updated_at = NOW()
         WHERE id = $9
         RETURNING *",
        strip_html_tags(&config.church_name),
        strip_html_tags(&config.contact_email),
        config.contact_phone.as_ref().map(|s| strip_html_tags(s)),
        strip_html_tags(&config.church_address),
        config.po_box.as_ref().map(|s| strip_html_tags(s)),
        config.google_maps_url.as_ref().map(|s| strip_html_tags(s)),
        strip_html_tags(&config.about_text),
        config.api_keys,
        config.id
    )
    .fetch_one(pool)
    .await?;

    Ok(updated)
}
