using System;
using System.Management;
using System.Security.Cryptography;
using System.Text;

namespace Levelcode_licenseCliente.Security
{
    public static class HwidService
    {
        public static string ObterHwid()
        {
            string cpuId = ObterCpuId();
            string diskId = ObterDiskId();

            string bruto = cpuId + "|" + diskId;

            using (SHA256 sha = SHA256.Create())
            {
                byte[] hash = sha.ComputeHash(Encoding.UTF8.GetBytes(bruto));
                return BitConverter.ToString(hash).Replace("-", "");
            }
        }

        private static string ObterCpuId()
        {
            try
            {
                ManagementObjectSearcher searcher =
                    new ManagementObjectSearcher("SELECT ProcessorId FROM Win32_Processor");

                foreach (ManagementObject obj in searcher.Get())
                    return obj["ProcessorId"]?.ToString() ?? "CPU_UNKNOWN";
            }
            catch { }

            return "CPU_UNKNOWN";
        }

        private static string ObterDiskId()
        {
            try
            {
                ManagementObjectSearcher searcher =
                    new ManagementObjectSearcher("SELECT SerialNumber FROM Win32_PhysicalMedia");

                foreach (ManagementObject obj in searcher.Get())
                    return obj["SerialNumber"]?.ToString() ?? "DISK_UNKNOWN";
            }
            catch { }

            return "DISK_UNKNOWN";
        }
    }
}
