use std::net::IpAddr;

use tokio::net::lookup_host;

/// Get a global routable IP address from a hostname.
/// If the hostname is not globally routable, returns None.
/// Handles hostnames with or without a port (e.g., "example.com" or "example.com:3000").
#[allow(clippy::let_and_return)] // newer rustc requires let and return; older warns
pub async fn get_global_ip_from_hostname(hostname: &str) -> Option<IpAddr> {
    // lookup_hosts requires a port to work, append a dummy port if needed.
    let lookup_str = if hostname.contains(':') {
        hostname.to_string()
    } else {
        format!("{}:50001", hostname)
    };

    let ip = match lookup_host(&lookup_str).await {
        Ok(mut ips) => ips.find(|ip| ip_rfc::global(&ip.ip())).map(|ip| ip.ip()),
        Err(_) => None,
    };

    ip
}
