using System.Diagnostics;
using System.Net;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;

namespace WerksverkaufScanner.Services
{
    public class NetworkInfoService
    {
        public string GetMacFromIp(string? ipAddress)
        {
            if (string.IsNullOrWhiteSpace(ipAddress))
                return "Unbekannt";

            try
            {
                // IPv6-Adressen auf IPv4 mappen falls möglich
                if (IPAddress.TryParse(ipAddress, out var ip))
                {
                    if (ip.IsIPv4MappedToIPv6)
                        ip = ip.MapToIPv4();

                    ipAddress = ip.ToString();
                }

                // ARP-Tabelle abfragen (Windows)
                var psi = new ProcessStartInfo("arp", $"-a {ipAddress}")
                {
                    RedirectStandardOutput = true,
                    UseShellExecute = false,
                    CreateNoWindow = true
                };

                using var process = Process.Start(psi);
                if (process == null) return "Fehler beim Starten";

                var output = process.StandardOutput.ReadToEnd();
                process.WaitForExit();

                // MAC-Adresse aus ARP-Output extrahieren
                var match = Regex.Match(output,
                    @"([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})");

                return match.Success ? match.Value.ToUpper() : "Nicht gefunden";
            }
            catch (Exception ex)
            {
                return $"Fehler: {ex.Message}";
            }
        }
    }
}
