<#
.SYNOPSIS
    Installs all available Windows Updates via PSWindowsUpdate module.

.DESCRIPTION
    Installs all currently available updates without rebooting.
    Exits with code 9 when updates were installed (reboot required for
    further rounds) or code 0 when the system is already fully up to date.

    The xetup.exe state machine handles the reboot cycle:
      - exit 9  ->  xetup saves state, sets autologon + X9-Resume task, reboots
      - on each subsequent logon X9-Resume launches xetup --resume
      - xetup re-runs this step until it exits 0 (no more updates)
      - then disables autologon, removes X9-Resume, shows the summary screen

.ITEMS
    nainstalovat-pswindowsupdate-modul: Installs NuGet provider and PSWindowsUpdate module from PSGallery.
    spustit-kolo-windows-update: One update pass without reboot. Exits 9 when updates were applied (more rounds needed). Exits 0 when system is fully up to date.
#>
param(
    [string]$ConfigPath,
    [string]$LogFile
)

. "$PSScriptRoot\common.ps1"
$Config = Load-Config $ConfigPath

Write-Log "=== Step 12 - Windows Update ===" -Level STEP

# -----------------------------------------------------------------------
# 1. NuGet provider + PSWindowsUpdate module
# -----------------------------------------------------------------------
Write-Log "Setting up PSWindowsUpdate module..." -Level INFO
try {
    Install-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201 -Force -Scope AllUsers | Out-Null
    $existing = Get-Module -ListAvailable -Name PSWindowsUpdate | Select-Object -First 1
    if ($existing) {
        Write-Log "  PSWindowsUpdate $($existing.Version) already installed" -Level INFO
    } else {
        Install-Module -Name PSWindowsUpdate -Force -Scope AllUsers -AllowClobber | Out-Null
        Write-Log "  PSWindowsUpdate installed" -Level OK
    }
    Import-Module PSWindowsUpdate -Force
} catch {
    Write-Log "  Module setup failed: $_" -Level ERROR
    exit 1
}

# -----------------------------------------------------------------------
# 2. Check and install available updates
# -----------------------------------------------------------------------
Write-Log "Checking for available Windows Updates..." -Level INFO
try {
    $available = Get-WindowsUpdate -AcceptAll -IgnoreReboot -ErrorAction Stop
} catch {
    Write-Log "  Failed to check for updates: $_" -Level ERROR
    exit 1
}

if (-not $available -or @($available).Count -eq 0) {
    Write-Log "  System is fully up to date" -Level OK
    Write-Log "Step 12 complete" -Level OK
    exit 0
}

Write-Log "  Found $($available.Count) update(s) - installing..." -Level INFO
try {
    # Format each update via its properties. Logging the raw object ($_) renders
    # as "System.__ComObject" because the WUApiLib result objects have no useful
    # ToString(); -Verbose 2>&1 also merged verbose-stream noise into the log.
    $result = Install-WindowsUpdate -AcceptAll -IgnoreReboot
    foreach ($u in $result) {
        if ($u.Title) {
            Write-Log ("  {0} - {1}" -f $u.Result, $u.Title) -Level INFO
        }
    }
    Write-Log "  Update pass complete - reboot required for next round" -Level OK
} catch {
    Write-Log "  Update install failed: $_" -Level ERROR
    exit 1
}

# Signal xetup that a reboot is needed before running this step again
Write-Log "Step 12 - reboot required (exit 9)" -Level OK
exit 9
