#Requires -Version 7.4

function Test-ElevationPrerequisite {
    <#
    .SYNOPSIS
        Validates that the session is running with elevated privileges.

    .DESCRIPTION
        Checks if the current PowerShell session is running as Administrator or as the
        SYSTEM account. vSEAL requires elevated privileges for golden image sealing operations.

    .EXAMPLE
        Test-ElevationPrerequisite

        Returns a result object indicating whether the session has elevated privileges.

    .OUTPUTS
        [PSCustomObject] with Name, Passed, Message, Required, Current, and HelpUrl properties.
    #>
    [CmdletBinding()]
    [OutputType([PSCustomObject])]
    param()

    $passed = $false
    $currentValue = 'Unknown'
    $message = ''

    # Only applicable on Windows
    if ($env:OS -ne 'Windows_NT') {
        return [PSCustomObject]@{
            Name     = 'Elevation'
            Passed   = $false
            Message  = 'Elevation check requires Windows environment.'
            Required = 'Running as Administrator or SYSTEM'
            Current  = 'Non-Windows environment'
            HelpUrl  = $null
        }
    }

    try {
        # Get current Windows identity
        $currentIdentity = [System.Security.Principal.WindowsIdentity]::GetCurrent()
        $currentPrincipal = [System.Security.Principal.WindowsPrincipal]::new($currentIdentity)

        # Check for SYSTEM account (S-1-5-18)
        $isSystem = $currentIdentity.IsSystem

        # Check for Administrator role
        $isAdmin = $currentPrincipal.IsInRole([System.Security.Principal.WindowsBuiltInRole]::Administrator)

        # Determine current context description
        $userName = $currentIdentity.Name
        if ($isSystem) {
            $currentValue = "SYSTEM ($userName)"
        }
        elseif ($isAdmin) {
            $currentValue = "Administrator ($userName)"
        }
        else {
            $currentValue = "Standard User ($userName)"
        }

        $passed = $isAdmin -or $isSystem

        $message = if ($passed) {
            if ($isSystem) {
                'Running as SYSTEM account. Elevation requirement met.'
            }
            else {
                'Running with Administrator privileges. Elevation requirement met.'
            }
        }
        else {
            'Not running with elevated privileges. Restart PowerShell as Administrator or run from SYSTEM context.'
        }
    }
    catch {
        $message = "Failed to determine elevation status: $($_.Exception.Message)"
        $currentValue = 'Unable to detect'
    }

    [PSCustomObject]@{
        Name     = 'Elevation'
        Passed   = $passed
        Message  = $message
        Required = 'Running as Administrator or SYSTEM'
        Current  = $currentValue
        HelpUrl  = 'https://learn.microsoft.com/en-us/powershell/scripting/windows-powershell/starting-windows-powershell'
    }
}
