#Requires -Version 7.4

function Test-vSEALShouldSkipEngage {
    <#
    .SYNOPSIS
        Determines whether Engage phase should be skipped based on status file content.

    .DESCRIPTION
        Implements intelligent skip decisions for Engage phase to prevent unnecessary
        execution on master images and already-engaged clones. This enables pooled VDI
        to run Engage every boot (status resets with write cache) while persistent VDI
        runs once.

        Skip conditions (DCSN-01 through DCSN-03):
        - DCSN-01: No seal record exists (status.json missing or seal section null)
        - DCSN-02: Running on the seal machine (computerName matches seal.computerName)
        - DCSN-03: Already engaged successfully on this machine (engage.result is Success
                   AND engage.computerName matches current machine)

        Clone detection: Returns Skip=$false when seal.computerName differs from current
        machine, allowing Engage to run normally.

    .PARAMETER Configuration
        The loaded vSEAL configuration hashtable, used to extract persistent_disk setting.

    .OUTPUTS
        [hashtable] with keys:
        - Skip: $true if Engage should be skipped, $false otherwise
        - Reason: String explaining why (or $null if not skipping)

    .EXAMPLE
        $result = Test-vSEALShouldSkipEngage -Configuration $config
        if ($result.Skip) {
            Write-vSEALLog "$($result.Reason). Skipping Engage." -Level INFO
            return
        }
    #>
    [CmdletBinding()]
    [OutputType([hashtable])]
    param(
        [Parameter(Mandatory)]
        $Configuration
    )

    # Extract persistent_disk using bracket notation (06-01-D01)
    $storage = $Configuration['storage']
    $persistentDisk = if ($storage) { $storage['persistent_disk'] } else { $null }

    # Read status with merge support
    $status = Read-vSEALStatus -PersistentDisk $persistentDisk

    # DCSN-01: No seal record
    if (-not $status -or -not $status.seal) {
        return @{ Skip = $true; Reason = 'No seal record found' }
    }

    # DCSN-02: Running on seal machine
    if ($env:COMPUTERNAME -eq $status.seal.computerName) {
        return @{ Skip = $true; Reason = "Running on seal machine ($($status.seal.computerName))" }
    }

    # DCSN-03: Already engaged successfully on this machine
    # Null-safe check: engage section may be null on fresh seal
    if ($status.engage -and
        $status.engage.result -eq 'Success' -and
        $status.engage.computerName -eq $env:COMPUTERNAME) {
        return @{ Skip = $true; Reason = 'Engage already completed successfully on this machine' }
    }

    # Clone detected - run Engage
    return @{ Skip = $false; Reason = $null }
}
