use serde::Deserialize;

#[derive(Debug, Clone, Deserialize)]
pub struct DatabaseConfig {
    /// PostgreSQL connection URL (e.g. postgres://user:pass@localhost/swym)
    #[serde(alias = "database_url")]
    pub url: String,

    /// Maximum number of connections in the pool
    #[serde(default = "default_max_connections")]
    pub max_connections: u32,

    /// If set, run strategy seeds for this environment after migrations.
    /// Supported values: `"dev"`. Leave unset in services that don't manage seeds.
    #[serde(default)]
    pub seed_env: Option<String>,
}

fn default_max_connections() -> u32 {
    5
}

impl DatabaseConfig {
    pub fn from_env() -> Result<Self, std::env::VarError> {
        Ok(Self {
            url: std::env::var("DATABASE_URL")?,
            max_connections: std::env::var("DATABASE_MAX_CONNECTIONS")
                .ok()
                .and_then(|v| v.parse().ok())
                .unwrap_or(5),
            seed_env: None,
        })
    }
}
