use crate::AppConfig;

impl AppConfig {
    pub fn smtp_host(&self) -> anyhow::Result<String> {
        if let Some(host) = self.env.get("APP_SMTP_HOST") {
            return Ok(host.to_string());
        }
        Err(anyhow::anyhow!("APP_SMTP_HOST not found"))
    }

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

    pub fn smtp_username(&self) -> anyhow::Result<String> {
        if let Some(username) = self.env.get("APP_SMTP_USERNAME") {
            return Ok(username.to_string());
        }
        Err(anyhow::anyhow!("APP_SMTP_USERNAME not found"))
    }

    pub fn smtp_password(&self) -> anyhow::Result<String> {
        if let Some(password) = self.env.get("APP_SMTP_PASSWORD") {
            return Ok(password.to_string());
        }
        Err(anyhow::anyhow!("APP_SMTP_PASSWORD not found"))
    }

    pub fn smtp_from(&self) -> anyhow::Result<String> {
        if let Some(from) = self.env.get("APP_SMTP_FROM") {
            return Ok(from.to_string());
        }
        Err(anyhow::anyhow!("APP_SMTP_FROM not found"))
    }

    pub fn smtp_tls(&self) -> anyhow::Result<bool> {
        if let Some(tls) = self.env.get("APP_SMTP_TLS") {
            return Ok(tls.parse::<bool>()?);
        }
        Ok(true)
    }

    pub fn smtp_timeout(&self) -> anyhow::Result<u64> {
        if let Some(timeout) = self.env.get("APP_SMTP_TIMEOUT") {
            return Ok(timeout.parse::<u64>()?);
        }
        Ok(30)
    }

    pub fn email_topic(&self) -> String {
        self.env
            .get("APP_EMAIL_TOPIC")
            .or_else(|| self.env.get("EMAIL_TOPIC"))
            .cloned()
            .unwrap_or_else(|| "email.send".to_string())
    }

    pub fn email_consumer_group_id(&self) -> String {
        self.env
            .get("APP_EMAIL_CONSUMER_GROUP_ID")
            .or_else(|| self.env.get("EMAIL_CONSUMER_GROUP_ID"))
            .cloned()
            .unwrap_or_else(|| "email-service".to_string())
    }

    pub fn email_send_retry_attempts(&self) -> u32 {
        self.env
            .get("APP_EMAIL_SEND_RETRY_ATTEMPTS")
            .or_else(|| self.env.get("EMAIL_SEND_RETRY_ATTEMPTS"))
            .and_then(|value| value.parse().ok())
            .unwrap_or(3)
    }

    pub fn email_send_retry_base_delay_secs(&self) -> u64 {
        self.env
            .get("APP_EMAIL_SEND_RETRY_BASE_DELAY_SECS")
            .or_else(|| self.env.get("EMAIL_SEND_RETRY_BASE_DELAY_SECS"))
            .and_then(|value| value.parse().ok())
            .unwrap_or(1)
    }
}
