//! Server utilities module

use crate::*;

/// Server configuration
#[derive(Debug, Clone)]
pub struct ServerConfig {
    /// Server address
    pub addr: std::net::SocketAddr,
    /// Environment mode
    pub environment: Environment,
    /// Whether to enable request logging
    pub enable_logging: bool,
    /// Whether to enable CORS
    pub enable_cors: bool,
}

impl ServerConfig {
    /// Create server config from environment variables
    pub fn from_env() -> Result<Self, std::env::VarError> {
        let host = std::env::var("HOST").unwrap_or_else(|_| "127.0.0.1".to_string());
        let port = std::env::var("PORT")
            .unwrap_or_else(|_| "3000".to_string())
            .parse::<u16>()
            .unwrap_or(3000);

        let environment = match std::env::var("ENVIRONMENT").as_deref() {
            Ok("production") => Environment::Production,
            Ok("staging") => Environment::Staging,
            Ok(custom) => Environment::Custom(custom.to_string()),
            _ => Environment::Development,
        };

        Ok(Self {
            addr: format!("{}:{}", host, port).parse().unwrap(),
            environment,
            enable_logging: std::env::var("ENABLE_LOGGING")
                .map(|v| v == "true")
                .unwrap_or(true),
            enable_cors: std::env::var("ENABLE_CORS")
                .map(|v| v == "true")
                .unwrap_or(true),
        })
    }
}

impl Default for ServerConfig {
    fn default() -> Self {
        Self {
            addr: "127.0.0.1:3000".parse().unwrap(),
            environment: Environment::Development,
            enable_logging: true,
            enable_cors: true,
        }
    }
}

/// Initialize server with configuration
pub async fn init_server() -> Result<(), Box<dyn std::error::Error>> {
    // Initialize panic handler for better error messages
    console_error_panic_hook::set_once();

    // Initialize logging
    if std::env::var("RUST_LOG").is_err() {
        std::env::set_var("RUST_LOG", "server_template=debug");
    }

    tracing_subscriber::fmt()
        .with_env_filter(tracing_subscriber::EnvFilter::from_default_env())
        .init();

    tracing::info!("Server initialized");
    Ok(())
}