#Requires -Version 7.4

function Close-vSEALLogger {
    <#
    .SYNOPSIS
    Closes the vSEAL logger and writes a final END entry to the log file.

    .DESCRIPTION
    Logs a final informational message via Write-vSEALLog, then appends an NDJSON END
    entry to the active log file if the logger was previously initialized. After writing
    the END entry, the logger is marked as uninitialized. If the logger was never
    initialized, only the console log message is emitted.

    .PARAMETER Message
    The closing message to log. Defaults to 'Phase completed'.
    #>
    [CmdletBinding()]
    param(
        [string]$Message = 'Phase completed',

        [switch]$Silent  # Skip console Write-vSEALLog (caller already emitted completion message)
    )

    # Log final message (works even if logger not initialized - goes to console)
    if (-not $Silent) {
        Write-vSEALLog -Message $Message -Level 'INFO'
    }

    # Write END entry if logger was initialized
    if ($script:LoggerInitialized) {
        $endEntry = [ordered]@{
            timestamp = (Get-Date).ToString('o')
            level     = 'END'
            message   = $Message
        }

        $endJson = $endEntry | ConvertTo-Json -Compress
        Add-Content -Path $script:LogConfig.LogFilePath -Value $endJson -Encoding utf8

        $script:LoggerInitialized = $false
    }
}
