use std::env;

/// Application configuration loaded from environment variables
#[derive(Debug, Clone)]
pub struct Config {
    /// Server host
    pub host: String,
    /// Server port
    pub port: u16,
    /// Database URL
    pub database_url: String,
    /// Valkey/Redis URL
    pub valkey_url: String,
    /// Oathkeeper shared secret
    pub oathkeeper_secret: String,
    /// S3 endpoint
    pub s3_endpoint: String,
    /// S3 bucket name
    pub s3_bucket: String,
    /// S3 access key
    pub s3_access_key: String,
    /// S3 secret key
    pub s3_secret_key: String,
    /// Log level
    pub log_level: String,
    /// Google service account key (JSON, base64, or file path)
    pub google_service_account_key: Option<String>,
    /// Google Calendar ID
    pub google_calendar_id: Option<String>,
    /// Gmail impersonation email (for domain-wide delegation)
    pub google_gmail_user: Option<String>,
    /// Wave API access token
    pub wave_access_token: Option<String>,
    /// Wave business ID
    pub wave_business_id: Option<String>,
}

impl Config {
    /// Load configuration from environment variables
    pub fn from_env() -> Result<Self, env::VarError> {
        Ok(Self {
            host: env::var("HOST").unwrap_or_else(|_| "0.0.0.0".to_string()),
            port: env::var("PORT")
                .unwrap_or_else(|_| "3000".to_string())
                .parse()
                .unwrap_or(3000),
            database_url: env::var("DATABASE_URL")?,
            valkey_url: env::var("VALKEY_URL").unwrap_or_else(|_| "redis://localhost:6379".to_string()),
            oathkeeper_secret: env::var("OATHKEEPER_SECRET").unwrap_or_default(),
            s3_endpoint: env::var("S3_ENDPOINT").unwrap_or_default(),
            s3_bucket: env::var("S3_BUCKET").unwrap_or_else(|_| "nexus".to_string()),
            s3_access_key: env::var("S3_ACCESS_KEY").unwrap_or_default(),
            s3_secret_key: env::var("S3_SECRET_KEY").unwrap_or_default(),
            log_level: env::var("RUST_LOG").unwrap_or_else(|_| "info".to_string()),
            google_service_account_key: env::var("GOOGLE_SERVICE_ACCOUNT_KEY").ok(),
            google_calendar_id: env::var("GOOGLE_CALENDAR_ID").ok(),
            google_gmail_user: env::var("GOOGLE_GMAIL_USER").ok(),
            wave_access_token: env::var("WAVE_ACCESS_TOKEN").ok(),
            wave_business_id: env::var("WAVE_BUSINESS_ID").ok(),
        })
    }

    /// Get the server bind address
    pub fn bind_addr(&self) -> String {
        format!("{}:{}", self.host, self.port)
    }
}
