use crate::error::{Result, SunscreenError};

/// Core configuration (always required).
#[derive(Debug, Clone)]
pub struct Config {
    pub database_url: String,
    /// OFAC SDN Advanced XML URL — the authoritative source for sanctioned crypto
    /// addresses and sanctions program data.
    pub ofac_xml_url: String,
    /// Ransomware tracker export URL.
    pub ransomware_url: String,
    /// How often (in seconds) to refresh sanctions data from sources.
    pub data_refresh_interval_secs: u64,
    /// How often (in seconds) to refresh the in-memory API key cache.
    pub api_key_refresh_interval_secs: u64,
}

impl Config {
    pub fn from_env() -> Result<Self> {
        let database_url = required_env("DATABASE_URL")?;
        let ofac_xml_url = std::env::var("OFAC_XML_URL").unwrap_or_else(|_| {
            "https://sanctionslistservice.ofac.treas.gov/api/PublicationPreview/exports/SDN_ADVANCED.XML".into()
        });
        let ransomware_url = std::env::var("RANSOMWARE_EXPORT_URL")
            .unwrap_or_else(|_| "https://api.ransomwhe.re/export".into());
        let data_refresh_interval_secs = std::env::var("DATA_REFRESH_INTERVAL_SECS")
            .ok()
            .and_then(|v| v.parse().ok())
            .unwrap_or(3600);
        let api_key_refresh_interval_secs = std::env::var("API_KEY_REFRESH_INTERVAL_SECS")
            .ok()
            .and_then(|v| v.parse().ok())
            .unwrap_or(60);

        Ok(Self {
            database_url,
            ofac_xml_url,
            ransomware_url,
            data_refresh_interval_secs,
            api_key_refresh_interval_secs,
        })
    }
}

/// HTTP server configuration (only needed when running standalone or embedded HTTP).
#[cfg(feature = "http")]
#[derive(Debug, Clone)]
pub struct HttpServerConfig {
    pub bind_addr: String,
    pub cors_allowed_origins: Vec<String>,
}

fn required_env(name: &str) -> Result<String> {
    std::env::var(name).map_err(|_| SunscreenError::MissingEnvVar(name.into()))
}
