// system/PrivilegeMgr.h
#pragma once
#include <windows.h>
#include <shellapi.h>

namespace PrivilegeManager
{
    inline bool IsRunAsAdministrator()
    {
        BOOL   isAdmin = FALSE;
        PSID   adminGroup = nullptr;
        SID_IDENTIFIER_AUTHORITY ntAuthority = SECURITY_NT_AUTHORITY;

        BOOL success = AllocateAndInitializeSid(
            &ntAuthority, 2,
            SECURITY_BUILTIN_DOMAIN_RID,
            DOMAIN_ALIAS_RID_ADMINS,
            0, 0, 0, 0, 0, 0,
            &adminGroup);

        if (success)
        {
            if (!CheckTokenMembership(nullptr, adminGroup, &isAdmin))
                isAdmin = FALSE;
            FreeSid(adminGroup);
        }

        return isAdmin == TRUE;
    }

    inline bool ElevateNow()
    {
        if (IsRunAsAdministrator())
            return true;

        wchar_t exePath[MAX_PATH] = { 0 };
        if (!GetModuleFileNameW(nullptr, exePath, MAX_PATH))
            return false;

        SHELLEXECUTEINFOW sei{ sizeof(sei) };
        sei.lpVerb = L"runas";
        sei.lpFile = exePath;
        sei.nShow = SW_NORMAL;
        sei.fMask = SEE_MASK_NOCLOSEPROCESS;

        if (ShellExecuteExW(&sei))
            exit(0);

        return false;
    }
}