Private/Rbac.ps1

# Scope tag and role assignment management: create, rename and delete scope tags, and set the scope tags on a role assignment.
# These are single, deliberate changes (not plans), so each one is checked against loaded data, re-read live just before the
# write (drift), backed up, written, read back and recorded with enough detail to undo it. Graph beta only, and every call goes
# through Invoke-STMGraph / Invoke-STMBatch so retries, pacing, the read-only guard and error logging apply.
# Needs DeviceManagementRBAC.ReadWrite.All (delegated or application).

$script:STMRbacVerifyReads = 3          # read-backs after a role assignment write before calling it unverified (Intune can lag)
$script:STMRbacVerifyDelayMs = 1500     # wait between those read-backs

function New-STMRbacRefusal {
    # A guardrail said no before anything was sent. Kind lets the page react (Drift -> offer Refresh, ReadOnly -> offer to turn on changes).
    param([Parameter(Mandatory)][string]$Message, [string]$Kind = 'Refused')
    $e = [System.Exception]::new($Message)
    $e.Data['Kind'] = $Kind; $e.Data['Status'] = 0
    return $e
}

function Assert-STMRbacWritable {
    if (-not $script:STM.Backend) { throw 'Sign in first.' }
    if ($script:STM.Mode -ne 'ReadWrite') { throw (New-STMRbacRefusal -Kind 'ReadOnly' -Message 'Turn on changes first. This session is read-only, so nothing was sent.') }
    # Checks (or, for a user sign-in, asks for) DeviceManagementRBAC.ReadWrite.All; throws in plain English when it is missing.
    # Asking can mean a new sign-in. If that lands in another tenant the ids in hand mean something else there, so stop.
    $tenant = $script:STM.TenantId
    Assert-STMRbacWrite
    if ([string]$script:STM.TenantId -ne [string]$tenant) { throw (New-STMRbacRefusal -Kind 'Drift' -Message 'The sign-in moved to a different tenant, so nothing was changed. Press Refresh and try again.') }
    $run = $script:STM.ActiveRun
    if ($run -and $script:STM.Runs[$run] -and -not $script:STM.Runs[$run].Done) { throw (New-STMRbacRefusal -Kind 'Busy' -Message 'A change run is in progress. Let it finish before changing scope tags or role assignments.') }
    # Every rule below compares against loaded data, so it has to be there.
    if (-not $script:STM.Tags) { [void](Update-STMScopeTags) }
    if (-not $script:STM.RoleAssignmentsLoadedAt) { [void](Update-STMRoleAssignments) }
}

function Get-STMRbacFolder {
    $d = Join-Path (Get-STMDataRoot) 'RbacChanges'
    if (-not (Test-Path -LiteralPath $d)) { New-Item -ItemType Directory -Path $d -Force | Out-Null }
    return $d
}

function ConvertTo-STMRbacIdSet {
    # Scope tag id lists are sets: order and duplicates never matter. Callers wrap the result in @().
    param([string[]]$Ids)
    return [string[]]@(@($Ids) | ForEach-Object { "$_".Trim() } | Where-Object { $_ -ne '' } | Sort-Object -Unique)
}

function Get-STMRbacTagSide {
    # The small before/after object for a role assignment: ids plus names, so the history reads without a lookup.
    param([string[]]$Ids)
    $set = @(ConvertTo-STMRbacIdSet -Ids $Ids)
    return [pscustomobject][ordered]@{ tagIds = [string[]]$set; tagNames = [string[]]@($set | ForEach-Object { Get-STMTagName $_ }) }
}

function Get-STMRbacNameList {
    param([string[]]$Ids)
    $n = @(@($Ids) | ForEach-Object { Get-STMTagName $_ })
    if (-not $n.Count) { return 'none' }
    return ($n -join ', ')
}

function Get-STMRbacProtectedIds {
    # Protected tags by setting. Matching on the name as well as Get-STMProtectedTagIds covers a protected name carried by two tags,
    # which that function reports as ambiguous and leaves out.
    $names = @($script:STM.Settings.ProtectedScopeTagNames | Where-Object { $_ })
    $ids = @((Get-STMProtectedTagIds).Ids)
    foreach ($t in @($script:STM.Tags)) { if ($names -contains $t.Name) { $ids += $t.Id } }
    return @($ids | Where-Object { $_ } | Sort-Object -Unique)
}

function Get-STMRbacLoadedTag {
    param([string]$Id)
    return (@($script:STM.Tags) | Where-Object { $_.Id -eq $Id } | Select-Object -First 1)
}

function Get-STMRbacCleanName {
    param([string]$Name, [string]$ExceptId)
    $n = "$Name".Trim()
    if (-not $n) { throw (New-STMRbacRefusal -Kind 'Invalid' -Message 'Give the scope tag a name.') }
    if ($n.Length -gt 128) { throw (New-STMRbacRefusal -Kind 'Invalid' -Message "A scope tag name can be at most 128 characters; this one has $($n.Length).") }
    if ($n -match '[\x00-\x1f\x7f]') { throw (New-STMRbacRefusal -Kind 'Invalid' -Message 'A scope tag name cannot contain line breaks or control characters.') }
    $dup = @($script:STM.Tags | Where-Object { $_.Name -ieq $n -and $_.Id -ne $ExceptId })
    if ($dup.Count) { throw (New-STMRbacRefusal -Kind 'Invalid' -Message "A scope tag named '$($dup[0].Name)' already exists (id $($dup[0].Id)). Scope tag names must be unique.") }
    return $n
}

function Get-STMRbacCleanDescription {
    param([string]$Description)
    $d = "$Description".Trim()
    if ($d.Length -gt 1024) { throw (New-STMRbacRefusal -Kind 'Invalid' -Message "A scope tag description can be at most 1024 characters; this one has $($d.Length).") }
    return $d
}

function Get-STMRbacLive {
    # Live read just before a write. A 404 becomes a plain refusal; any other Graph error passes through unchanged (nothing was sent).
    param([Parameter(Mandatory)][string]$Uri, [Parameter(Mandatory)][string]$What)
    try { return Invoke-STMGraph -Method GET -Uri $Uri }
    catch {
        if ($_.Exception.Data['Kind'] -eq 'NotFound') { throw (New-STMRbacRefusal -Kind 'NotFound' -Message "$What is already gone from Intune. Press Refresh.") }
        throw
    }
}

function Get-STMRbacLiveTagName {
    # Same rule as Update-STMScopeTags: the built-in tag can come back without a display name.
    param($Live, [string]$Id)
    $n = [string](Get-STMProp $Live 'displayName')
    if ($Id -eq '0' -and -not $n) { return 'Default' }
    return $n
}

function Get-STMRbacTagUse {
    # What the loaded data says still uses a tag, in plain English. Empty = nothing loaded uses it.
    param([Parameter(Mandatory)][string]$Id, [string[]]$LiveGroupIds)
    $why = [System.Collections.Generic.List[string]]::new()
    $n = 0; $examples = [System.Collections.Generic.List[string]]::new()
    foreach ($row in $script:STM.Inventory.Values) {
        if (@($row.TagIds) -contains $Id) { $n++; if ($examples.Count -lt 3) { $examples.Add("$($row.Name) ($($row.TypeLabel))") } }
    }
    if ($n) { $why.Add("$n loaded object(s) carry it, for example $($examples -join '; ')") }
    $ras = @($script:STM.RoleAssignments | Where-Object { @($_.TagIds) -contains $Id })
    if ($ras.Count) { $why.Add("$($ras.Count) role assignment(s) use it: $((@($ras | Select-Object -First 5 | ForEach-Object { if ($_.Name) { $_.Name } else { $_.Id } })) -join ', ')") }
    $tag = Get-STMRbacLoadedTag -Id $Id
    $groups = @(@(if ($tag) { $tag.AssignedGroupIds }) + @($LiveGroupIds) | Where-Object { $_ } | Sort-Object -Unique)
    if ($groups.Count) {
        $names = @($groups | Select-Object -First 5 | ForEach-Object { if ($script:STM.GroupNames.ContainsKey($_)) { $script:STM.GroupNames[$_] } else { $_ } })
        $why.Add("it is assigned to $($groups.Count) group(s), which puts it on their devices automatically: $($names -join ', ')")
    }
    return @($why)
}

function Invoke-STMRbacWrite {
    # One write. Never throws: a write that fails still gets a history record. Returns @{ Ok; Response; Error }.
    param([Parameter(Mandatory)][ValidateSet('POST', 'PATCH', 'DELETE')][string]$Method, [Parameter(Mandatory)][string]$Uri, $Body)
    $out = @{ Ok = $false; Response = $null; Error = '' }
    try {
        if ($Method -eq 'DELETE') {
            # Invoke-STMGraph takes GET, PATCH and POST only, so a delete travels as a one-item $batch: same transport, retries,
            # write pacing and read-only guard.
            $r = (Invoke-STMBatch -Requests @(@{ id = 'delete'; method = 'DELETE'; url = "/$Uri"; body = $null }))['delete']
            if (-not $r -or $r.status -lt 200 -or $r.status -ge 300) {
                $status = 0; if ($r) { $status = [int]$r.status }
                if ($r -and $r.body) { throw (New-STMGraphError -Status $status -Body ($r.body | ConvertTo-Json -Depth 10 -Compress) -Uri $Uri -Method 'DELETE') }
                # No body: the whole batch call failed and Invoke-STMGraph has already logged it.
                $text = 'No response came back from Microsoft Graph.'; if ($r -and $r.error) { $text = [string]$r.error }
                $e = [System.Exception]::new($text); $e.Data['Status'] = $status; $e.Data['Kind'] = Get-STMErrorKind -Status $status -Message $text
                throw $e
            }
        }
        else { $out.Response = Invoke-STMGraph -Method $Method -Uri $Uri -Body $Body }
        $out.Ok = $true
    }
    catch {
        $msg = [string]$_.Exception.Message; $kind = [string]$_.Exception.Data['Kind']
        if ($kind -eq 'MultiAdminApprovalRequired') { $msg += ' This tenant requires Multi Admin Approval for this change; request approval in the Intune admin center.' }
        elseif ($kind -eq 'Forbidden' -and $msg -notmatch 'DeviceManagementRBAC') { $msg += ' Scope tag and role assignment changes need the DeviceManagementRBAC.ReadWrite.All permission and an Intune role that may manage roles.' }
        $out.Error = $msg
    }
    return $out
}

function New-STMRbacChange {
    param([Parameter(Mandatory)][string]$Kind, [string]$TargetId, [string]$TargetName, $Before, $After, [string]$UndoOf = '')
    $now = [DateTime]::UtcNow
    return [pscustomobject][ordered]@{
        ChangeId = '{0}-{1}' -f $now.ToString('yyyyMMdd-HHmmss'), ([guid]::NewGuid().ToString('N').Substring(0, 4))
        AtUtc = $now.ToString('o'); Actor = [string]$script:STM.Account; Tenant = [string]$script:STM.TenantId
        Kind = $Kind; TargetId = $TargetId; TargetName = $TargetName; Before = $Before; After = $After
        Result = ''; Detail = ''; UndoOf = $UndoOf; CanUndo = $false; Undone = $false
    }
}

function Save-STMRbacBackup {
    # The full object as Graph returned it, on disk before the write is sent.
    param([Parameter(Mandatory)]$Change, [Parameter(Mandatory)][string]$Uri, $Object, [hashtable]$Extra)
    $o = [ordered]@{ changeId = $Change.ChangeId; kind = $Change.Kind; tenant = $Change.Tenant; readAtUtc = [DateTime]::UtcNow.ToString('o'); uri = $Uri; object = $Object }
    if ($Extra) { foreach ($k in $Extra.Keys) { $o[$k] = $Extra[$k] } }
    $o | ConvertTo-Json -Depth 20 | Set-Content -LiteralPath (Join-Path (Get-STMRbacFolder) "$($Change.ChangeId)-before.json") -Encoding utf8
}

function Complete-STMRbacChange {
    # Sets the outcome, appends the history line and the audit line, and marks the original as undone when this was a working undo.
    param([Parameter(Mandatory)]$Change, [Parameter(Mandatory)][ValidateSet('Applied', 'AppliedUnverified', 'Failed')][string]$Result, [Parameter(Mandatory)][string]$Detail, [bool]$CanUndo = $false)
    $Change.Result = $Result
    $Change.Detail = if ($Change.UndoOf) { "Undo of change $($Change.UndoOf). $Detail" } else { $Detail }
    # An undo is never itself undoable (make the change again instead), and neither is a failed or empty change.
    $Change.CanUndo = [bool]($CanUndo -and -not $Change.UndoOf -and $Result -ne 'Failed')
    # The write has already happened (or failed) by now, so a full disk here must not hide the outcome from the admin.
    try {
        $file = Join-Path (Get-STMRbacFolder) 'changes.jsonl'
        Add-Content -LiteralPath $file -Value ($Change | ConvertTo-Json -Compress -Depth 6) -Encoding utf8 -ErrorAction Stop
        if ($Change.UndoOf -and $Result -ne 'Failed') {
            # Append-only history: the original line is never rewritten; Get-STMRbacChanges applies this marker when reading.
            $marker = [ordered]@{ Marker = 'Undone'; ChangeId = $Change.UndoOf; By = $Change.ChangeId; AtUtc = [DateTime]::UtcNow.ToString('o') }
            Add-Content -LiteralPath $file -Value ($marker | ConvertTo-Json -Compress) -Encoding utf8 -ErrorAction Stop
        }
        Write-STMAudit -Event 'RbacChange' -Data @{ changeId = $Change.ChangeId; kind = $Change.Kind; targetId = $Change.TargetId; targetName = $Change.TargetName; before = $Change.Before; after = $Change.After; result = $Result; detail = $Change.Detail; undoOf = $Change.UndoOf }
    }
    catch { $Change.Detail += " This entry could not be written to the change history ($($_.Exception.Message)), so note it yourself." }
    return $Change
}

function Update-STMRbacState {
    # Reloads what the page shows. A reload that fails must not turn a finished write into an error; returns '' or a note for Detail.
    param([switch]$Tags, [switch]$Assignments)
    try {
        if ($Tags) { [void](Update-STMScopeTags) }
        if ($Assignments) { [void](Update-STMRoleAssignments) }
        return ''
    }
    catch { return ' The lists could not be reloaded afterwards; press Refresh.' }
}

function Get-STMRbacChanges {
    <# Change history for scope tags and role assignments, newest first (this tenant only unless -AllTenants). #>
    param([switch]$AllTenants)
    $file = Join-Path (Join-Path (Get-STMDataRoot) 'RbacChanges') 'changes.jsonl'
    if (-not (Test-Path -LiteralPath $file)) { return @() }
    $records = [System.Collections.Generic.List[object]]::new(); $undone = @{}
    foreach ($line in @(Get-Content -LiteralPath $file -Encoding utf8)) {
        if ([string]::IsNullOrWhiteSpace($line)) { continue }
        # A damaged line (interrupted write, hand edit) must not hide the rest of the history.
        $o = $null
        try { $o = $line | ConvertFrom-STMJson } catch { continue }
        if (-not $o) { continue }
        if ($o.PSObject.Properties['Marker']) { if ($o.Marker -eq 'Undone') { $undone[[string]$o.ChangeId] = $true }; continue }
        if (@('ChangeId', 'Kind', 'AtUtc', 'Tenant', 'Result', 'UndoOf', 'CanUndo', 'Undone' | Where-Object { -not $o.PSObject.Properties[$_] }).Count) { continue }
        $o.AtUtc = ConvertTo-STMIsoDate $o.AtUtc
        $records.Add($o)
    }
    $out = [System.Collections.Generic.List[object]]::new()
    for ($i = $records.Count - 1; $i -ge 0; $i--) {
        $r = $records[$i]
        if (-not $AllTenants -and $script:STM.TenantId -and [string]$r.Tenant -ne [string]$script:STM.TenantId) { continue }
        if ($undone.ContainsKey([string]$r.ChangeId)) { $r.Undone = $true; $r.CanUndo = $false }
        $out.Add($r)
    }
    return $out.ToArray()
}

# ---- Scope tags ----

function Invoke-STMRbacTagCreateCore {
    param([string]$Name, [string]$Description, [string]$UndoOf = '', [string]$OldId = '')
    Assert-STMRbacWritable
    $n = Get-STMRbacCleanName -Name $Name
    $d = Get-STMRbacCleanDescription -Description $Description
    $change = New-STMRbacChange -Kind 'TagCreate' -TargetId '' -TargetName $n -Before $null -After ([pscustomobject][ordered]@{ name = $n; description = $d }) -UndoOf $UndoOf
    $w = Invoke-STMRbacWrite -Method POST -Uri 'deviceManagement/roleScopeTags' -Body ([ordered]@{ displayName = $n; description = $d })
    $note = Update-STMRbacState -Tags
    if (-not $w.Ok) { return Complete-STMRbacChange -Change $change -Result Failed -Detail "Intune did not accept the new scope tag '$n': $($w.Error)$note" }
    $id = [string](Get-STMProp $w.Response 'id')
    if (-not $id) { $byName = @($script:STM.Tags | Where-Object { $_.Name -ceq $n }); if ($byName.Count -eq 1) { $id = $byName[0].Id } }
    $change.TargetId = $id
    $what = "Created scope tag '$n' (id $id)."
    if ($UndoOf) { $what = "Recreated scope tag '$n'. It has a new id ($id; it was $OldId), so anything that referred to the old id has to be pointed at the new tag." }
    if ($id -and (Get-STMRbacLoadedTag -Id $id)) { return Complete-STMRbacChange -Change $change -Result Applied -Detail "$what$note" -CanUndo $true }
    return Complete-STMRbacChange -Change $change -Result AppliedUnverified -Detail "$what Intune accepted it, but it does not show in the tag list yet. Check it in the Intune admin center (Tenant administration > Roles > Scope tags).$note" -CanUndo ([bool]$id)
}

function Invoke-STMRbacTagUpdateCore {
    # $ExpectName/$ExpectDescription: what the caller last saw (the loaded tag, or for an undo the change's "after").
    param([string]$Id, [string]$Name, [string]$Description, [string]$ExpectName, [string]$ExpectDescription, [string]$UndoOf = '', $UndoBefore)
    Assert-STMRbacWritable
    $tag = Get-STMRbacLoadedTag -Id $Id
    if (-not $tag) { throw (New-STMRbacRefusal -Kind 'NotFound' -Message "Scope tag $Id is not in the loaded list. Press Refresh.") }
    if (-not $UndoOf) { $ExpectName = [string]$tag.Name; $ExpectDescription = [string]$tag.Description }
    $n = Get-STMRbacCleanName -Name $Name -ExceptId $Id
    $d = Get-STMRbacCleanDescription -Description $Description
    if ($n -cne $tag.Name) {
        if ($tag.IsBuiltIn -or $Id -eq '0') { throw (New-STMRbacRefusal -Kind 'BuiltIn' -Message "'$($tag.Name)' is the built-in scope tag and cannot be renamed.") }
        if (@(Get-STMRbacProtectedIds) -contains $Id) { throw (New-STMRbacRefusal -Kind 'Protected' -Message "'$($tag.Name)' is a protected scope tag (setting ProtectedScopeTagNames) and cannot be renamed with this tool.") }
    }
    $uri = "deviceManagement/roleScopeTags/$Id"
    $live = Get-STMRbacLive -Uri $uri -What "Scope tag '$($tag.Name)'"
    $liveName = Get-STMRbacLiveTagName -Live $live -Id $Id; $liveDesc = [string](Get-STMProp $live 'description')
    if ($liveName -cne $ExpectName -or $liveDesc -cne $ExpectDescription) {
        if ($UndoOf -and $UndoBefore -and $liveName -ceq [string]$UndoBefore.name -and $liveDesc -ceq [string]$UndoBefore.description) { throw (New-STMRbacRefusal -Kind 'Undo' -Message 'Nothing to undo: Intune already shows the earlier name and description. Press Refresh.') }
        if ($UndoOf) { throw (New-STMRbacRefusal -Kind 'Drift' -Message 'This scope tag was changed again after that change, so it was not undone. Press Refresh and look at it first.') }
        throw (New-STMRbacRefusal -Kind 'Drift' -Message 'This scope tag changed since it was loaded. Press Refresh and try again.')
    }
    $before = [pscustomobject][ordered]@{ name = $liveName; description = $liveDesc }
    $change = New-STMRbacChange -Kind 'TagUpdate' -TargetId $Id -TargetName $n -Before $before -After ([pscustomobject][ordered]@{ name = $n; description = $d }) -UndoOf $UndoOf
    if ($n -ceq $liveName -and $d -ceq $liveDesc) { return Complete-STMRbacChange -Change $change -Result Applied -Detail 'No change needed' }
    Save-STMRbacBackup -Change $change -Uri $uri -Object $live
    $w = Invoke-STMRbacWrite -Method PATCH -Uri $uri -Body ([ordered]@{ displayName = $n; description = $d })
    $note = Update-STMRbacState -Tags
    if (-not $w.Ok) { return Complete-STMRbacChange -Change $change -Result Failed -Detail "Intune did not accept the change to scope tag '$liveName': $($w.Error)$note" }
    $what = if ($n -cne $liveName -and $d -cne $liveDesc) { "Renamed scope tag '$liveName' to '$n' and updated its description." }
        elseif ($n -cne $liveName) { "Renamed scope tag '$liveName' to '$n'." }
        else { "Updated the description of scope tag '$n'." }
    $now = Get-STMRbacLoadedTag -Id $Id
    if ($now -and $now.Name -ceq $n -and $now.Description -ceq $d) { return Complete-STMRbacChange -Change $change -Result Applied -Detail "$what$note" -CanUndo $true }
    return Complete-STMRbacChange -Change $change -Result AppliedUnverified -Detail "$what Intune accepted it, but reading the tag back did not show it yet. Check it in the Intune admin center (Tenant administration > Roles > Scope tags).$note" -CanUndo $true
}

function Invoke-STMRbacTagDeleteCore {
    # $ExpectName: the name the admin typed to confirm (must match exactly), or for an undo the name the tag was created with.
    param([string]$Id, [string]$ExpectName, [string]$UndoOf = '')
    Assert-STMRbacWritable
    $uri = "deviceManagement/roleScopeTags/$Id"
    $tag = Get-STMRbacLoadedTag -Id $Id
    if (-not $tag) {
        # Not loaded: say whether it is gone or just not loaded yet. Either way nothing is deleted on stale data.
        [void](Get-STMRbacLive -Uri $uri -What "Scope tag $Id")
        throw (New-STMRbacRefusal -Kind 'NotFound' -Message "Scope tag $Id is not in the loaded list. Press Refresh.")
    }
    if ($tag.IsBuiltIn -or $Id -eq '0') { throw (New-STMRbacRefusal -Kind 'BuiltIn' -Message "'$($tag.Name)' is the built-in scope tag and cannot be deleted.") }
    if (@(Get-STMRbacProtectedIds) -contains $Id) { throw (New-STMRbacRefusal -Kind 'Protected' -Message "'$($tag.Name)' is a protected scope tag (setting ProtectedScopeTagNames) and cannot be deleted with this tool.") }
    if (-not $UndoOf -and $ExpectName -cne $tag.Name) { throw (New-STMRbacRefusal -Kind 'Confirm' -Message "To delete this scope tag, type its name exactly: $($tag.Name)") }
    $live = Get-STMRbacLive -Uri $uri -What "Scope tag '$($tag.Name)'"
    $liveName = Get-STMRbacLiveTagName -Live $live -Id $Id
    if ($liveName -cne $ExpectName -or $liveName -cne $tag.Name) {
        if ($UndoOf) { throw (New-STMRbacRefusal -Kind 'Drift' -Message "This scope tag was renamed after it was created (now '$liveName'), so it was not deleted. Press Refresh and look at it first.") }
        throw (New-STMRbacRefusal -Kind 'Drift' -Message 'This scope tag changed since it was loaded. Press Refresh and try again.')
    }
    # In-use check. Role assignments that could not be read might use the tag, so they block the delete rather than pass silently.
    $unread = @($script:STM.RoleAssignments | Where-Object { $_.ReadError })
    if ($unread.Count) { throw (New-STMRbacRefusal -Kind 'InUse' -Message "$($unread.Count) role assignment(s) could not be read, so it is not known whether they use this scope tag. Press Refresh; if they still cannot be read, delete the tag in the Intune admin center.") }
    # Group assignments are read live as well (they also go into the backup); the loaded list still counts if this read fails.
    $liveAssignments = @()
    try { $liveAssignments = @((Invoke-STMGraph -Method GET -Uri "$uri/assignments").value) } catch { $liveAssignments = @() }
    $liveGroups = @($liveAssignments | ForEach-Object { [string](Get-STMProp (Get-STMProp $_ 'target') 'groupId') } | Where-Object { $_ })
    $use = @(Get-STMRbacTagUse -Id $Id -LiveGroupIds $liveGroups)
    if ($use.Count) { throw (New-STMRbacRefusal -Kind 'InUse' -Message "Scope tag '$($tag.Name)' is still in use, so it was not deleted: $($use -join '; '). Remove it from these first.") }
    $before = [pscustomobject][ordered]@{ name = $liveName; description = [string](Get-STMProp $live 'description') }
    $change = New-STMRbacChange -Kind 'TagDelete' -TargetId $Id -TargetName $liveName -Before $before -After $null -UndoOf $UndoOf
    Save-STMRbacBackup -Change $change -Uri $uri -Object $live -Extra @{ assignments = $liveAssignments }
    $w = Invoke-STMRbacWrite -Method DELETE -Uri $uri
    $note = Update-STMRbacState -Tags
    if (-not $w.Ok) { return Complete-STMRbacChange -Change $change -Result Failed -Detail "Intune did not delete scope tag '$liveName': $($w.Error)$note" }
    # Say what the in-use check actually covered: only loaded objects can be checked.
    $checked = if ($script:STM.Inventory.Count) { "Nothing loaded used it ($($script:STM.Inventory.Count) loaded objects and $(@($script:STM.RoleAssignments).Count) role assignments checked)." }
        else { "No Intune objects were loaded, so only role assignments and the tag's groups were checked for use." }
    $what = "Deleted scope tag '$liveName' (id $Id). $checked"
    if (-not (Get-STMRbacLoadedTag -Id $Id)) { return Complete-STMRbacChange -Change $change -Result Applied -Detail "$what$note" -CanUndo $true }
    return Complete-STMRbacChange -Change $change -Result AppliedUnverified -Detail "$what Intune accepted the delete, but the tag still shows in the list. Check it in the Intune admin center (Tenant administration > Roles > Scope tags).$note" -CanUndo $true
}

function Invoke-STMTagCreate {
    <# Creates a scope tag. Returns the change record. #>
    param([string]$Name, [string]$Description)
    return Invoke-STMRbacTagCreateCore -Name $Name -Description $Description
}

function Invoke-STMTagUpdate {
    <# Renames a scope tag and/or changes its description. Returns the change record. #>
    param([Parameter(Mandatory)][string]$Id, [string]$Name, [string]$Description)
    return Invoke-STMRbacTagUpdateCore -Id $Id -Name $Name -Description $Description
}

function Invoke-STMTagDelete {
    <# Deletes an unused scope tag after the admin typed its name. Returns the change record. #>
    param([Parameter(Mandatory)][string]$Id, [string]$ConfirmName)
    return Invoke-STMRbacTagDeleteCore -Id $Id -ExpectName $ConfirmName
}

# ---- Role assignments ----

function Invoke-STMRbacAssignmentCore {
    # $AllowProtectedRemoval: protected tag ids an undo may take off again because the change being undone put them there.
    param([string]$Id, [string[]]$TagIds, [string[]]$ExpectedTagIds, [string[]]$AllowProtectedRemoval = @(), [string]$UndoOf = '', [string[]]$UndoBefore)
    Assert-STMRbacWritable
    if (-not $PSBoundParameters.ContainsKey('ExpectedTagIds')) {
        $loaded = @($script:STM.RoleAssignments) | Where-Object { $_.Id -eq $Id } | Select-Object -First 1
        if (-not $loaded) { throw (New-STMRbacRefusal -Kind 'NotFound' -Message "Role assignment $Id is not in the loaded list. Press Refresh.") }
        $ExpectedTagIds = @($loaded.TagIds)
    }
    $want = @(ConvertTo-STMRbacIdSet -Ids $TagIds)
    $expected = @(ConvertTo-STMRbacIdSet -Ids $ExpectedTagIds)
    # Deliberately no wording about what an untagged assignment can see: that is Intune's rule to explain, and a choice to make there.
    if (-not $want.Count) { throw (New-STMRbacRefusal -Kind 'Invalid' -Message 'Pick at least one scope tag. Leaving a role assignment without any scope tag changes what its admins can see, so that is done on purpose in the Intune admin center, not here.') }
    $known = @($script:STM.Tags | ForEach-Object { $_.Id })
    $unknown = @($want | Where-Object { $known -notcontains $_ })
    if ($unknown.Count) { throw (New-STMRbacRefusal -Kind 'Invalid' -Message "Scope tag id(s) $($unknown -join ', ') are not in the loaded tag list. Press Refresh and try again.") }
    $uri = "deviceManagement/roleAssignments/$Id"
    $live = Get-STMRbacLive -Uri $uri -What 'This role assignment'
    $name = [string](Get-STMProp $live 'displayName'); if (-not $name) { $name = $Id }
    $now = @(ConvertTo-STMRbacIdSet -Ids @(Get-STMProp $live 'roleScopeTagIds'))
    if (($now -join ',') -ne ($expected -join ',')) {
        if ($UndoOf -and ($now -join ',') -eq ((@(ConvertTo-STMRbacIdSet -Ids $UndoBefore)) -join ',')) { throw (New-STMRbacRefusal -Kind 'Undo' -Message 'Nothing to undo: Intune already shows the earlier scope tags on this role assignment. Press Refresh.') }
        if ($UndoOf) { throw (New-STMRbacRefusal -Kind 'Drift' -Message 'This role assignment was changed again after that change, so it was not undone. Press Refresh and look at it first.') }
        throw (New-STMRbacRefusal -Kind 'Drift' -Message 'This role assignment changed since it was loaded. Press Refresh and try again.')
    }
    $added = @($want | Where-Object { $now -notcontains $_ }); $removed = @($now | Where-Object { $want -notcontains $_ })
    $protected = @(Get-STMRbacProtectedIds)
    $blocked = @($removed | Where-Object { $protected -contains $_ -and $AllowProtectedRemoval -notcontains $_ })
    if ($blocked.Count) { throw (New-STMRbacRefusal -Kind 'Protected' -Message "Protected scope tag(s) $(Get-STMRbacNameList -Ids $blocked) cannot be removed from a role assignment with this tool (setting ProtectedScopeTagNames).") }
    $change = New-STMRbacChange -Kind 'AssignmentTags' -TargetId $Id -TargetName $name -Before (Get-STMRbacTagSide -Ids $now) -After (Get-STMRbacTagSide -Ids $want) -UndoOf $UndoOf
    if (-not $added.Count -and -not $removed.Count) { return Complete-STMRbacChange -Change $change -Result Applied -Detail 'No change needed' }
    Save-STMRbacBackup -Change $change -Uri $uri -Object $live
    # Full replacement list; the type name is required for this resource.
    $w = Invoke-STMRbacWrite -Method PATCH -Uri $uri -Body ([ordered]@{ '@odata.type' = '#microsoft.graph.deviceAndAppManagementRoleAssignment'; roleScopeTagIds = [string[]]$want })
    if (-not $w.Ok) {
        $note = Update-STMRbacState -Assignments
        return Complete-STMRbacChange -Change $change -Result Failed -Detail "Intune did not accept the scope tag change on role assignment '$name': $($w.Error)$note"
    }
    # Read back. Intune can take a moment to show a write, so a mismatch is re-read before it is reported.
    $got = $null; $verified = $false
    for ($i = 1; $i -le $script:STMRbacVerifyReads -and -not $verified; $i++) {
        if ($i -gt 1) { Start-Sleep -Milliseconds $script:STMRbacVerifyDelayMs }
        try { $got = @(ConvertTo-STMRbacIdSet -Ids @(Get-STMProp (Invoke-STMGraph -Method GET -Uri $uri) 'roleScopeTagIds')); $verified = (($got -join ',') -eq ($want -join ',')) }
        catch { $got = $null }
    }
    $note = Update-STMRbacState -Assignments
    $delta = @(); if ($added.Count) { $delta += "added $(Get-STMRbacNameList -Ids $added)" }; if ($removed.Count) { $delta += "removed $(Get-STMRbacNameList -Ids $removed)" }
    if ($verified) { return Complete-STMRbacChange -Change $change -Result Applied -Detail "Role assignment '$name' now has the scope tags $(Get-STMRbacNameList -Ids $want) ($($delta -join '; ')). Read back from Intune and confirmed.$note" -CanUndo $true }
    $shows = if ($null -eq $got) { 'it could not be read back' } else { "it still shows $(Get-STMRbacNameList -Ids $got)" }
    return Complete-STMRbacChange -Change $change -Result AppliedUnverified -Detail "Intune accepted the scope tag change on role assignment '$name' ($($delta -join '; ')), but $shows. Check this role assignment in the Intune admin center (Tenant administration > Roles) before relying on it.$note" -CanUndo $true
}

function Invoke-STMAssignmentTags {
    <# Replaces the scope tags on a role assignment. -ExpectedTagIds is what the caller last saw (defaults to the loaded value). Returns the change record. #>
    param([Parameter(Mandatory)][string]$Id, [string[]]$TagIds, [string[]]$ExpectedTagIds)
    $p = @{ Id = $Id; TagIds = $TagIds }
    if ($PSBoundParameters.ContainsKey('ExpectedTagIds')) { $p.ExpectedTagIds = $ExpectedTagIds }
    return Invoke-STMRbacAssignmentCore @p
}

# ---- Undo ----

function Invoke-STMRbacUndo {
    <# Reverses one recorded change, under the same guardrails as making it. The undo is recorded as its own change. #>
    param([Parameter(Mandatory)][string]$ChangeId)
    Assert-STMRbacWritable
    $c = @(Get-STMRbacChanges -AllTenants | Where-Object { $_.ChangeId -eq $ChangeId }) | Select-Object -First 1
    if (-not $c) { throw (New-STMRbacRefusal -Kind 'Undo' -Message "Change $ChangeId is not in the change history.") }
    if ([string]$c.Tenant -ne [string]$script:STM.TenantId) { throw (New-STMRbacRefusal -Kind 'Undo' -Message "That change was made in another tenant ($($c.Tenant)). Sign in to that tenant to undo it.") }
    if ($c.UndoOf) { throw (New-STMRbacRefusal -Kind 'Undo' -Message 'That entry is itself an undo. To reverse it, make the change again.') }
    if ($c.Undone) { throw (New-STMRbacRefusal -Kind 'Undo' -Message 'That change was already undone.') }
    if ($c.Result -eq 'Failed') { throw (New-STMRbacRefusal -Kind 'Undo' -Message 'That change failed, so there is nothing to undo.') }
    if (-not $c.CanUndo) { throw (New-STMRbacRefusal -Kind 'Undo' -Message 'That entry changed nothing, so there is nothing to undo.') }
    switch ([string]$c.Kind) {
        'TagCreate' { return Invoke-STMRbacTagDeleteCore -Id ([string]$c.TargetId) -ExpectName ([string]$c.After.name) -UndoOf $ChangeId }
        'TagUpdate' { return Invoke-STMRbacTagUpdateCore -Id ([string]$c.TargetId) -Name ([string]$c.Before.name) -Description ([string]$c.Before.description) -ExpectName ([string]$c.After.name) -ExpectDescription ([string]$c.After.description) -UndoOf $ChangeId -UndoBefore $c.Before }
        'TagDelete' { return Invoke-STMRbacTagCreateCore -Name ([string]$c.Before.name) -Description ([string]$c.Before.description) -UndoOf $ChangeId -OldId ([string]$c.TargetId) }
        'AssignmentTags' {
            $before = @(ConvertTo-STMRbacIdSet -Ids @($c.Before.tagIds)); $after = @(ConvertTo-STMRbacIdSet -Ids @($c.After.tagIds))
            # Tags that change added may come off again even when protected; protected tags the assignment had before stay put.
            $addedThen = @($after | Where-Object { $before -notcontains $_ })
            return Invoke-STMRbacAssignmentCore -Id ([string]$c.TargetId) -TagIds $before -ExpectedTagIds $after -AllowProtectedRemoval $addedThen -UndoOf $ChangeId -UndoBefore $before
        }
        default { throw (New-STMRbacRefusal -Kind 'Undo' -Message "Change $ChangeId is of a kind this version cannot undo ($($c.Kind)).") }
    }
}