use crate::AppConfig;

impl AppConfig {
    pub fn nats_url(&self) -> String {
        self.env
            .get("NATS_URL")
            .cloned()
            .unwrap_or_else(|| "localhost:4222".to_string())
    }

    pub fn nats_token(&self) -> Option<String> {
        self.env.get("NATS_TOKEN").cloned()
    }

    pub fn nats_stream_name(&self) -> String {
        self.env
            .get("NATS_STREAM_NAME")
            .cloned()
            .unwrap_or_else(|| "APP_EVENTS".to_string())
    }

    pub fn nats_stream_subjects(&self) -> Vec<String> {
        self.env
            .get("NATS_STREAM_SUBJECTS")
            .map(|subjects| {
                subjects
                    .split(',')
                    .map(str::trim)
                    .filter(|subject| !subject.is_empty())
                    .map(ToOwned::to_owned)
                    .collect()
            })
            .filter(|subjects: &Vec<String>| !subjects.is_empty())
            .unwrap_or_else(|| {
                let subject = self
                    .env
                    .get("APP_EMAIL_TOPIC")
                    .or_else(|| self.env.get("EMAIL_TOPIC"))
                    .cloned()
                    .unwrap_or_else(|| "email.send".to_string());
                vec![subject.clone(), format!("{subject}.>")]
            })
    }

    pub fn nats_max_deliver(&self) -> i64 {
        self.env
            .get("NATS_MAX_DELIVER")
            .and_then(|v| v.parse().ok())
            .unwrap_or(3)
    }

    pub fn nats_ack_wait_secs(&self) -> u64 {
        self.env
            .get("NATS_ACK_WAIT_SECS")
            .and_then(|v| v.parse().ok())
            .unwrap_or(10)
    }

    pub fn nats_retry_delay_secs(&self) -> u64 {
        self.env
            .get("NATS_RETRY_DELAY_SECS")
            .and_then(|v| v.parse().ok())
            .unwrap_or_else(|| self.nats_ack_wait_secs())
    }

    pub fn nats_max_age_secs(&self) -> u64 {
        self.env
            .get("NATS_MAX_AGE_SECS")
            .and_then(|v| v.parse().ok())
            .unwrap_or(86_400)
    }

    pub fn nats_buffer_size(&self) -> usize {
        self.env
            .get("NATS_BUFFER_SIZE")
            .and_then(|v| v.parse().ok())
            .unwrap_or(256)
    }

    pub fn nats_is_enabled(&self) -> bool {
        !self.nats_url().is_empty()
    }
}
