Private/UI/Invoke-EwWorkbenchLibraryRegistrationResult.ps1

Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'

function Invoke-EwWorkbenchLibraryRegistrationResult {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)][Collections.IDictionary]$State,
        [Parameter(Mandatory)][psobject]$Job
    )

    $context = $State.LibraryRegistrationContext
    $State.LibraryRegistrationContext = $null
    $envelope = @($Job.Output) | Select-Object -Last 1
    if ($Job.State -ne 'Completed' -or $null -ne $Job.TerminatingError -or $null -eq $envelope) {
        $detail = if ($null -ne $Job.TerminatingError) { [string]$Job.TerminatingError.Exception.Message } else { [string]$Job.State }
        Write-EwWorkbenchLog -State $State -Message "Library registration outcome unavailable: $detail. No automatic retry; reload the library before adding again." -Level Error
        $State.LoadedLibraryPath = ''
        return
    }
    if ($null -ne $envelope.Plan) {
        try {
            $State.LibraryPromptActive = $true
            $choice = Show-EwWorkbenchLibraryRegistrationDialog -Window $State.Window -Plan $envelope.Plan -InitialName $envelope.InitialName -ValidationError $envelope.ValidationError
        }
        finally {
            $State.LibraryPromptActive = $false
            Invoke-EwWorkbenchLibraryRegistrationState -State $State
        }
        if ($null -ne $choice) {
            $null = $context.Remove('Replace')
            $context.RegistrationName = $choice.RegistrationName
            if ($choice.Action -eq 'Replace') { $context.Replace = $true }
            $context.ExpectedLibraryHash = $envelope.Plan.LibraryHash
            Invoke-EwWorkbenchLibraryRegistration -State $State -Parameters $context
        }
        else { Write-EwWorkbenchLog -State $State -Message 'Library registration cancelled; no filters changed.' }
        return
    }
    $result = $envelope.Result
    if (-not $result.Succeeded) {
        Write-EwWorkbenchLog -State $State -Message "Library registration failed for $($context.Name): $($result.Error)" -Level Error
    }
    else {
        $outcome = if ($result.Status -eq 'AlreadyPresent') { 'already present' } else { $result.Status.ToLowerInvariant() }
        Write-EwWorkbenchLog -State $State -Message "Library registration for $($result.Name) $outcome in $($result.Path). Use Update library on the Library page to download matching Artifacts; none were downloaded."
    }
    if ($envelope.RefreshError) {
        $State.LoadedLibraryPath = ''
        Write-EwWorkbenchLog -State $State -Message "Registration outcome: $($result.Status). Library inventory refresh failed: $($envelope.RefreshError)" -Level Error
    }
    elseif ([string]$State.LibraryPathBox.Text -ceq $context.Path) {
        Invoke-EwWorkbenchLibraryInventory -State $State -Item @($envelope.Items) -Path $context.Path -SelectedName $result.Name
    }
}