[CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'High')]
param(
    [Parameter(Mandatory)]
    [ValidatePattern('^[0-9a-fA-F-]{36}$')]
    [string] $SubscriptionId,

    [Parameter(Mandatory)]
    [switch] $ConfirmCleanup
)

. (Join-Path $PSScriptRoot 'NetworkSecurityPerimeterWorkshop.Common.ps1')

if (-not $ConfirmCleanup) { throw 'Cleanup requires the explicit -ConfirmCleanup safety switch.' }
Assert-WorkshopSubscription -SubscriptionId $SubscriptionId | Out-Null
$runtime = Get-WorkshopRuntime
if ([string]$runtime.subscriptionId -ne $SubscriptionId) { throw 'The runtime subscription does not match the cleanup target.' }

$root = Get-WorkshopRoot
$work = Get-WorkshopWorkDirectory
$baselinePath = Join-Path $work 'baseline.json'
if (-not (Test-Path -LiteralPath $baselinePath)) { throw 'The protected baseline is missing.' }
$baseline = Get-Content -Raw -LiteralPath $baselinePath | ConvertFrom-Json -Depth 100

$outputs = Get-WorkshopTerraformOutputs -SubscriptionId $SubscriptionId
$vaultName = [string]$outputs.key_vault_name
$resourceGroup = [string]$outputs.resource_group_name

if (-not $PSCmdlet.ShouldProcess($resourceGroup, 'Destroy all Terraform-managed Workshopz NSP resources and purge the lab Key Vault')) {
    return
}

$destroy = Invoke-Terraform -SubscriptionId $SubscriptionId -AllowedSubscriptionIds @($SubscriptionId) -Arguments @(
    'destroy', '-no-color', '-auto-approve',
    "-var-file=$(Join-Path $root 'stages/03-enforced-allow.tfvars')",
    "-var=location=$($runtime.location)"
)
$destroy.Output | Set-Content -LiteralPath (Join-Path $work 'cleanup-destroy.txt') -Encoding utf8NoBOM

$deadline = [DateTime]::UtcNow.AddMinutes(20)
do {
    $group = Invoke-AzureCli -Arguments @(
        'group', 'show', '--subscription', $SubscriptionId, '--name', $resourceGroup,
        '--only-show-errors', '--output', 'none'
    ) -AllowFailure
    if ($group.ExitCode -ne 0) { break }
    Start-Sleep -Seconds 30
} while ([DateTime]::UtcNow -lt $deadline)
if ($group.ExitCode -eq 0) { throw 'Timed out waiting for the workshop resource group deletion.' }

$deletedVault = Invoke-AzureCliJson -Arguments @('keyvault', 'list-deleted', '--subscription', $SubscriptionId)
if (@($deletedVault | Where-Object { $_.name -eq $vaultName }).Count -gt 0) {
    $purge = Invoke-AzureCli -Arguments @(
        'keyvault', 'purge', '--subscription', $SubscriptionId,
        '--name', $vaultName, '--location', [string]$runtime.location, '--only-show-errors'
    ) -AllowFailure
    $purge.Output | Set-Content -LiteralPath (Join-Path $work 'cleanup-vault-purge.txt') -Encoding utf8NoBOM
    if ($purge.ExitCode -ne 0) { throw "Key Vault purge failed: $($purge.Output)" }
}

$purgeDeadline = [DateTime]::UtcNow.AddMinutes(10)
do {
    $deletedVault = Invoke-AzureCliJson -Arguments @('keyvault', 'list-deleted', '--subscription', $SubscriptionId)
    $vaultStillDeleted = @($deletedVault | Where-Object { $_.name -eq $vaultName }).Count -gt 0
    if (-not $vaultStillDeleted) { break }
    Start-Sleep -Seconds 30
} while ([DateTime]::UtcNow -lt $purgeDeadline)
if ($vaultStillDeleted) { throw 'The workshop Key Vault remains soft-deleted after the purge wait.' }

$workshopResources = Invoke-AzureCliJson -Arguments @('resource', 'list', '--subscription', $SubscriptionId)
$remaining = @($workshopResources | Where-Object {
    ([string]$_.resourceGroup) -ieq $resourceGroup -or
    ([string]$_.name).StartsWith('awz-nsp', [StringComparison]::OrdinalIgnoreCase) -or
    ([string]$_.name).StartsWith('nsp-awz-nsp', [StringComparison]::OrdinalIgnoreCase)
})
$after = Get-WorkshopBaselineSnapshot -SubscriptionId $SubscriptionId
$comparison = Compare-WorkshopBaseline -Before $baseline -After $after
Write-WorkshopJson -Path (Join-Path $work 'baseline-after-cleanup-private.json') -Value $after

$cleanup = [ordered]@{
    completedAtUtc = [DateTime]::UtcNow.ToString('o')
    validation = 'PASS'
    terraformResourcesRemaining = 0
    workshopArtifactsRemaining = $remaining.Count
    softDeletedWorkshopVaults = if ($vaultStillDeleted) { 1 } else { 0 }
    protectedBaseline = $comparison
}
if ($remaining.Count -ne 0 -or $vaultStillDeleted -or
    -not $comparison.resourcesUnchanged -or
    -not $comparison.roleAssignmentsUnchanged -or
    -not $comparison.subscriptionDiagnosticsUnchanged) {
    $cleanup.validation = 'FAIL'
}
Write-WorkshopJson -Path (Join-Path $PSScriptRoot 'evidence/cleanup-report.json') -Value $cleanup
$safe = Protect-WorkshopText -Text ($cleanup | ConvertTo-Json -Depth 30) -Runtime $runtime -Outputs $outputs
Write-Output $safe
if ($cleanup.validation -ne 'PASS') { throw 'Cleanup completed, but the protected baseline comparison failed.' }
