use network_interface::{NetworkInterface, NetworkInterfaceConfig};
use serde::Serialize;

#[derive(Debug, Serialize)]
pub struct InterfaceInfo {
    pub name: String,
    pub addr: String,
    pub mac: Option<String>,
}

fn map_interface_to_info(interface: &NetworkInterface) -> InterfaceInfo {
    let mac_address = interface.mac_addr.as_ref().map(|mac| mac.to_string());
    let ip_addr = interface
        .addr
        .iter()
        .find(|addr| addr.ip().is_ipv4())
        .map(|addr| addr.ip().to_string())
        .unwrap_or_else(|| "N/A".to_string());

    InterfaceInfo {
        name: interface.name.clone(),
        addr: ip_addr,
        mac: mac_address,
    }
}

#[tauri::command]
pub async fn get_network_interfaces() -> Result<Vec<InterfaceInfo>, String> {
    match NetworkInterface::show() {
        Ok(interfaces) => {
            let info_list: Vec<InterfaceInfo> = interfaces
                .into_iter()
                .map(|interface| map_interface_to_info(&interface))
                .collect();
            Ok(info_list)
        }
        Err(e) => Err(format!("无法获取网络接口信息: {}", e)),
    }
}
