use crate::{ResolverConfig, Result};
use std::{net::SocketAddr, path::PathBuf, sync::LazyLock};

static RESOLVER_DIR: LazyLock<PathBuf> = LazyLock::new(|| PathBuf::from("/etc/resolver"));

/// macOS implementation using /etc/resolver files
pub struct MacOsDns;
impl MacOsDns {
    pub async fn add_resolver(config: &ResolverConfig) -> Result<()> {
        let content = Self::generate_resolver_content(&config.domain, &config.resolvers);
        let file_path = RESOLVER_DIR.join(&config.domain);

        if !RESOLVER_DIR.exists() {
            tokio::fs::create_dir_all(RESOLVER_DIR.as_path()).await?;
        }

        tokio::fs::write(&file_path, content).await?;
        Ok(())
    }

    pub async fn remove_resolver(config: &ResolverConfig) -> Result<()> {
        let file_path = RESOLVER_DIR.join(&config.domain);
        if file_path.exists() {
            tokio::fs::remove_file(&file_path).await?;
        }
        Ok(())
    }

    fn generate_resolver_content(domain: &str, nameservers: &[SocketAddr]) -> String {
        let mut content = String::new();
        content.push_str(&format!("# Generated by SplitDNS for {}\n", domain));

        for nameserver in nameservers {
            content.push_str(&format!("nameserver {}\n", nameserver.ip()));
            if nameserver.port() != 53 {
                content.push_str(&format!("port {}\n", nameserver.port()));
            }
        }

        content
    }
}
