Private/Mock.ps1

# In-memory stand-in for Microsoft Graph (beta) used by the demo and the tests. It behaves like Graph where it matters here:
# paging, $select, $filter (eq / startswith), $batch (20 max), PATCH validation, 404 for missing endpoints, and injected faults
# (429 with and without Retry-After, persistent failures, Multi Admin Approval 403s, read-after-write lag, drift).
# Scope tags can be created, read, renamed and deleted; role assignments accept a roleScopeTagIds PATCH (NoApplyIds makes one
# be accepted but silently not applied, the way Intune sometimes answers 2xx and changes nothing).
# No real tenant data is used; every name below is invented.

function New-STMMockTenant {
    param([int]$DeviceCount = 3000, [int]$Seed = 42, [string[]]$MissingTypes = @('MicrosoftTunnelSite', 'WindowsQualityUpdatePolicy'))
    $rnd = [System.Random]::new($Seed)
    $m = @{
        Collections = @{}; ById = @{}; Groups = @{}; TagAssignments = @{}; RoleDefinitions = @(); RoleAssignments = @{}
        Options = @{
            PageSize = 100; ThrottleNext = 0; ThrottleRetryAfter = $null; FailIds = @{}; MaaIds = @{}; LagIds = @{}
            NoSelectPaths = @(); MissingPaths = @(); ForbiddenPaths = @(); DeviceListOmitsTags = $false; RequireODataType = @()
            NoApplyIds = @{}
        }
        Requests = [System.Collections.Generic.List[object]]::new()
        Writes = [System.Collections.Generic.List[object]]::new()
    }
    $tags = @(
        @{ id = '0'; displayName = 'Default'; description = 'Built-in default scope tag'; isBuiltIn = $true }
        @{ id = '1'; displayName = 'Corp-Windows'; description = 'Corporate Windows endpoints'; isBuiltIn = $false }
        @{ id = '2'; displayName = 'Corp-Mobile'; description = 'Corporate iOS and Android'; isBuiltIn = $false }
        @{ id = '3'; displayName = 'BYOD-Mobile'; description = 'Personal devices with app protection'; isBuiltIn = $false }
        @{ id = '4'; displayName = 'Region-East'; description = 'East region help desk'; isBuiltIn = $false }
        @{ id = '5'; displayName = 'Region-West'; description = 'West region help desk'; isBuiltIn = $false }
        @{ id = '6'; displayName = 'Servers-Kiosk'; description = 'Shared and kiosk devices'; isBuiltIn = $false }
        @{ id = '7'; displayName = 'PAW-Protected'; description = 'Privileged access workstations (protected)'; isBuiltIn = $false }
        @{ id = '8'; displayName = 'Pilot'; description = 'Pilot rings'; isBuiltIn = $false }
    )
    $m.Collections['deviceManagement/roleScopeTags'] = [System.Collections.Generic.List[object]]::new()
    foreach ($t in $tags) { $m.Collections['deviceManagement/roleScopeTags'].Add([pscustomobject]$t) }
    $m.Groups = @{
        'a1111111-0000-4000-8000-000000000001' = 'SG-Intune-Helpdesk-East'; 'a1111111-0000-4000-8000-000000000002' = 'SG-Intune-Helpdesk-West'
        'a1111111-0000-4000-8000-000000000003' = 'SG-Intune-Mobile-Admins'; 'a1111111-0000-4000-8000-000000000004' = 'SG-Devices-East'
        'a1111111-0000-4000-8000-000000000005' = 'SG-Devices-West'; 'a1111111-0000-4000-8000-000000000006' = 'SG-Intune-Readers'
        'a1111111-0000-4000-8000-000000000007' = 'SG-Kiosk-Devices'
    }
    $m.TagAssignments['7'] = @()
    $m.TagAssignments['6'] = @('a1111111-0000-4000-8000-000000000007')

    $m.RoleDefinitions = @(
        [pscustomobject]@{ id = 'rd-helpdesk'; displayName = 'Help Desk Operator'; isBuiltIn = $true }
        [pscustomobject]@{ id = 'rd-readonly'; displayName = 'Read Only Operator'; isBuiltIn = $true }
        [pscustomobject]@{ id = 'rd-mobile'; displayName = 'Mobile Platform Admin (custom)'; isBuiltIn = $false }
    )
    $m.RoleAssignments = @{
        'rd-helpdesk' = @(
            [pscustomobject]@{ id = 'ra-east'; displayName = 'Help desk East'; members = @('a1111111-0000-4000-8000-000000000001'); scopeMembers = @('a1111111-0000-4000-8000-000000000004'); resourceScopes = @(); scopeType = 'resourceScope'; roleScopeTagIds = @('4') }
            [pscustomobject]@{ id = 'ra-west'; displayName = 'Help desk West'; members = @('a1111111-0000-4000-8000-000000000002'); scopeMembers = @('a1111111-0000-4000-8000-000000000005'); resourceScopes = @(); scopeType = 'resourceScope'; roleScopeTagIds = @('5') }
        )
        'rd-readonly' = @(
            [pscustomobject]@{ id = 'ra-readers'; displayName = 'Intune readers'; members = @('a1111111-0000-4000-8000-000000000006'); scopeMembers = @(); resourceScopes = @(); scopeType = 'allDevicesAndLicensedUsers'; roleScopeTagIds = @('0', '1', '2', '3') }
        )
        'rd-mobile' = @(
            [pscustomobject]@{ id = 'ra-mobile'; displayName = 'Mobile admins'; members = @('a1111111-0000-4000-8000-000000000003'); scopeMembers = @(); resourceScopes = @(); scopeType = 'allDevices'; roleScopeTagIds = @('2', '3', '8') }
        )
    }

    $pick = { param($arr) $arr[$rnd.Next(0, $arr.Count)] }
    $tagSets = @(@('0'), @('0'), @('1'), @('2'), @('3'), @('1', '4'), @('1', '5'), @('2', '3'), @('2', '8'), @('6'), @('7'), @('1', '8'), @('0', '2'))
    $registry = Get-STMTypeRegistry
    $seedNames = @{
        DeviceConfiguration = @('WIN - Device restrictions', 'iOS - Wi-Fi Corp', 'Android Enterprise - Work profile restrictions', 'macOS - FileVault', 'WIN - Endpoint protection', 'iOS - Email profile', 'WIN - VPN Always On', 'WIN - Delivery Optimization')
        ConfigurationPolicy = @('WIN - Security baseline overrides', 'WIN - Edge settings', 'macOS - Platform SSO', 'WIN - BitLocker', 'WIN - Defender AV', 'iOS - Restrictions (settings catalog)', 'WIN - Windows Hello for Business', 'WIN - LAPS')
        GroupPolicyConfiguration = @('ADMX - Office', 'ADMX - Chrome', 'ADMX - OneDrive')
        Intent = @('Security baseline - Windows', 'Defender for Endpoint baseline')
        DeviceCompliancePolicy = @('Compliance - Windows', 'Compliance - iOS corporate', 'Compliance - Android Enterprise', 'Compliance - macOS', 'Compliance - iOS BYOD')
        CompliancePolicy = @('Compliance - Linux')
        MobileApp = @('Company Portal', 'Microsoft Outlook', 'Microsoft Teams', 'Microsoft Edge', '7-Zip', 'Adobe Acrobat Reader', 'Zoom Workplace', 'Microsoft Authenticator', 'Notepad++', 'Defender for Endpoint', 'Citrix Workspace', 'Microsoft 365 Apps')
        MobileAppConfiguration = @('Outlook iOS config', 'Edge Android config')
        TargetedManagedAppConfiguration = @('Outlook MAM config', 'Edge MAM config')
        IOSManagedAppProtection = @('APP - iOS BYOD level 2', 'APP - iOS corporate level 3')
        AndroidManagedAppProtection = @('APP - Android BYOD level 2', 'APP - Android corporate level 3')
        WindowsManagedAppProtection = @('APP - Windows Edge MAM')
        DeviceManagementScript = @('Set time zone', 'Remove bloatware', 'Collect diagnostics')
        DeviceShellScript = @('macOS - Install Rosetta', 'macOS - Dock layout')
        DeviceHealthScript = @('Remediation - Disk cleanup', 'Remediation - Restart pending')
        WindowsFeatureUpdateProfile = @('Feature update - Windows 11 24H2')
        WindowsQualityUpdateProfile = @('Expedite - November security update')
        WindowsDriverUpdateProfile = @('Drivers - Pilot ring', 'Drivers - Broad ring')
        DeviceEnrollmentConfiguration = @('All users and all devices', 'Enrollment restrictions - Personal Android', 'ESP - Corporate')
        WindowsAutopilotDeploymentProfile = @('Autopilot - User driven', 'Autopilot - Self deploying kiosk')
        AssignmentFilter = @('Filter - Corporate owned', 'Filter - Personal iOS', 'Filter - Windows 11')
        TermsAndConditions = @('Acceptable use')
        NotificationMessageTemplate = @('Noncompliance notice')
        DeviceCategory = @('Kiosk', 'Engineering', 'Clinical')
        PolicySet = @('Policy set - New hire')
        DeviceComplianceScript = @('Custom compliance - Agent health')
        MdmWindowsInformationProtectionPolicy = @()
        AndroidDeviceOwnerEnrollmentProfile = @('Dedicated devices - Kiosk', 'Fully managed - Corporate')
        DepOnboardingSetting = @('ADE token - Corporate')
        VppToken = @('Contoso Health VPP')
        IntuneBrandingProfile = @('Default branding', 'Clinical branding')
        WdacSupplementalPolicy = @('WDAC - Line of business')
        DeviceCustomAttributeShellScript = @('macOS - Battery health attribute')
        MicrosoftTunnelConfiguration = @('Tunnel - Mobile clinicians')
    }
    $odata = @{
        DeviceConfiguration = @('#microsoft.graph.windows10GeneralConfiguration', '#microsoft.graph.iosWiFiConfiguration', '#microsoft.graph.androidWorkProfileGeneralDeviceConfiguration', '#microsoft.graph.macOSEndpointProtectionConfiguration', '#microsoft.graph.windows10EndpointProtectionConfiguration', '#microsoft.graph.iosEasEmailProfileConfiguration', '#microsoft.graph.windows10VpnConfiguration', '#microsoft.graph.windowsDeliveryOptimizationConfiguration')
        DeviceCompliancePolicy = @('#microsoft.graph.windows10CompliancePolicy', '#microsoft.graph.iosCompliancePolicy', '#microsoft.graph.androidWorkProfileCompliancePolicy', '#microsoft.graph.macOSCompliancePolicy', '#microsoft.graph.iosCompliancePolicy')
        MobileApp = @('#microsoft.graph.iosStoreApp', '#microsoft.graph.iosVppApp', '#microsoft.graph.officeSuiteApp', '#microsoft.graph.windowsMicrosoftEdgeApp', '#microsoft.graph.win32LobApp', '#microsoft.graph.win32LobApp', '#microsoft.graph.winGetApp', '#microsoft.graph.androidManagedStoreApp', '#microsoft.graph.win32LobApp', '#microsoft.graph.androidManagedStoreApp', '#microsoft.graph.win32LobApp', '#microsoft.graph.officeSuiteApp')
        DeviceEnrollmentConfiguration = @('#microsoft.graph.deviceEnrollmentLimitConfiguration', '#microsoft.graph.deviceEnrollmentPlatformRestrictionConfiguration', '#microsoft.graph.windows10EnrollmentCompletionPageConfiguration')
        WindowsAutopilotDeploymentProfile = @('#microsoft.graph.azureADWindowsAutopilotDeploymentProfile', '#microsoft.graph.azureADWindowsAutopilotDeploymentProfile')
        IOSManagedAppProtection = @('#microsoft.graph.iosManagedAppProtection'); AndroidManagedAppProtection = @('#microsoft.graph.androidManagedAppProtection')
        WindowsManagedAppProtection = @('#microsoft.graph.windowsManagedAppProtection'); TargetedManagedAppConfiguration = @('#microsoft.graph.targetedManagedAppConfiguration')
        MobileAppConfiguration = @('#microsoft.graph.iosMobileAppConfiguration', '#microsoft.graph.androidManagedStoreAppConfiguration')
    }
    $m.Options.RequireODataType = @($registry | Where-Object writeStrategy -eq 'PatchWithODataType' | ForEach-Object { $_.path })
    $i = 0
    foreach ($def in $registry) {
        $coll = [System.Collections.Generic.List[object]]::new()
        $m.Collections[$def.path] = $coll
        if ($MissingTypes -contains $def.key) { $m.Options.MissingPaths += $def.path; continue }
        if ($def.key -eq 'ManagedDevice') { continue }
        $names = @($seedNames[$def.key])
        $extraCount = if ($def.key -in 'DeviceConfiguration', 'ConfigurationPolicy') { 40 } elseif ($def.key -eq 'MobileApp') { 60 } else { 0 }
        for ($k = 0; $k -lt $names.Count + $extraCount; $k++) {
            $i++
            $name = if ($k -lt $names.Count) { $names[$k] } else { '{0} - {1} {2:000}' -f (& $pick @('WIN', 'iOS', 'Android', 'macOS')), (& $pick @('Ring', 'Site', 'Team', 'Clinic', 'Lab')), $k }
            $o = [ordered]@{ id = if ($def.key -in 'DepOnboardingSetting', 'VppToken') { [guid]::NewGuid().ToString() } else { ('{0:x8}-{1:x4}-4{2:x3}-8{3:x3}-{4:x12}' -f $i, $rnd.Next(0, 65535), $rnd.Next(0, 4095), $rnd.Next(0, 4095), [long]$rnd.Next()) } }
            if ($odata.ContainsKey($def.key)) { $o['@odata.type'] = $odata[$def.key][$k % $odata[$def.key].Count] }
            $o[$def.nameProperty] = $name
            if ($def.PSObject.Properties['platformProperty'] -and $def.platformProperty) { $o[$def.platformProperty] = if ($def.key -eq 'AssignmentFilter') { (& $pick @('windows10AndLater', 'iOS', 'androidForWork')) } else { (& $pick @('windows10', 'macOS', 'iOS')) } }
            $tagProp = if ($def.PSObject.Properties['tagProperty']) { $def.tagProperty } else { 'roleScopeTagIds' }
            $o[$tagProp] = @(& $pick $tagSets)
            $o['lastModifiedDateTime'] = [DateTime]::UtcNow.AddDays(-$rnd.Next(1, 400)).ToString('o')
            if ($def.key -eq 'DeviceConfiguration') { $o['supportsScopeTags'] = ($k -ne 3) }
            if ($def.key -eq 'DeviceEnrollmentConfiguration') { $o['priority'] = $k }
            if ($def.key -eq 'MobileApp') { $o['publisher'] = 'Publisher' }
            $obj = [pscustomobject]$o
            $coll.Add($obj); $m.ById["$($def.path)/$($obj.id)"] = $obj
        }
    }
    # Devices
    $devPath = 'deviceManagement/managedDevices'
    $oses = @('Windows', 'Windows', 'Windows', 'iOS', 'iOS', 'Android', 'macOS')
    for ($d = 1; $d -le $DeviceCount; $d++) {
        $os = & $pick $oses
        $prefix = switch ($os) { 'Windows' { 'WKS' } 'iOS' { 'IPH' } 'Android' { 'AND' } default { 'MAC' } }
        $tags = switch ($os) { 'Windows' { & $pick @(@('1'), @('1', '4'), @('1', '5'), @('0'), @('7'), @('6')) } default { & $pick @(@('2'), @('3'), @('2', '4'), @('0')) } }
        $obj = [pscustomobject][ordered]@{
            id = ('d{0:x7}-0000-4000-8000-{1:x12}' -f $d, $d); deviceName = ('{0}-{1:00000}' -f $prefix, $d); operatingSystem = $os
            osVersion = switch ($os) { 'Windows' { '10.0.26100.2314' } 'iOS' { '18.6' } 'Android' { '15' } default { '15.7' } }
            serialNumber = ('SN{0:0000000}' -f ($d * 7)); userPrincipalName = ('user{0}@contoso.example' -f ($d % 900))
            managedDeviceOwnerType = if ($os -in 'iOS', 'Android' -and $d % 3 -eq 0) { 'personal' } else { 'company' }
            lastSyncDateTime = [DateTime]::UtcNow.AddHours(-$rnd.Next(1, 24 * 120)).ToString('o'); roleScopeTagIds = @($tags)
            managementAgent = if ($os -eq 'Windows' -and $d % 3 -ne 0) { 'configurationManagerClientMdm' } else { 'mdm' }
        }
        $m.Collections[$devPath].Add($obj); $m.ById["$devPath/$($obj.id)"] = $obj
    }
    $script:STMMock = $m
    return $m
}

function Get-STMMockCollectionPath {
    param([string]$Path)
    # Longest registered collection that prefixes the path.
    $best = $null
    foreach ($k in $script:STMMock.Collections.Keys) {
        if ($Path -eq $k -or $Path.StartsWith("$k/")) { if (-not $best -or $k.Length -gt $best.Length) { $best = $k } }
    }
    return $best
}

function New-STMMockResponse {
    param([int]$Status, $Body, $RetryAfter)
    $json = if ($null -eq $Body) { '' } elseif ($Body -is [string]) { $Body } else { $Body | ConvertTo-Json -Depth 20 -Compress }
    return @{ Status = $Status; Body = $json; RetryAfter = $RetryAfter }
}

function New-STMMockError {
    param([int]$Status, [string]$Code, [string]$Message)
    return New-STMMockResponse -Status $Status -Body @{ error = @{ code = $Code; message = $Message } }
}

function Select-STMMockFields {
    param($Object, [string[]]$Fields)
    if (-not $Fields) { return $Object }
    $o = [ordered]@{}
    if ($Object.PSObject.Properties['@odata.type']) { $o['@odata.type'] = $Object.'@odata.type' }
    foreach ($f in $Fields) { if ($Object.PSObject.Properties[$f]) { $o[$f] = $Object.$f } }
    return [pscustomobject]$o
}

function Invoke-STMMockRequest {
    param([string]$Method, [string]$Uri, [string]$Body)
    $m = $script:STMMock
    $m.Requests.Add([pscustomobject]@{ Method = $Method; Uri = $Uri; Body = $Body })
    if ($m.Options.ThrottleNext -gt 0 -and $Uri -notmatch '\$batch$') {
        $m.Options.ThrottleNext--
        return New-STMMockResponse -Status 429 -Body @{ error = @{ code = 'TooManyRequests'; message = 'Too many requests' } } -RetryAfter $m.Options.ThrottleRetryAfter
    }
    $u = [uri]$Uri
    $path = [uri]::UnescapeDataString($u.AbsolutePath)
    $isV1 = $path.StartsWith('/v1.0/')
    $path = $path -replace '^/(beta|v1\.0)/', ''
    $query = @{}
    if ($u.Query) { foreach ($pair in $u.Query.TrimStart('?').Split('&')) { $kv = $pair.Split('=', 2); $query[[uri]::UnescapeDataString($kv[0])] = if ($kv.Count -gt 1) { [uri]::UnescapeDataString($kv[1]) } else { '' } } }

    if ($Method -eq 'POST' -and $path -eq '$batch') { return Invoke-STMMockBatch -Body $Body }
    if ($Method -eq 'POST' -and $isV1 -and $path -eq 'directoryObjects/getByIds') {
        $req = $Body | ConvertFrom-STMJson
        $val = @(foreach ($id in @($req.ids)) { if ($m.Groups.ContainsKey($id)) { @{ '@odata.type' = '#microsoft.graph.group'; id = $id; displayName = $m.Groups[$id] } } })
        return New-STMMockResponse -Status 200 -Body @{ value = $val }
    }
    if ($path -match '^deviceManagement/roleScopeTags/([^/]+)/assignments$') {
        $tid = $Matches[1]
        $val = @(foreach ($g in @($m.TagAssignments[$tid])) { if ($g) { @{ id = "$tid-$g"; target = @{ '@odata.type' = '#microsoft.graph.groupAssignmentTarget'; groupId = $g } } } })
        return New-STMMockResponse -Status 200 -Body @{ value = $val }
    }
    if ($path -eq 'deviceManagement/roleDefinitions') { return New-STMMockResponse -Status 200 -Body @{ value = $m.RoleDefinitions } }
    if ($path -match '^deviceManagement/roleDefinitions/([^/]+)/roleAssignments$') {
        return New-STMMockResponse -Status 200 -Body @{ value = @($m.RoleAssignments[$Matches[1]] | ForEach-Object { @{ id = $_.id; displayName = $_.displayName } }) }
    }
    if ($path -match '^deviceManagement/roleAssignments/([^/]+)$') {
        $id = $Matches[1]
        $ra = $null
        foreach ($list in $m.RoleAssignments.Values) { foreach ($a in $list) { if ($a.id -eq $id) { $ra = $a } } }
        if (-not $ra) { return New-STMMockError -Status 404 -Code 'ResourceNotFound' -Message 'Role assignment not found' }
        if ($Method -eq 'PATCH') {
            if ($m.Options.MaaIds.ContainsKey($id)) { return New-STMMockError -Status 403 -Code 'Forbidden' -Message 'This action requires approval. Multi Admin Approval is enabled for this resource.' }
            if ($m.Options.FailIds.ContainsKey($id)) { return New-STMMockError -Status ([int]$m.Options.FailIds[$id]) -Code 'InternalServerError' -Message 'An internal server error occurred.' }
            $b = $Body | ConvertFrom-STMJson
            if (-not $b -or -not $b.PSObject.Properties['roleScopeTagIds']) { return New-STMMockError -Status 400 -Code 'BadRequest' -Message 'Body must contain roleScopeTagIds' }
            $new = @(@($b.roleScopeTagIds) | ForEach-Object { [string]$_ } | Where-Object { $_ -ne '' })
            $valid = @($m.Collections['deviceManagement/roleScopeTags'] | ForEach-Object { [string]$_.id })
            $bad = @($new | Where-Object { $valid -notcontains $_ })
            if ($bad.Count) { return New-STMMockError -Status 400 -Code 'BadRequest' -Message "Invalid scope tag id(s): $($bad -join ',')" }
            # NoApplyIds: the write is accepted and nothing changes, so the caller's read-back is what catches it.
            if ($m.Options.NoApplyIds.ContainsKey($id)) { return New-STMMockResponse -Status 204 -Body $null }
            if ($m.Options.LagIds.ContainsKey($id)) { $m.Options.LagIds[$id].Old = @($ra.roleScopeTagIds) }
            $ra.roleScopeTagIds = $new
            $m.Writes.Add([pscustomobject]@{ Path = "deviceManagement/roleAssignments/$id"; Tags = ($new -join ',') })
            return New-STMMockResponse -Status 200 -Body $ra
        }
        if ($Method -eq 'GET' -and $m.Options.LagIds.ContainsKey($id) -and $m.Options.LagIds[$id].Reads -gt 0) {
            $m.Options.LagIds[$id].Reads--
            $old = $ra.PSObject.Copy(); $old.roleScopeTagIds = @($m.Options.LagIds[$id].Old)
            return New-STMMockResponse -Status 200 -Body $old
        }
        return New-STMMockResponse -Status 200 -Body $ra
    }

    $coll = Get-STMMockCollectionPath -Path $path
    if (-not $coll) { return New-STMMockError -Status 404 -Code 'BadRequest' -Message "Resource not found for the segment '$path'." }
    if ($m.Options.MissingPaths -contains $coll) { return New-STMMockError -Status 400 -Code 'BadRequest' -Message "Resource not found for the segment '$($coll.Split('/')[-1])'." }
    if ($m.Options.ForbiddenPaths -contains $coll) { return New-STMMockError -Status 403 -Code 'Forbidden' -Message 'Application is not authorized to perform this operation.' }
    $rest = $path.Substring($coll.Length).TrimStart('/')
    $fields = if ($query.ContainsKey('$select') -and $query['$select']) { @($query['$select'].Split(',')) } else { $null }
    if ($fields -and $m.Options.NoSelectPaths -contains $coll) { return New-STMMockError -Status 400 -Code 'BadRequest' -Message 'Could not find a property named on type in select' }

    if ($coll -eq 'deviceManagement/roleScopeTags' -and $rest -and $rest -notmatch '/' -and $Method -in 'GET', 'PATCH', 'DELETE') {
        # Scope tags live only in the collection (seeded, created by POST, or added by a test), so one tag is found there, not in ById.
        $tag = $m.Collections[$coll] | Where-Object { [string]$_.id -eq $rest } | Select-Object -First 1
        if (-not $tag) { return New-STMMockError -Status 404 -Code 'ResourceNotFound' -Message "Resource $rest not found" }
        if ($Method -eq 'GET') { return New-STMMockResponse -Status 200 -Body (Select-STMMockFields -Object $tag -Fields $fields) }
        if ($m.Options.MaaIds.ContainsKey($rest)) { return New-STMMockError -Status 403 -Code 'Forbidden' -Message 'This action requires approval. Multi Admin Approval is enabled for this resource.' }
        if ($m.Options.FailIds.ContainsKey($rest)) { return New-STMMockError -Status ([int]$m.Options.FailIds[$rest]) -Code 'InternalServerError' -Message 'An internal server error occurred.' }
        if ($Method -eq 'DELETE') {
            if ($tag.isBuiltIn) { return New-STMMockError -Status 400 -Code 'BadRequest' -Message 'The built-in scope tag cannot be deleted.' }
            [void]$m.Collections[$coll].Remove($tag); $m.TagAssignments.Remove($rest)
            return New-STMMockResponse -Status 204 -Body $null
        }
        $b = $Body | ConvertFrom-STMJson
        if (-not $b) { return New-STMMockError -Status 400 -Code 'BadRequest' -Message 'Empty body' }
        $extraProps = @($b.PSObject.Properties.Name | Where-Object { $_ -notin @('displayName', 'description', '@odata.type') })
        if ($extraProps.Count) { return New-STMMockError -Status 400 -Code 'BadRequest' -Message "Unexpected properties: $($extraProps -join ',')" }
        if ($b.PSObject.Properties['displayName']) {
            if (-not "$($b.displayName)".Trim()) { return New-STMMockError -Status 400 -Code 'BadRequest' -Message 'displayName cannot be empty' }
            if ($tag.isBuiltIn -and [string]$b.displayName -cne [string]$tag.displayName) { return New-STMMockError -Status 400 -Code 'BadRequest' -Message 'The built-in scope tag cannot be renamed.' }
            $tag.displayName = [string]$b.displayName
        }
        if ($b.PSObject.Properties['description']) {
            if ($tag.PSObject.Properties['description']) { $tag.description = [string]$b.description } else { $tag | Add-Member -NotePropertyName description -NotePropertyValue ([string]$b.description) }
        }
        return New-STMMockResponse -Status 200 -Body $tag
    }
    if (-not $rest -and $Method -eq 'POST') {
        # Create (used by the lab test's demo mode). New objects start on the Default tag, as in Intune.
        $b = $Body | ConvertFrom-STMJson
        if (-not $b) { return New-STMMockError -Status 400 -Code 'BadRequest' -Message 'Empty body' }
        $new = [ordered]@{}
        foreach ($p in $b.PSObject.Properties) { $new[$p.Name] = $p.Value }
        if ($coll -eq 'deviceManagement/roleScopeTags') {
            $ids = @($m.Collections[$coll] | ForEach-Object { [int]$_.id })
            $new['id'] = [string](($ids | Measure-Object -Maximum).Maximum + 1); $new['isBuiltIn'] = $false
            $o = [pscustomobject]$new; $m.Collections[$coll].Add($o)
            return New-STMMockResponse -Status 201 -Body $o
        }
        $def = Get-STMTypeRegistry | Where-Object { $_.path -eq $coll } | Select-Object -First 1
        $tp = if ($def -and $def.PSObject.Properties['tagProperty']) { $def.tagProperty } else { 'roleScopeTagIds' }
        $new['id'] = [guid]::NewGuid().ToString(); $new[$tp] = @('0'); $new['lastModifiedDateTime'] = [DateTime]::UtcNow.ToString('o')
        $o = [pscustomobject]$new
        $m.Collections[$coll].Add($o); $m.ById["$coll/$($o.id)"] = $o
        return New-STMMockResponse -Status 201 -Body $o
    }
    if ($rest -and $Method -eq 'DELETE') {
        $id = $rest.Split('/')[0]
        $match = @($m.Collections[$coll] | Where-Object { [string]$_.id -eq $id })
        if (-not $match.Count) { return New-STMMockError -Status 404 -Code 'ResourceNotFound' -Message "Resource $id not found" }
        foreach ($x in $match) { [void]$m.Collections[$coll].Remove($x) }
        $m.ById.Remove("$coll/$id")
        return New-STMMockResponse -Status 204 -Body $null
    }
    if (-not $rest) {
        if ($Method -ne 'GET') { return New-STMMockError -Status 405 -Code 'MethodNotAllowed' -Message 'Not allowed' }
        $items = @($m.Collections[$coll])
        if ($query.ContainsKey('$filter')) {
            $f = $query['$filter']
            foreach ($clause in ($f -split ' and ')) {
                if ($clause -match "^(\w+) eq '(.*)'$") { $p = $Matches[1]; $v = $Matches[2].Replace("''", "'"); $items = @($items | Where-Object { "$($_.$p)" -ieq $v }) }
                elseif ($clause -match "^startswith\((\w+),'(.*)'\)$") { $p = $Matches[1]; $v = $Matches[2].Replace("''", "'"); $items = @($items | Where-Object { "$($_.$p)".StartsWith($v, [StringComparison]::OrdinalIgnoreCase) }) }
                else { return New-STMMockError -Status 400 -Code 'BadRequest' -Message "Unsupported filter $clause" }
            }
        }
        $size = $m.Options.PageSize
        if ($query.ContainsKey('$top')) { $size = [math]::Min([int]$query['$top'], 999) }
        $skip = if ($query.ContainsKey('$skiptoken')) { [int]$query['$skiptoken'] } else { 0 }
        $page = if ($skip -lt $items.Count) { @($items[$skip..([math]::Min($skip + $size, $items.Count) - 1)]) } else { @() }
        $out = @(foreach ($o in $page) {
            $x = Select-STMMockFields -Object $o -Fields $fields
            if ($coll -eq 'deviceManagement/managedDevices' -and $m.Options.DeviceListOmitsTags) { $x = $x | Select-Object * -ExcludeProperty roleScopeTagIds }
            $x
        })
        $resp = [ordered]@{ value = $out }
        if ($skip + $size -lt $items.Count) {
            $q = @()
            foreach ($k in $query.Keys) { if ($k -ne '$skiptoken') { $q += "$k=$([uri]::EscapeDataString($query[$k]))" } }
            $q += "`$skiptoken=$($skip + $size)"
            $resp['@odata.nextLink'] = "https://graph.microsoft.com/beta/$coll`?$($q -join '&')"
        }
        return New-STMMockResponse -Status 200 -Body $resp
    }

    $id = $rest.Split('/')[0]
    $key = "$coll/$id"
    if (-not $m.ById.ContainsKey($key)) { return New-STMMockError -Status 404 -Code 'ResourceNotFound' -Message "Resource $id not found" }
    $obj = $m.ById[$key]
    $def = Get-STMTypeRegistry | Where-Object { $_.path -eq $coll } | Select-Object -First 1
    $tagProp = if ($def -and $def.PSObject.Properties['tagProperty']) { $def.tagProperty } else { 'roleScopeTagIds' }

    if ($Method -eq 'GET') {
        if ($m.Options.LagIds.ContainsKey($id) -and $m.Options.LagIds[$id].Reads -gt 0) {
            $m.Options.LagIds[$id].Reads--
            $old = $obj.PSObject.Copy(); $old.$tagProp = @($m.Options.LagIds[$id].Old)
            return New-STMMockResponse -Status 200 -Body (Select-STMMockFields -Object $old -Fields $fields)
        }
        return New-STMMockResponse -Status 200 -Body (Select-STMMockFields -Object $obj -Fields $fields)
    }
    if ($Method -eq 'PATCH') {
        if ($m.Options.MaaIds.ContainsKey($id)) { return New-STMMockError -Status 403 -Code 'Forbidden' -Message 'This action requires approval. Multi Admin Approval is enabled for this resource.' }
        if ($m.Options.FailIds.ContainsKey($id)) { return New-STMMockError -Status ([int]$m.Options.FailIds[$id]) -Code 'InternalServerError' -Message 'An internal server error occurred.' }
        $b = $Body | ConvertFrom-STMJson
        if (-not $b -or -not $b.PSObject.Properties[$tagProp]) { return New-STMMockError -Status 400 -Code 'BadRequest' -Message "Body must contain $tagProp" }
        $extraProps = @($b.PSObject.Properties.Name | Where-Object { $_ -notin @($tagProp, '@odata.type') })
        if ($extraProps.Count) { return New-STMMockError -Status 400 -Code 'BadRequest' -Message "Unexpected properties: $($extraProps -join ',')" }
        if ($m.Options.RequireODataType -contains $coll) {
            if (-not $b.PSObject.Properties['@odata.type']) { return New-STMMockError -Status 400 -Code 'ModelValidationFailure' -Message 'A type named is required: @odata.type missing for derived type' }
            if ($obj.PSObject.Properties['@odata.type'] -and $b.'@odata.type' -ne $obj.'@odata.type') { return New-STMMockError -Status 400 -Code 'ModelValidationFailure' -Message '@odata.type does not match the resource' }
        }
        $new = @(@($b.$tagProp) | ForEach-Object { [string]$_ })
        $valid = @($m.Collections['deviceManagement/roleScopeTags'] | ForEach-Object { [string]$_.id })
        $bad = @($new | Where-Object { $valid -notcontains $_ })
        if ($bad.Count) { return New-STMMockError -Status 400 -Code 'BadRequest' -Message "Invalid scope tag id(s): $($bad -join ',')" }
        if ($new.Count -gt 100) { return New-STMMockError -Status 400 -Code 'BadRequest' -Message 'Too many scope tags' }
        if ($m.Options.LagIds.ContainsKey($id)) { $m.Options.LagIds[$id].Old = @($obj.$tagProp) }
        $obj.$tagProp = $new
        $m.Writes.Add([pscustomobject]@{ Path = $key; Tags = ($new -join ',') })
        return New-STMMockResponse -Status 204 -Body $null
    }
    return New-STMMockError -Status 405 -Code 'MethodNotAllowed' -Message 'Not allowed'
}

function Invoke-STMMockBatch {
    param([string]$Body)
    $req = $Body | ConvertFrom-STMJson
    $reqs = @($req.requests)
    if ($reqs.Count -gt 20) { return New-STMMockError -Status 400 -Code 'BadRequest' -Message 'A batch can hold at most 20 requests' }
    $responses = foreach ($r in $reqs) {
        $sb = if ($r.PSObject.Properties['body'] -and $null -ne $r.body) { $r.body | ConvertTo-Json -Depth 20 -Compress } else { $null }
        $res = Invoke-STMMockRequest -Method $r.method -Uri ("https://graph.microsoft.com/beta/" + "$($r.url)".TrimStart('/')) -Body $sb
        $out = [ordered]@{ id = [string]$r.id; status = $res.Status }
        if ($res.RetryAfter) { $out.headers = @{ 'Retry-After' = [string]$res.RetryAfter } }
        if ($res.Body) { $out.body = $res.Body | ConvertFrom-STMJson }
        $out
    }
    return New-STMMockResponse -Status 200 -Body @{ responses = @($responses) }
}