#Requires -Version 7.4

function Remove-vSEALBaseline {
    <#
    .SYNOPSIS
        Deletes a baseline by ID.

    .DESCRIPTION
        Removes a baseline folder and all its contents from storage. By default,
        protected baselines are skipped with a warning. Use -Force to override
        protection. Uses retry logic to handle transient file locks.

    .PARAMETER Id
        The baseline ID in YYYYMMDD_HHMMSS format (e.g., '20260125_120000').

    .PARAMETER Config
        Optional hashtable containing vSEAL configuration. If the configuration
        contains a baseline.path setting, that path will be used for lookup.

    .PARAMETER Force
        Skip protected baseline check. Required to delete protected baselines.

    .EXAMPLE
        Remove-vSEALBaseline -Id '20260125_120000'

        Deletes the baseline with the specified ID.

    .EXAMPLE
        Remove-vSEALBaseline -Id '20260125_120000' -Force

        Deletes the baseline even if it's marked as protected.

    .EXAMPLE
        $config = @{ baseline = @{ path = 'D:\Baselines' } }
        Remove-vSEALBaseline -Id '20260125_120000' -Config $config

        Deletes a baseline from a custom storage location.

    .OUTPUTS
        [bool] $true if baseline was deleted, $false if not found, protected, or failed.
    #>
    [CmdletBinding()]
    [OutputType([bool])]
    param(
        [Parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [string]$Id,

        [Parameter()]
        [hashtable]$Config,

        [Parameter()]
        [switch]$Force
    )

    # Resolve storage location
    $basePath = Resolve-vSEALBaselinePath -Config $Config

    # Build baseline folder path
    $baselineDir = Join-Path $basePath $Id

    Write-vSEALLog "Attempting to remove baseline: $baselineDir" -Level VERBOSE

    # Check if baseline exists
    if (-not (Test-Path -Path $baselineDir -PathType Container)) {
        Write-Warning "Baseline not found: $Id"
        return $false
    }

    # Check protected flag (only if not Force)
    if (-not $Force) {
        $manifestPath = Join-Path $baselineDir '_manifest.json'
        if (Test-Path -Path $manifestPath -PathType Leaf) {
            try {
                $content = Get-Content -Path $manifestPath -Raw -Encoding utf8 -ErrorAction Stop
                $manifest = $content | ConvertFrom-Json -AsHashtable -ErrorAction Stop
                if ($null -ne $manifest -and $manifest.ContainsKey('protected') -and $manifest.protected) {
                    Write-Warning "Baseline $Id is protected. Use -Force to override."
                    return $false
                }
            }
            catch {
                # If we can't read manifest, proceed with deletion (baseline may be corrupt)
                Write-vSEALLog "Could not read manifest for protection check, proceeding with deletion" -Level VERBOSE
            }
        }
    }

    # Delete with retry pattern (5 retries, 1s delay per CONTEXT.md)
    $maxRetries = 5
    $retryDelay = 1000

    for ($i = 0; $i -lt $maxRetries; $i++) {
        try {
            Remove-Item -Path $baselineDir -Recurse -Force -ErrorAction Stop
            Write-vSEALLog "Baseline deleted: $Id" -Level INFO
            return $true
        }
        catch {
            if ($i -lt $maxRetries - 1) {
                Write-vSEALLog "Delete attempt $($i + 1) failed, retrying... ($($_.Exception.Message))" -Level VERBOSE
                Start-Sleep -Milliseconds $retryDelay
            }
            else {
                Write-vSEALLog "Delete failed after all retries: $($_.Exception.Message)" -Level ERROR
            }
        }
    }

    Write-Warning "Failed to delete baseline after $maxRetries attempts: $Id"
    return $false
}
