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

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

Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'
. (Join-Path $PSScriptRoot 'AvdWorkshop.Common.ps1')

if (-not $ConfirmCleanup) { throw 'Pass -ConfirmCleanup to remove the workshop resources.' }
$paths = Get-AvdWorkshopPaths -ScriptRoot $PSScriptRoot
$state = Read-AvdWorkshopState -Path $paths.StatePath
if ([string]$state.SubscriptionId -ne $SubscriptionId) { throw 'The requested subscription does not match the private workshop state.' }
if ([string]$state.ResourceGroup -ne 'rg-avd-deepdive-we') { throw 'Unexpected resource-group target. Cleanup stopped.' }
if ([string]$state.SessionId -notmatch '^[0-9a-f]{8}$') { throw 'Invalid workshop session marker. Cleanup stopped.' }

Invoke-AvdAzCli -Arguments @('account','set','--subscription',$SubscriptionId) -Quiet | Out-Null
$group = Invoke-AvdAzJson -Arguments @('group','show','--name',$state.ResourceGroup) -AllowFailure -Quiet
if ($group -and ([string]$group.tags.workshop -ne 'azure-virtual-desktop-deep-dive' -or [string]$group.tags.'workshop-session' -ne [string]$state.SessionId)) {
    throw 'The resource-group ownership tags do not match the private workshop session. Cleanup stopped.'
}

$removed = [ordered]@{
    TestUserRoleAssignments = $false
    License = $false
    TemporaryUserSoftDeleted = $false
    AutoscaleRoleAssignment = $false
    StorageConsent = $false
    ResourceGroup = $false
    StorageApplication = $false
    LicenseBaselineRestored = $false
    RuntimeState = $false
}

if ($PSCmdlet.ShouldProcess($state.ResourceGroup, 'Delete only the tagged AVD workshop resources, temporary identity, consent, and role assignments')) {
    foreach ($assignmentId in @($state.TestUserRoleAssignmentIds)) {
        if ($assignmentId) {
            Invoke-AvdAzCli -Arguments @('role','assignment','delete','--ids',[string]$assignmentId) -AllowFailure -Quiet | Out-Null
        }
    }
    $removed.TestUserRoleAssignments = $true

    if ([bool]$state.TestUserCreated -and $state.TestUserObjectId) {
        if ($state.AssignedLicenseSkuId) {
            Invoke-AvdGraphJson -Method POST -Path "users/$($state.TestUserObjectId)/assignLicense" -Body @{
                addLicenses = @()
                removeLicenses = @([string]$state.AssignedLicenseSkuId)
            } -AllowFailure | Out-Null
        }
        $removed.License = $true

        Invoke-AvdGraphJson -Method DELETE -Path "users/$($state.TestUserObjectId)" -AllowFailure | Out-Null
        $userCheck = Invoke-AvdGraphJson -Method GET -Path "users/$($state.TestUserObjectId)?`$select=id" -AllowFailure
        $removed.TemporaryUserSoftDeleted = (-not [bool]$userCheck)
    }
    else {
        $removed.License = $true
        $removed.TemporaryUserSoftDeleted = $true
    }

    if ([bool]$state.AutoscaleRoleCreated -and $state.AutoscaleRoleAssignmentId) {
        Invoke-AvdAzCli -Arguments @('role','assignment','delete','--ids',[string]$state.AutoscaleRoleAssignmentId) -AllowFailure -Quiet | Out-Null
        $check = Invoke-AvdAzJson -Arguments @('role','assignment','show','--ids',[string]$state.AutoscaleRoleAssignmentId) -AllowFailure -Quiet
        $removed.AutoscaleRoleAssignment = (-not [bool]$check)
    }
    else { $removed.AutoscaleRoleAssignment = $true }

    if ([bool]$state.StorageConsentCreated -and $state.StorageConsentGrantId) {
        Invoke-AvdGraphJson -Method DELETE -Path "oauth2PermissionGrants/$($state.StorageConsentGrantId)" -AllowFailure | Out-Null
        $grantCheck = Invoke-AvdGraphJson -Method GET -Path "oauth2PermissionGrants/$($state.StorageConsentGrantId)" -AllowFailure
        $removed.StorageConsent = (-not [bool]$grantCheck)
    }
    else { $removed.StorageConsent = $true }

    if ($group) {
        Invoke-AvdAzCli -Arguments @('group','delete','--name',$state.ResourceGroup,'--yes') -Quiet | Out-Null
    }
    $removed.ResourceGroup = (-not [bool](Invoke-AvdAzJson -Arguments @('group','show','--name',$state.ResourceGroup) -AllowFailure -Quiet))

    if ([bool]$state.StorageApplicationCreated -and $state.StorageApplicationObjectId) {
        $appCheck = Invoke-AvdGraphJson -Method GET -Path "applications/$($state.StorageApplicationObjectId)?`$select=id" -AllowFailure
        if ($appCheck) {
            Invoke-AvdGraphJson -Method DELETE -Path "applications/$($state.StorageApplicationObjectId)" -AllowFailure | Out-Null
        }
        $appAfter = Invoke-AvdGraphJson -Method GET -Path "applications/$($state.StorageApplicationObjectId)?`$select=id" -AllowFailure
        $removed.StorageApplication = (-not [bool]$appAfter)
    }
    else { $removed.StorageApplication = $true }

    if ($state.AssignedLicenseSkuId) {
        $baseline = @($state.LicenseInventoryBaseline | Where-Object { [string]$_.SkuId -eq [string]$state.AssignedLicenseSkuId })[0]
        $deadline = [DateTime]::UtcNow.AddMinutes(10)
        do {
            $inventory = Invoke-AvdGraphJson -Method GET -Path 'subscribedSkus'
            $current = @($inventory.value | Where-Object { [string]$_.skuId -eq [string]$state.AssignedLicenseSkuId })[0]
            $removed.LicenseBaselineRestored = ($current -and [int]$current.consumedUnits -eq [int]$baseline.Consumed)
            if (-not $removed.LicenseBaselineRestored) { Start-Sleep -Seconds 20 }
        } while (-not $removed.LicenseBaselineRestored -and [DateTime]::UtcNow -lt $deadline)
    }
    else { $removed.LicenseBaselineRestored = $true }

    $verified = @(
        $removed.TestUserRoleAssignments,
        $removed.License,
        $removed.TemporaryUserSoftDeleted,
        $removed.AutoscaleRoleAssignment,
        $removed.StorageConsent,
        $removed.ResourceGroup,
        $removed.StorageApplication,
        $removed.LicenseBaselineRestored
    )
    if ($verified -contains $false) { throw "Cleanup verification failed: $($removed | ConvertTo-Json -Compress)" }

    $cleanupEvidence = [ordered]@{
        Workshop = 'Azure Virtual Desktop Deep Dive'
        CleanedUtc = [DateTime]::UtcNow.ToString('o')
        WorkshopResourceGroupRemoved = $removed.ResourceGroup
        TemporaryUserSoftDeleted = $removed.TemporaryUserSoftDeleted
        AssignedLicenseRemoved = $removed.License
        LicenseConsumptionBaselineRestored = $removed.LicenseBaselineRestored
        WorkshopUserRoleAssignmentsRemoved = $removed.TestUserRoleAssignments
        WorkshopAutoscaleRoleAssignmentRemoved = $removed.AutoscaleRoleAssignment
        WorkshopStorageConsentRemoved = $removed.StorageConsent
        WorkshopStorageApplicationRemoved = $removed.StorageApplication
        ConditionalAccessModified = $false
        TenantMfaModified = $false
        Recovery = 'The Azure resource group and temporary tenant objects were removed. The reusable local workshop bundle remains.'
    }
    $cleanupPath = Join-Path $paths.EvidenceRoot 'cleanup-evidence.json'
    [System.IO.File]::WriteAllText($cleanupPath, ($cleanupEvidence | ConvertTo-Json -Depth 10), [System.Text.UTF8Encoding]::new($false))
    Assert-AvdSanitizedFile -Path $cleanupPath

    $runtimeResolved = [System.IO.Path]::GetFullPath($paths.RuntimeRoot)
    $workspacePrefix = [System.IO.Path]::GetFullPath($paths.WorkspaceRoot).TrimEnd([System.IO.Path]::DirectorySeparatorChar) + [System.IO.Path]::DirectorySeparatorChar
    if (-not $runtimeResolved.StartsWith($workspacePrefix, [System.StringComparison]::OrdinalIgnoreCase)) {
        throw 'Runtime cleanup target escaped the intended workspace.'
    }
    if ((Split-Path -Leaf $runtimeResolved) -ne 'azure-virtual-desktop-deep-dive') {
        throw 'Runtime cleanup target was broader than the workshop directory.'
    }
    if (Test-Path -LiteralPath $runtimeResolved) {
        Remove-Item -LiteralPath $runtimeResolved -Recurse -Force
    }
    $removed.RuntimeState = $true
    Write-Host 'AVD workshop resources and private runtime material were removed.' -ForegroundColor Green
}
