using System.Diagnostics;
using System.Security.Principal;

namespace NexusInstaller.Services;

internal static class AdminElevationHelper
{
    public static bool IsRunningElevated()
    {
        if (!OperatingSystem.IsWindows())
        {
            return false;
        }

        using var identity = WindowsIdentity.GetCurrent();
        var principal = new WindowsPrincipal(identity);
        return principal.IsInRole(WindowsBuiltInRole.Administrator);
    }

    public static string AdminStatusLabel =>
        IsRunningElevated() ? "Administrator: Ja" : "Administrator: Nej — kræves til installation";

    public static bool RequiresElevationForInstall => !IsRunningElevated();

    public static bool TryRelaunchElevated(string[] args)
    {
        var exePath = Environment.ProcessPath
            ?? Process.GetCurrentProcess().MainModule?.FileName;

        if (string.IsNullOrWhiteSpace(exePath))
        {
            return false;
        }

        var argLine = args.Length == 0
            ? string.Empty
            : string.Join(" ", args.Select(a => a.Contains(' ') ? $"\"{a}\"" : a));

        var psi = new ProcessStartInfo
        {
            FileName = exePath,
            Arguments = argLine,
            UseShellExecute = true,
            Verb = "runas",
        };

        try
        {
            Process.Start(psi);
            return true;
        }
        catch
        {
            return false;
        }
    }
}
