use sqlx::PgPool;
use serde_json::Value;
use crate::{
    db,
    models::ChurchConfig,
    error::Result,
};

/// Config business logic service
/// Contains all church config-related business logic, keeping handlers thin and focused on HTTP concerns
pub struct ConfigService;

impl ConfigService {
    /// Get public configuration (excludes API keys)
    pub async fn get_public_config(pool: &PgPool) -> Result<Option<Value>> {
        let config = db::config::get_config(pool).await?;
        
        match config {
            Some(config) => {
                let public_config = serde_json::json!({
                    "church_name": config.church_name,
                    "contact_email": config.contact_email,
                    "contact_phone": config.contact_phone.unwrap_or_else(|| "(860) 875-0450".to_string()),
                    "church_address": config.church_address,
                    "po_box": config.po_box,
                    "google_maps_url": config.google_maps_url,
                    "about_text": config.about_text,
                    "brand_color": config.brand_color,
                    "tagline": "Proclaiming the Three Angels' Messages",
                    "coordinates": {"lat": 41.8703594, "lng": -72.4077036},
                    "donation_url": "https://adventistgiving.org/donate/AN4MJG",
                    "service_times": [
                        {"day": "Saturday", "time": "9:15 AM", "service": "Sabbath School"},
                        {"day": "Saturday", "time": "11:00 AM", "service": "Worship Service"},
                        {"day": "Wednesday", "time": "6:30 PM", "service": "Prayer Meeting"}
                    ]
                });
                Ok(Some(public_config))
            },
            None => Ok(None),
        }
    }

    /// Get admin configuration (includes all fields including API keys)
    pub async fn get_admin_config(pool: &PgPool) -> Result<Option<ChurchConfig>> {
        db::config::get_config(pool).await
    }

    /// Update church configuration
    pub async fn update_config(pool: &PgPool, config: ChurchConfig) -> Result<ChurchConfig> {
        db::config::update_config(pool, config).await
    }
}