use crate::AppConfig;

impl AppConfig {
    pub fn git_http_port(&self) -> anyhow::Result<u16> {
        if let Some(port) = self.env.get("APP_GIT_HTTP_PORT") {
            return Ok(port.parse::<u16>()?);
        }
        Ok(8021)
    }

    pub fn git_rpc_port(&self) -> anyhow::Result<u16> {
        if let Some(port) = self.env.get("APP_GIT_RPC_PORT") {
            return Ok(port.parse::<u16>()?);
        }
        Ok(8030)
    }

    pub fn git_rpc_addr(&self) -> anyhow::Result<String> {
        self.env
            .get("APP_GIT_RPC_ADDR")
            .map(|v| v.trim().to_string())
            .ok_or_else(|| anyhow::anyhow!("APP_GIT_RPC_ADDR not set"))
    }

    pub fn repos_root(&self) -> anyhow::Result<String> {
        if let Some(root) = self.env.get("APP_REPOS_ROOT") {
            return Ok(root.to_string());
        }
        let base = std::env::current_dir()?;
        Ok(base
            .join("data")
            .join("repos")
            .to_string_lossy()
            .to_string())
    }

    pub fn gitsync_health_port(&self) -> u16 {
        self.env
            .get("APP_GITSYNC_HEALTH_PORT")
            .and_then(|v| v.trim().parse::<u16>().ok())
            .unwrap_or(8083)
    }
}
