using System.Management;

namespace ITNexusAgent.Services;

public static class SecurityInfoService
{
    public static string GetBitlockerStatus()
    {
        try
        {
            var scope = new ManagementScope(@"\\.\root\cimv2\Security\MicrosoftVolumeEncryption");
            scope.Connect();
            using var searcher = new ManagementObjectSearcher(scope,
                new System.Management.ObjectQuery("SELECT * FROM Win32_EncryptableVolume WHERE DriveLetter='C:'"));
            foreach (ManagementObject obj in searcher.Get())
            {
                var protection = Convert.ToInt32(obj["ProtectionStatus"]);
                return protection switch
                {
                    1 => "encrypted",
                    2 => "unknown",
                    _ => "off"
                };
            }
        }
        catch { }
        return "unknown";
    }

    public static (bool Enabled, int SignaturesAgeDays, DateTime? LastScan) GetDefenderStatus()
    {
        try
        {
            var scope = new ManagementScope(@"\\.\root\Microsoft\Windows\Defender");
            scope.Connect();
            using var searcher = new ManagementObjectSearcher(scope,
                new System.Management.ObjectQuery("SELECT * FROM MSFT_MpComputerStatus"));
            foreach (ManagementObject obj in searcher.Get())
            {
                var enabled = Convert.ToBoolean(obj["AMServiceEnabled"] ?? false);
                var sigDate = obj["AntivirusSignatureLastUpdated"]?.ToString();
                var lastScanAge = Convert.ToInt32(obj["QuickScanAge"] ?? 999);

                int sigAge = 0;
                if (!string.IsNullOrEmpty(sigDate) && sigDate.Length >= 8)
                {
                    if (DateTime.TryParseExact(sigDate[..14], "yyyyMMddHHmmss",
                        null, System.Globalization.DateTimeStyles.None, out var sigDateTime))
                    {
                        sigAge = (int)(DateTime.Now - sigDateTime).TotalDays;
                    }
                }

                DateTime? lastScan = lastScanAge < 999
                    ? DateTime.Now.AddDays(-lastScanAge)
                    : null;

                return (enabled, sigAge, lastScan);
            }
        }
        catch { }
        return (false, -1, null);
    }
}
