//! 应用配置模块
//!
//! 从环境变量加载配置，不再使用 TOML 文件。
//! systemd service 的 Environment= 是唯一的配置来源。

#[derive(Debug, Clone)]
pub struct AppConfig {
    pub database_url: String,
    pub wechat_appid: String,
    pub wechat_secret: String,
    pub jwt_secret: String,
    pub ssl_key_path: String,
    pub ssl_cert_path: String,
    pub rust_log: String,
    pub environment: String,
    pub free_user_data_limit: i32,
}

impl AppConfig {
    pub fn load() -> Result<Self, String> {
        let environment = std::env::var("APP_ENV").unwrap_or_else(|_| "development".into());

        let app_config = Self {
            database_url: env_or_fail("DATABASE_URL")?,
            wechat_appid: env_or_fail("WECHAT_APPID")?,
            wechat_secret: env_or_fail("WECHAT_SECRET")?,
            jwt_secret: env_or_fail("JWT_SECRET")?,
            ssl_key_path: std::env::var("SSL_KEY_PATH").unwrap_or_default(),
            ssl_cert_path: std::env::var("SSL_CERT_PATH").unwrap_or_default(),
            rust_log: std::env::var("RUST_LOG").unwrap_or_else(|_| "info".into()),
            free_user_data_limit: std::env::var("FREE_USER_DATA_LIMIT")
                .ok()
                .and_then(|v| v.parse().ok())
                .unwrap_or(20),
            environment,
        };

        tracing::info!(
            "配置加载成功，环境={}",
            app_config.environment
        );

        Ok(app_config)
    }

    pub fn database_url(&self) -> &str {
        &self.database_url
    }

    pub fn rust_log(&self) -> &str {
        &self.rust_log
    }

    pub fn is_production(&self) -> bool {
        self.environment == "production"
    }
}

fn env_or_fail(key: &str) -> Result<String, String> {
    std::env::var(key).map_err(|_| format!("环境变量 {} 未设置", key))
}
