//! Dynamic Content Configuration
//!
//! This module provides fully configuration-driven content management
//! that automatically discovers and enables content types from
//! content-kinds.toml.

use std::collections::HashMap;

use serde::{Deserialize, Serialize};

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DynamicContentConfig {
    /// Map of content type name to enabled status
    pub enabled_content_types: HashMap<String, bool>,
    /// Global pages functionality
    pub pages_enabled: bool,
}

impl Default for DynamicContentConfig {
    fn default() -> Self {
        // Discover available content types dynamically
        let available_types = crate::get_all_content_types();
        let mut enabled_content_types = HashMap::new();

        // Enable all discovered content types by default
        for content_type in available_types {
            enabled_content_types.insert(content_type.to_string(), true);
        }

        Self {
            enabled_content_types,
            pages_enabled: true,
        }
    }
}

impl DynamicContentConfig {
    /// Load content configuration from environment variables or use defaults
    pub fn from_env() -> Self {
        let mut config = Self::default();

        // Check for specific content type overrides
        let content_types: Vec<String> = config.enabled_content_types.keys().cloned().collect();
        for content_type in content_types {
            let env_key = format!("CONTENT_{}_ENABLED", content_type.to_uppercase());
            if let Ok(value) = std::env::var(&env_key) {
                if let Ok(enabled) = value.parse::<bool>() {
                    config.enabled_content_types.insert(content_type, enabled);
                }
            }
        }

        // Check global pages setting
        config.pages_enabled = std::env::var("CONTENT_PAGES_ENABLED")
            .unwrap_or_else(|_| "true".to_string())
            .parse()
            .unwrap_or(true);

        config
    }

    /// Check if a specific content type is enabled
    pub fn is_content_type_enabled(&self, content_type: &str) -> bool {
        self.enabled_content_types
            .get(content_type)
            .copied()
            .unwrap_or(false)
    }

    /// Get all enabled content types
    pub fn get_enabled_content_types(&self) -> Vec<String> {
        self.enabled_content_types
            .iter()
            .filter_map(|(content_type, enabled)| {
                if *enabled {
                    Some(content_type.clone())
                } else {
                    None
                }
            })
            .collect()
    }

    /// Check if pages functionality is enabled
    pub fn is_pages_enabled(&self) -> bool {
        self.pages_enabled
    }
}

/// Global content configuration instance
static DYNAMIC_CONTENT_CONFIG: std::sync::OnceLock<DynamicContentConfig> =
    std::sync::OnceLock::new();

/// Get the global dynamic content configuration
pub fn get_dynamic_content_config() -> &'static DynamicContentConfig {
    DYNAMIC_CONTENT_CONFIG.get_or_init(DynamicContentConfig::from_env)
}

/// Check if a content type is enabled globally (works in both SSR and client)
pub fn is_content_type_enabled(content_type: &str) -> bool {
    get_dynamic_content_config().is_content_type_enabled(content_type)
}

/// Get all enabled content types globally
pub fn get_enabled_content_types() -> Vec<String> {
    get_dynamic_content_config().get_enabled_content_types()
}

/// Check if pages are enabled globally (works in both SSR and client)
pub fn is_pages_enabled() -> bool {
    get_dynamic_content_config().is_pages_enabled()
}
