Modules/Utility/Utility.psm1

Import-Module (Join-Path -Path $PSScriptRoot -ChildPath '../Connection/ConnectHelpers.psm1') -Function Invoke-ScubaGraphRequest

function Set-Utf8NoBom {
    <#
    .Description
    Using the .NET framework, save the provided input as a UTF-8 file without the byte-order marking (BOM).
    .Functionality
    Internal
    .Parameter Content
    The content to save to the file.
    .Parameter Location
    The location to save the file to. Note that it MUST already exist and that the name of the file you want to save
    should not be included in this string.
    .Parameter FileName
    The name of the file you want to save. Note this should not include the full path, i.e., use "Example.json" instead
    of "./examplefolder/Example.json"
    #>

    [CmdletBinding()]
    param(
        [Parameter(Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [string]
        $Content,

        [Parameter(Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [string]
        $Location,

        [Parameter(Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [string]
        $FileName
    )
    process {
        # Need to insure the location is an absolute path, otherwise you can get some inconsistent behavior.
        # LiteralPath so output folders containing wildcard characters (e.g. []) are treated literally.
        $ResolvedPath = $(Resolve-Path -LiteralPath $Location).ProviderPath
        $FinalPath = Join-Path -Path $ResolvedPath -ChildPath $FileName -ErrorAction 'Stop'
        # The $false in the next line indicates that the BOM should not be used.
        $Utf8NoBomEncoding = New-Object System.Text.UTF8Encoding $False
        Invoke-WriteAllText -Content $Content -Path $FinalPath -Encoding $Utf8NoBomEncoding
        $FinalPath  # Used to test path construction more easily
    }
}

function Get-Utf8NoBom {
    <#
    .Description
    Using the .NET framework, read the provided path as a UTF-8 file without the byte-order marking (BOM).
    .Functionality
    Internal
    .Parameter FilePath
    The full path of the file you want to read. The file must exist.
    #>

    [CmdletBinding()]
    param(
        [Parameter(Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [string]
        $FilePath
    )
    process {
        # The $false in the next line indicates that the BOM should not be used.
        $Utf8NoBomEncoding = New-Object System.Text.UTF8Encoding $False

        $ResolvedPath = $(Resolve-Path -LiteralPath $FilePath).ProviderPath
        $Content = Invoke-ReadAllText -Path $ResolvedPath -Encoding $Utf8NoBomEncoding
        $Content
    }
}

function Invoke-WriteAllText {
    <#
    .Description
    Using the .NET framework, save the provided content to the file
    path provided using the given encoding.
    .Functionality
    Internal
    .Parameter Content
    The content to save to the file.
    .Parameter Path
    The full file path to the file being written.
    .Parameter Encoding
    An object of type System.Text.Encoding that determines how the
    content is encoded for output to file.
    Default: UTF-8 without BOM encoding used
    #>

    [CmdletBinding()]
    param(
        [Parameter(Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [string]
        $Content,

        [Parameter(Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [string]
        $Path,

        [Parameter(Mandatory = $false)]
        [ValidateNotNullOrEmpty()]
        [System.Text.Encoding]
        $Encoding = (New-Object System.Text.UTF8Encoding $False)
    )
    process {
        [System.IO.File]::WriteAllText($Path, $Content, $Encoding)
    }
}

function Invoke-ReadAllText {
    <#
    .Description
    Using the .NET framework, read content from the file
    path provided using the given encoding.
    .Functionality
    Internal
    .Parameter Path
    The full file path to the file being read.
    .Parameter Encoding
    An object of type System.Text.Encoding that determines how the
    content is encoded for output to file.
    Default: UTF-8 without BOM encoding used
    #>

    [CmdletBinding()]
    param(
        [Parameter(Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [string]
        $Path,

        [Parameter(Mandatory = $false)]
        [ValidateNotNullOrEmpty()]
        [System.Text.Encoding]
        $Encoding = (New-Object System.Text.UTF8Encoding $False)
    )
    process {
        $Content = [System.IO.File]::ReadAllText($Path, $Encoding)
        $Content
    }
}

function Invoke-GraphDirectly {
    <#
    .SYNOPSIS
    Invoke Microsoft Graph API requests directly, replacing specific cmdlets.
 
    .Description
    This function is used to invoke Microsoft Graph API requests directly, replacing the need for specific cmdlets.
 
    .Parameter commandlet
    The name of the commandlet to replace, e.g., "Get-MgBetaServicePrincipal".
 
    .Parameter M365Environment
    The Microsoft 365 environment to target, e.g., "Commercial", "Government", etc.
 
    .Parameter queryParams
    A hashtable of query parameters to append to the request URI.
 
    .Parameter apiHeader
    A switch to indicate whether to include API headers in the request.
 
    .Parameter ID
    The ID of the resource to target, if applicable.
 
    .Parameter Body
    The body of the request, typically used for POST or PATCH requests.
 
    .Example
    Invoke-GraphDirectly -commandlet "Get-MgBetaServicePrincipal" -M365Environment "Commercial" -queryParams @{ filter = "displayName eq 'Test'" } -ID "12345"
 
    This example invokes the Microsoft Graph API to get a service principal with the specified filter, using the commercial environment and including API headers.
 
    .Example
    Invoke-GraphDirectly -commandlet "New-MgBetaServicePrincipal" -M365Environment "Commercial" -Body @{ displayName = "New SP"; appId = "12345678-1234-1234-1234-123456789012" }
 
    This example invokes the Microsoft Graph API to create a new service principal with the specified body, using the commercial environment.
 
    .Parameter Uri
    An explicit Graph API URI (relative, e.g. "/v1.0/me/licenseDetails") to call when the target has
    no registered cmdlet mapping. When supplied, the request is sent as-is without endpoint resolution
    or response key normalization, so callers receive the raw Graph response (GET requests are still
    paginated automatically, since Invoke-ScubaGraphRequest handles pagination internally).
 
    .Parameter Method
    The HTTP method to use with -Uri (default: GET). Ignored in cmdlet mode, where the method is
    derived from the cmdlet verb.
 
    .Parameter Headers
    Additional request headers to send with -Uri (e.g. @{ ConsistencyLevel = 'eventual' }).
 
    .Parameter OutputType
    The Invoke-ScubaGraphRequest -OutputType to use with -Uri (e.g. "PSObject").
 
    .Example
    Invoke-GraphDirectly -Uri "/v1.0/me/licenseDetails" -Method GET
 
    This example calls an arbitrary Graph endpoint that has no registered cmdlet mapping.
 
    #>

    [CmdletBinding(DefaultParameterSetName = 'Commandlet')]
    param (
        [Parameter(ParameterSetName = 'Commandlet')]
        [ValidateNotNullOrEmpty()]
        [string]
        $commandlet,

        [Parameter(ParameterSetName = 'Commandlet')]
        [ValidateNotNullOrEmpty()]
        [string]
        $M365Environment,

        [Parameter(ParameterSetName = 'Commandlet')]
        [System.Collections.Hashtable]
        $queryParams,

        [Parameter(ParameterSetName = 'Commandlet')]
        [string]$ID,

        [object]$Body,

        [Parameter(ParameterSetName = 'Uri', Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [string]$Uri,

        [Parameter(ParameterSetName = 'Uri')]
        [string]$Method = 'GET',

        [Parameter(ParameterSetName = 'Uri')]
        [System.Collections.Hashtable]$Headers,

        [Parameter(ParameterSetName = 'Uri')]
        [string]$OutputType
    )

    # Uri mode: call an arbitrary Graph endpoint directly for targets with no registered cmdlet
    # mapping. The raw response is returned without key normalization so the caller gets what the
    # Graph API sent, matching a direct Invoke-ScubaGraphRequest call.
    if ($PSCmdlet.ParameterSetName -eq 'Uri') {
        Write-Debug "Graph Api direct (explicit Uri): $Uri"
        $graphParams = @{
            Uri    = $Uri
            Method = $Method
        }
        if ($Headers) { $graphParams['Headers'] = $Headers }
        if ($OutputType) { $graphParams['OutputType'] = $OutputType }
        if ($null -ne $Body) {
            # Accept either a pre-serialized JSON string or an object to serialize.
            $graphParams['Body'] = if ($Body -is [string]) { $Body } else { $Body | ConvertTo-Json -Depth 10 }
            $graphParams['ContentType'] = 'application/json'
        }
        return Invoke-ScubaGraphRequest @graphParams
    }

    Write-Debug "Using Graph REST API instead of cmdlet: $commandlet"

    # Determine HTTP method based on commandlet name
    if ($commandlet) {
    $verb = $commandlet.Split('-')[0]
    $Method = switch ($verb) {
        "Get"    { "GET" }
        "New"    { "POST" }
        "Update" { "PATCH" }
        "Remove" { "DELETE" }
        default  { "GET" }
        }
    }

    # Determine endpoint
    if ($ID) {
        $endpoint = Get-ScubaGearGraphEndpoint -CmdletName $commandlet -Environment $M365Environment -Id $ID
    } else {
        $endpoint = Get-ScubaGearGraphEndpoint -CmdletName $commandlet -Environment $M365Environment
    }

    if ($queryParams) {
        # If query params are passed in, we augment the endpoint URI to include the params.
        $q = [System.Web.HttpUtility]::ParseQueryString([string]::Empty)
        foreach ($item in $queryParams.GetEnumerator()) {
            $q.Add($item.Key, $item.Value)
        }
        # Named $uriBuilder (not $uri) to avoid colliding with the [string]$Uri parameter (variables are case-insensitive).
        $uriBuilder = [System.UriBuilder]::new("", "", 443, $endpoint)
        $uriBuilder.Query = $q.ToString()
        $APIFilter = $uriBuilder.Query
        $endpoint = $endpoint + $APIFilter
    }
    Write-Debug "Graph Api direct: $endpoint"

    If ($null -eq $endpoint) {
        throw "The commandlet $commandlet can't be used with the Invoke-GraphDirectly function yet."
    }

    $apiHeader = Get-ScubaGearApiHeader -CmdletName $commandlet -Environment $M365Environment

    $graphParams = @{
        Uri         = $endpoint
        Method      = $Method
    }

    # If the API header is stored in the PermissionsHelper module for the commandlet, we add it to the request
    if ($null -ne $apiHeader.PSObject.Properties.Name) {
        # Named $apiHeaders (not $headers) to avoid colliding with the [hashtable]$Headers parameter (variables are case-insensitive).
        $apiHeaders = @{}
        foreach ($property in $apiHeader.PSObject.Properties) {
            $apiHeaders[$property.Name] = $property.Value
        }
        $graphParams['Headers'] = $apiHeaders
    }

    # Add body if provided
    if ($Body) {
        $graphParams['Body']        = $Body | ConvertTo-Json -Depth 10
        $graphParams['ContentType'] = 'application/json'
    }

    # Execute the initial request (Invoke-ScubaGraphRequest handles pagination internally)
    $resp = Invoke-ScubaGraphRequest @graphParams

    if ($Method -notmatch "DELETE|PATCH") {
        return $resp | ConvertFrom-GraphHashtable
    }
}

function Resolve-ScubaOrganization {
    <#
    .SYNOPSIS
    Returns the tenant's organization record (GET /beta/organization), calling Microsoft Graph at most once per Graph session.
 
    .Description
    Connection, the AAD and Power Platform providers, and the risky permissions helpers all need the
    organization record. The first call reads it through Invoke-GraphDirectly and caches it on the shared
    Graph session ($Global:ScubaGearState.Session.Organization); later calls return the cached record.
    Connect-GraphHelper replaces the session on every sign-in and Disconnect-ScubaGraph clears it, so a
    cached record never outlives the tenant connection it was read from.
 
    The record is returned in the same shape as (Invoke-GraphDirectly -Commandlet Get-MgBetaOrganization).Value.
 
    .Parameter M365Environment
    The M365 environment used to resolve the Graph endpoint for the first, uncached call.
 
    .Functionality
    Internal
    #>

    [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidGlobalVars', '', Justification = 'Organization is cached on the cross-module MSAL session singleton')]
    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [string]
        $M365Environment
    )

    $Session = $Global:ScubaGearState.Session
    if (-not $Session) {
        throw 'Microsoft Graph is not connected. Call Connect-GraphHelper first.'
    }
    if ($null -ne $Session.Organization) {
        Write-Debug "Using cached organization record from the Graph session"
        return ,$Session.Organization
    }

    $Organization = (Invoke-GraphDirectly -Commandlet "Get-MgBetaOrganization" -M365Environment $M365Environment).Value
    if ($null -eq $Organization -or @($Organization).Count -eq 0) {
        throw 'Microsoft Graph returned no organization record for the connected tenant.'
    }
    $Session.Organization = $Organization
    return ,$Organization
}

Function ConvertFrom-GraphHashtable {
    <#
    .SYNOPSIS
    Converts a collection of hashtables from Microsoft Graph API responses into PowerShell objects.
 
    .DESCRIPTION
    This function processes a collection of hashtables, typically returned from Microsoft Graph API responses,
    and converts them into PowerShell objects. It handles nested hashtables and arrays, converting them into
    appropriate PowerShell object properties. The function is designed to work with the output of the
    Invoke-GraphDirectly function, allowing for easy manipulation and access to the data.
 
    .PARAMETER GraphData
    The input data, which is expected to be a collection of hashtables or objects returned from Microsoft Graph API requests.
 
    .EXAMPLE
    $graphData = @(
        @{ id = "1"; displayName = "Example 1"; properties = @{ nestedProp = "value1" } },
        @{ id = "2"; displayName = "Example 2"; properties = @{ nestedProp = "value2" } }
    )
    $convertedData = ConvertFrom-GraphHashtable -GraphData $graphData
 
    This example takes a collection of hashtables representing Microsoft Graph API data and converts them into PowerShell objects,
    allowing for easier access to properties and nested data.
 
    .NOTES
    This function is part of the ScubaGear PowerShell module and is intended for internal use to facilitate
    the conversion of Microsoft Graph API responses into a more manageable format in order to limit REGO changes.
 
    #>

    [CmdletBinding()]
    param(
        [Parameter(Mandatory=$true, ValueFromPipeline=$true)]
        $GraphData
    )

    Begin {
        $GraphObject = [System.Collections.ArrayList]::new()
    }

    Process {
        foreach ($Item in $GraphData) {
            if ($Item -is [System.Collections.IDictionary] -or $Item.PSTypeNames[0] -eq 'System.Management.Automation.PSCustomObject') {
                # Create a new object
                $Object = New-Object -TypeName PSObject

                $Properties = if ($Item -is [System.Collections.IDictionary]) {
                    $Item.GetEnumerator() | ForEach-Object {
                        [pscustomobject]@{ Name = $_.Key; Value = $_.Value }
                    }
                }
                else {
                    $Item.PSObject.Properties
                }

                # Process each property in the Graph response
                foreach ($property in $Properties) {
                    $UpperCamelCase = ($property.Name).Substring(0,1).ToUpper() + ($property.Name).Substring(1)
                    if ($null -ne $property.Value -and ($property.Value -is [System.Collections.IDictionary] -or $property.Value.PSTypeNames[0] -eq 'System.Management.Automation.PSCustomObject')) {
                        # Recursive call to process nested Graph objects
                        $NestedObject = ConvertFrom-GraphHashtable -GraphData @($property.Value)

                        $Object | Add-Member -MemberType NoteProperty -Name $UpperCamelCase -Value $NestedObject
                    }
                    elseif ($property.Value -is [array]) {
                        # Handle arrays (check if elements are Graph objects)
                        $ProcessedArray = @()
                        foreach ($element in $property.Value) {
                            if ($null -ne $element -and ($element -is [System.Collections.IDictionary] -or $element.PSTypeNames[0] -eq 'System.Management.Automation.PSCustomObject')) {
                                $ProcessedArray += ConvertFrom-GraphHashtable -GraphData @($element)
                            } else {
                                $ProcessedArray += $element
                            }
                        }
                        $Object | Add-Member -MemberType NoteProperty -Name $UpperCamelCase -Value $ProcessedArray
                    }
                    else {
                        $Value = $property.Value
                        $Object | Add-Member -MemberType NoteProperty -Name $UpperCamelCase -Value $Value
                    }
                }

                [void]$GraphObject.Add($Object)
            }
            else {
                # Handle normal objects
                [void]$GraphObject.Add($Item)
            }
        }
    }

    End {
        return $GraphObject
    }
}

function Invoke-GraphBatchRequest {
    <#
    .SYNOPSIS
        Executes multiple Graph API requests in a single batch call.
 
    .DESCRIPTION
        Uses Microsoft Graph $batch endpoint to execute up to 20 requests in a single HTTP call.
        Automatically handles batching if more than 20 requests are provided.
 
    .PARAMETER Requests
        Array of request objects. Each object should have: id, method, url. Use this parameter set
        when you have already built the request objects externally.
 
    .PARAMETER InputObject
        Collection of objects to transform into batch requests. Use with -UrlScript (and optionally
        -IdScript) instead of building request objects manually.
 
    .PARAMETER IdScript
        Scriptblock that produces the request id from each InputObject element (default: { $_.Id }).
        The current element is available as $_ inside the scriptblock.
 
    .PARAMETER UrlScript
        Scriptblock that produces the request URL from each InputObject element.
        The current element is available as $_ inside the scriptblock.
 
    .PARAMETER M365Environment
        The M365 environment to use for the batch request.
 
    .PARAMETER ApiVersion
        The Microsoft Graph API version to use (default: v1.0).
        Valid values are "v1.0" and "beta".
 
    .PARAMETER MaxRetries
        Maximum number of times to retry sub-requests that return HTTP 429 (throttled).
        Default is 5. Safeguard against runaway retries.
 
        Added per recommendation in Microsoft Graph throttling documentation to implement retry logic when receiving 429s:
        If the request fails again with a 429 error code, you're still being throttled. Continue to use the recommended Retry-After delay and retry the request until it succeeds.
 
    .PARAMETER BatchSize
        Number of requests packed into each Graph $batch envelope (1-20). Default is 20 as that the maximum allowed by the Graph API.
        Lower values reduce burst pressure on rate-limited endpoints (e.g. the PIM policy store
        when using $filter) at the cost of more HTTP round-trips.
 
    .PARAMETER RetriableStatusCodes
        Sub-response (and batch-envelope) HTTP status codes eligible for retry. Default is @(429),
        which preserves the throttle-only behavior. Pass e.g. @(429, 500, 502, 503, 504) to also
        retry transient server errors.
 
    .PARAMETER UseExponentialBackoffFallback
        When set, retriable responses that lack a parseable Retry-After header (common for 5xx) are
        retried using exponential backoff (FallbackBaseDelaySeconds * 2^attempt, capped at 300s)
        instead of being surfaced to the caller. Default is off, preserving the "honor Retry-After
        or surface" behavior described in .NOTES.
 
    .PARAMETER FallbackBaseDelaySeconds
        Base delay in seconds for the exponential backoff fallback (default: 1). Only used when
        -UseExponentialBackoffFallback is set and no Retry-After header is present.
 
    .EXAMPLE
        $requests = @(
            @{ id = "1"; method = "GET"; url = "/servicePrincipals/12345" }
            @{ id = "2"; method = "GET"; url = "/servicePrincipals/67890" }
        )
        $results = Invoke-GraphBatchRequest -Requests $requests -M365Environment "commercial"
 
        This example executes two GET requests in a single batch call to retrieve service principals.
 
    .EXAMPLE
        $requests = @(
            @{ id = "1"; method = "GET"; url = "/users" }
            @{ id = "2"; method = "GET"; url = "/groups" }
        )
        $results = Invoke-GraphBatchRequest -Requests $requests -M365Environment "commercial" -ApiVersion "beta"
 
        This example executes two GET requests in a single batch call to retrieve users and groups using the beta API version.
 
    .EXAMPLE
        $groups = @(
            [PSCustomObject]@{ Id = "aaaa-1111" }
            [PSCustomObject]@{ Id = "bbbb-2222" }
        )
        $results = Invoke-GraphBatchRequest -InputObject $groups `
            -UrlScript { "/groups/$($_.Id)?`$select=displayName" } `
            -M365Environment "commercial" -ApiVersion "beta"
 
        This example uses -InputObject and -UrlScript to batch fetch display names without manually
        building request objects. The default -IdScript ({ $_.Id }) is used as the request id.
 
    .EXAMPLE
        $policyInputs = $groups | Select-Object @{n='PolicyId'; e={ $policyResults[$_.Id].body.value[0].policyId }}
        $results = Invoke-GraphBatchRequest -InputObject $policyInputs `
            -IdScript { $_.PolicyId } `
            -UrlScript { "/policies/roleManagementPolicies/$($_.PolicyId)/rules" } `
            -M365Environment "commercial" -ApiVersion "beta"
 
        This example uses a custom -IdScript when the batch request id should come from a derived
        property (PolicyId) rather than the default Id property.
 
    .NOTES
        This function is part of the ScubaGear PowerShell module and is intended for internal use to facilitate
        efficient Graph API interactions by minimizing the number of HTTP requests.
 
        Individual sub-requests in a Graph $batch can return HTTP 429 even when the batch envelope
        returns 200, and Graph doesn't automatically retry throttled batched requests.
        This function retries only the throttled sub-requests, using each response's Retry-After
        header value as the base wait time.
 
        Retry backoff: the first retry honors the server's Retry-After value verbatim. Each
        subsequent retry doubles the wait (Retry-After * 2^attempt), capped at 300 seconds per
        sleep. This deviates from "honor Retry-After exactly" as there are times when it will
        still fail and adding an additional offset can help mitigate repeated failures.
 
        References:
          https://learn.microsoft.com/en-us/graph/throttling
          https://learn.microsoft.com/en-us/graph/throttling#throttling-and-batching
          https://learn.microsoft.com/en-us/graph/json-batching
          https://learn.microsoft.com/en-us/graph/throttling-limits
 
        Microsoft documentation also recommends an exponential backoff fallback when Retry-After is
        absent. ScubaGear does not implement that fallback because all batched URLs target the
        identity-and-access service currently, which always returns Retry-After per the throttling-limits
        reference above. If a throttled sub-response lacks Retry-After, this function returns the
        429 to the caller rather than guess a wait time.
    #>

    [CmdletBinding(DefaultParameterSetName = 'Requests')]
    param(
        [Parameter(ParameterSetName = 'Requests', Mandatory = $true)]
        [array]$Requests,

        [Parameter(ParameterSetName = 'InputObject', Mandatory = $true)]
        [array]$InputObject,

        [Parameter(ParameterSetName = 'InputObject', Mandatory = $false)]
        [scriptblock]$IdScript = { $_.Id },

        [Parameter(ParameterSetName = 'InputObject', Mandatory = $true)]
        [scriptblock]$UrlScript,

        [Parameter(Mandatory = $true)]
        [ValidateSet("commercial", "gcc", "gcchigh", "dod", IgnoreCase = $True)]
        [string]$M365Environment,

        [Parameter(Mandatory = $false)]
        [ValidateSet("v1.0", "beta", IgnoreCase = $True)]
        [string]$ApiVersion = "v1.0",

        [Parameter(Mandatory = $false)]
        [int]$MaxRetries = 5,

        [Parameter(Mandatory = $false)]
        [ValidateRange(1, 20)]
        [int]$BatchSize = 20,

        [Parameter(Mandatory = $false)]
        [int[]]$RetriableStatusCodes = @(429),

        [Parameter(Mandatory = $false)]
        [switch]$UseExponentialBackoffFallback,

        [Parameter(Mandatory = $false)]
        [ValidateRange(1, 60)]
        [int]$FallbackBaseDelaySeconds = 1
    )

    # If InputObject parameter set is used, build $Requests from the collection + scriptblocks
    if ($PSCmdlet.ParameterSetName -eq 'InputObject') {
        $Requests = @()
        foreach ($item in $InputObject) {
            $Requests += @{
                id     = $item | ForEach-Object $IdScript
                method = "GET"
                url    = $item | ForEach-Object $UrlScript
            }
        }
    }

    $allResults = @{}
    # $currentBatchSize controls how many requests we put in each batch we send.
    # It starts at the caller's $BatchSize (up to 20, which is the Graph limit).
    # When we get a 429 statusCode (too many requests), we cut it in half (down to 1 minimum)
    # so the next batch we send is smaller. Microsoft's throttling guidance says to
    # "reduce the number of operations per request" when you get throttled, see:
    # https://learn.microsoft.com/en-us/graph/throttling#best-practices-to-handle-throttling
    # Once we shrink the batch call, we stay shrunk for the rest of this call.
    $currentBatchSize = $BatchSize

    # Split requests into batches
    for ($i = 0; $i -lt $Requests.Count;) {
        # Select the next batch of requests, capped at the end of the array.
        $batchRequests = $Requests[$i..[Math]::Min($i + $currentBatchSize - 1, $Requests.Count - 1)]
        $requestCountForThisBatch = $batchRequests.Count
        $pendingRequests = @($batchRequests)
        $attempt = 0

        while ($pendingRequests.Count -gt 0) {
            # Build batch request body
            $batchBody = @{
                requests = @($pendingRequests)
            }

            try {
                # Execute batch request using the internal Graph transport
                Write-Verbose "Executing batch request with $($pendingRequests.Count) requests (attempt $($attempt + 1))"
                $endpoint = Get-ScubaGearServiceEndpoint -Product aad -Environment $M365Environment
                $batchResponse = Invoke-ScubaGraphRequest -Method POST -Uri "$endpoint/$ApiVersion/`$batch" -Body ($batchBody | ConvertTo-Json -Depth 10)
            }
            catch {
                # Entire batch request failed (e.g., network error, auth error, or even a 429 if the batch envelope itself is too large).
                # Retry only when a parseable Retry-After
                # header is present (https://learn.microsoft.com/en-us/graph/throttling#sample-response).
                $statusCode = $null
                $retryAfter = 0
                $response   = $_.Exception.Response
                if ($response) {
                    $statusCode = [int]$response.StatusCode
                    # Retry retriable responses when Graph provides a parseable Retry-After delay.
                    if (($RetriableStatusCodes -contains $statusCode) -and $attempt -lt $MaxRetries -and $response.Headers) {
                        $headerValue = $response.Headers['Retry-After']
                        if ($headerValue) {
                            [void][int]::TryParse([string]$headerValue, [ref]$retryAfter)
                        }
                    }
                }
                $canRetryEnvelope = ($null -ne $statusCode) -and ($RetriableStatusCodes -contains $statusCode) -and ($attempt -lt $MaxRetries)
                if ($canRetryEnvelope -and ($retryAfter -gt 0 -or $UseExponentialBackoffFallback)) {
                    if ($retryAfter -gt 0) {
                        # First retry waits exactly the Retry-After value the server told us to wait.
                        # Later retries double that wait time, but never sleep more than 300 seconds.
                        # See .NOTES for why we double instead of using Retry-After every time.
                        $waitSeconds = [int]([Math]::Min([double]$retryAfter * [Math]::Pow(2, $attempt), 300))
                    }
                    else {
                        # No Retry-After (common for 5xx). Fall back to exponential backoff when the
                        # caller opted in via -UseExponentialBackoffFallback.
                        $waitSeconds = [int]([Math]::Min([double]$FallbackBaseDelaySeconds * [Math]::Pow(2, $attempt), 300))
                    }
                    # We got throttled, so cut the batch size in half and trim the request list
                    # down to the new size before we retry. The requests we trimmed off don't get
                    # lost: this batch only advances by the number of requests we keep, so the next
                    # pass will pick up the trimmed requests in a new (smaller) batch.
                    if ($currentBatchSize -gt 1) {
                        $currentBatchSize = [Math]::Max(1, [int][Math]::Floor($currentBatchSize / 2))
                        Write-ScubaLog -Message "Reducing batch size to $currentBatchSize after HTTP $statusCode." -Level Info -Source "Invoke-GraphBatchRequest"
                        $pendingRequests = @($pendingRequests | Select-Object -First $currentBatchSize)
                        $requestCountForThisBatch = $pendingRequests.Count
                    }
                    if ($attempt -eq 0) {
                        Write-ScubaLog -Message "Batch size: $($pendingRequests.Count) Request: $UrlScript - Batch request failed (HTTP $statusCode). Retrying in $waitSeconds second(s)." -Level Info -Source "Invoke-GraphBatchRequest"
                    } else {
                        Write-ScubaLog -Message "Batch size: $($pendingRequests.Count) Request: $UrlScript - Batch request failed (HTTP $statusCode). Retrying in $waitSeconds second(s) (attempt $($attempt + 1), Retry-After=$retryAfter)." -Level Info -Source "Invoke-GraphBatchRequest"
                    }
                    Start-Sleep -Seconds $waitSeconds
                    $attempt++
                    continue
                }
                Write-ScubaLog -Message "Batch request failed" -Level Error -Source "Invoke-GraphBatchRequest" -Data @{
                    Error = $_.Exception.Message
                    StackTrace = $_.ScriptStackTrace
                }
                throw
            }

            # Per https://learn.microsoft.com/en-us/graph/throttling#throttling-and-batching,
            # retry only failed sub-requests in a new batch using the longest Retry-After value
            # across them. Each sub-response carries its own headers object
            # (https://learn.microsoft.com/en-us/graph/json-batching).
            $throttled = @()
            foreach ($response in $batchResponse.responses) {
                if (($RetriableStatusCodes -contains [int]$response.status) -and $attempt -lt $MaxRetries) {
                    $throttled += $response
                }
                else {
                    $allResults[$response.id] = $response
                }
            }

            if ($throttled.Count -eq 0) { break }

            # Find the longest Retry-After value returned by any throttled sub-request.
            $longestRetryAfterSeconds = 0
            $hasRetryAfter = $false
            foreach ($r in $throttled) {
                if ($r.headers -and $r.headers.'Retry-After') {
                    $value = 0
                    if ([int]::TryParse([string]$r.headers.'Retry-After', [ref]$value)) {
                        $hasRetryAfter = $true
                        if ($value -gt $longestRetryAfterSeconds) { $longestRetryAfterSeconds = $value }
                    }
                }
            }

            if (-not $hasRetryAfter -and -not $UseExponentialBackoffFallback) {
                # No parseable Retry-After on any throttled sub-response. Identity-and-access
                # endpoints always return Retry-After per
                # https://learn.microsoft.com/en-us/graph/throttling-limits, so if it is missing
                # the wait time is unknown. Surface the responses to the caller instead of guessing,
                # unless the caller opted in to exponential backoff via -UseExponentialBackoffFallback.
                foreach ($r in $throttled) { $allResults[$r.id] = $r }
                break
            }

            # First retry honors Retry-After verbatim; subsequent retries double the wait,
            # capped at 300 seconds per sleep. See .NOTES for rationale. When no Retry-After was
            # provided (e.g. transient 5xx) and the caller opted in, fall back to exponential backoff.
            if ($hasRetryAfter) {
                $waitSeconds = [int][Math]::Min($longestRetryAfterSeconds * [Math]::Pow(2, $attempt), 300)
            }
            else {
                $waitSeconds = [int][Math]::Min([double]$FallbackBaseDelaySeconds * [Math]::Pow(2, $attempt), 300)
            }

            if ($attempt -eq 0) {
                Write-ScubaLog -Message "Batch size: $($pendingRequests.Count) Request: $UrlScript - $($throttled.Count) sub-request(s) failed with a retriable status. Retrying in $waitSeconds second(s)." -Level Info -Source "Invoke-GraphBatchRequest"
            } else {
                Write-ScubaLog -Message "Batch size: $($pendingRequests.Count) Request: $UrlScript - $($throttled.Count) sub-request(s) failed with a retriable status. Retrying in $waitSeconds second(s) (attempt $($attempt + 1), Retry-After=$longestRetryAfterSeconds)." -Level Info -Source "Invoke-GraphBatchRequest"
            }
            # Cut the batch size in half so later batches in this call are smaller.
            # We don't trim $pendingRequests here because it already only holds the throttled
            # requests, which is no more than the original batch size, so it still fits in one send.
            if ($currentBatchSize -gt 1) {
                $currentBatchSize = [Math]::Max(1, [int][Math]::Floor($currentBatchSize / 2))
                Write-ScubaLog -Message "Reducing batch size to $currentBatchSize after a retriable failure." -Level Info -Source "Invoke-GraphBatchRequest"
            }
            Start-Sleep -Seconds $waitSeconds

            # Rebuild pending requests by matching ids of throttled responses to their originals.
            $throttledIds = @($throttled | ForEach-Object { [string]$_.id })
            $pendingRequests = @($pendingRequests | Where-Object { $throttledIds -contains [string]$_.id })
            $attempt++
        }

        $i += $requestCountForThisBatch
    }

    return $allResults
}

function Get-RetryAfterSeconds {
    <#
    .SYNOPSIS
        Extracts the Retry-After delay (in seconds) from an HTTP response object, if present.
    .DESCRIPTION
        Handles both the PS 5.1 HttpWebResponse header shape (string-indexable WebHeaderCollection)
        and the PS 7+ HttpResponseMessage shape (strongly-typed RetryConditionHeaderValue).
    .PARAMETER HttpResponseObject
        The response object to inspect (an exception's .Response property).
    .PARAMETER DefaultSeconds
        The value to return if no Retry-After header is present or it cannot be parsed.
    .FUNCTIONALITY
        Internal
    #>

    [CmdletBinding()]
    param(
        [Parameter(Mandatory = $false)]
        $HttpResponseObject,

        [Parameter(Mandatory = $true)]
        [int]$DefaultSeconds
    )

    if ($null -eq $HttpResponseObject) {
        return $DefaultSeconds
    }

    try {
        if ($HttpResponseObject.GetType().FullName -eq 'System.Net.Http.HttpResponseMessage') {
            $RetryAfterHeader = $HttpResponseObject.Headers.RetryAfter
            # PowerShell auto-unwraps Nullable<TimeSpan>, so .Delta is already a [TimeSpan] (not Nullable<TimeSpan>).
            if ($RetryAfterHeader -and $RetryAfterHeader.Delta) {
                return [Math]::Max(0, [int][Math]::Ceiling($RetryAfterHeader.Delta.TotalSeconds))
            }
            if ($RetryAfterHeader -and $RetryAfterHeader.Date) {
                $DelaySeconds = ($RetryAfterHeader.Date.ToUniversalTime() - [DateTimeOffset]::UtcNow).TotalSeconds
                return [Math]::Max(0, [int][Math]::Ceiling($DelaySeconds))
            }
        }
        else {
            $RetryAfterValue = $HttpResponseObject.Headers['Retry-After']
            $RetryAfterSeconds = 0
            if ($RetryAfterValue -and [int]::TryParse($RetryAfterValue, [ref]$RetryAfterSeconds)) {
                return [Math]::Max(0, $RetryAfterSeconds)
            }

            $RetryAfterDate = [DateTimeOffset]::MinValue
            if ($RetryAfterValue -and [DateTimeOffset]::TryParse(
                    $RetryAfterValue,
                    [System.Globalization.CultureInfo]::InvariantCulture,
                    [System.Globalization.DateTimeStyles]::AssumeUniversal,
                    [ref]$RetryAfterDate
                )) {
                $DelaySeconds = ($RetryAfterDate.ToUniversalTime() - [DateTimeOffset]::UtcNow).TotalSeconds
                return [Math]::Max(0, [int][Math]::Ceiling($DelaySeconds))
            }
        }
    }
    catch {
        Write-Verbose "Could not parse Retry-After header: $($_.Exception.Message)"
    }

    return $DefaultSeconds
}

function Test-ScubaTransientConnectionError {
    <#
    .SYNOPSIS
        Determines whether a REST call failure with no HTTP response object represents a
        transient connection-level issue (timeout, DNS blip, connection reset) worth retrying.
 
    .DESCRIPTION
        PS 5.1 throws System.Net.WebException with a .Status enum that reliably identifies
        timeouts/connection failures. PS 7+ throws a mix of types (HttpRequestException,
        TaskCanceledException, IOException, SocketException) with no single reliable status
        enum, so those are matched by exception type name, falling back to a message-text
        match for anything else that looks like a timeout/connection failure.
 
    .PARAMETER ErrorRecord
        The error record whose exception should be inspected.
 
    .FUNCTIONALITY
        Internal
    #>

    [CmdletBinding()]
    param(
        [Parameter(Mandatory = $true)]
        $ErrorRecord
    )

    $Exception = $ErrorRecord.Exception
    while ($null -ne $Exception) {
        if ($Exception -is [System.Net.WebException]) {
            $TransientStatuses = @(
                [System.Net.WebExceptionStatus]::Timeout,
                [System.Net.WebExceptionStatus]::ConnectFailure,
                [System.Net.WebExceptionStatus]::ConnectionClosed,
                [System.Net.WebExceptionStatus]::KeepAliveFailure,
                [System.Net.WebExceptionStatus]::NameResolutionFailure,
                [System.Net.WebExceptionStatus]::ReceiveFailure,
                [System.Net.WebExceptionStatus]::SendFailure
            )
            return $Exception.Status -in $TransientStatuses
        }

        if ($Exception -is [System.TimeoutException] -or $Exception.GetType().FullName -in @(
                'System.Threading.Tasks.TaskCanceledException',
                'System.Net.Http.HttpRequestException',
                'System.IO.IOException',
                'System.Net.Sockets.SocketException'
            )) {
            return $true
        }

        if ($Exception.Message -match 'timed out|timeout|connection.*(closed|reset|refused)|name.*resolution') {
            return $true
        }
        $Exception = $Exception.InnerException
    }
    return $false
}

function Invoke-ScubaRestMethod {
    <#
    .SYNOPSIS
        Invokes an authenticated REST API method using a Bearer token.
 
    .DESCRIPTION
        Generic wrapper for making authenticated REST API calls. Supports different
        content types for different APIs (e.g., SharePoint uses odata=verbose, Power Platform uses standard JSON).
 
    .PARAMETER BaseUrl
        The base URL of the API (e.g., SharePoint Admin URL or BAP base URL).
 
    .PARAMETER AccessToken
        The OAuth2 access token.
 
    .PARAMETER Endpoint
        The API endpoint path (e.g., "/_api/SPO.Tenant").
 
    .PARAMETER Method
        HTTP method (default: GET).
 
    .PARAMETER Body
        Request body (optional).
 
    .PARAMETER ContentType
        The Content-Type header value (default: "application/json").
 
    .PARAMETER Accept
        The Accept header value (optional). If not specified, not included in headers.
 
    .PARAMETER AdditionalHeaders
        Extra request headers to send beyond Authorization/Content-Type/Accept (optional).
        Keys that collide with the protected Authorization/Content-Type/Accept headers are ignored.
 
    .PARAMETER TimeoutSec
        Request timeout in seconds (optional). If not specified, uses Invoke-RestMethod's default.
 
    .PARAMETER MaxRetries
        Number of retries on HTTP 408/429/500/502/503/504 responses and transient connection errors,
        including timeouts (default: 0, i.e. no retries; max: 100).
 
    .PARAMETER RetryDelaySeconds
        Initial retry delay in seconds, used as a fallback when a 429/5xx response has no Retry-After
        header, and doubled after each successive retry (default: 5). Any single sleep,
        including a server-supplied Retry-After, is capped at MaxDelaySeconds.
 
    .PARAMETER MaxDelaySeconds
        Upper bound in seconds on any single sleep between retries (default: 3600; range 1-3600).
        Keeps a large or hostile Retry-After value from stalling a scan. The Teams, SharePoint,
        Power Platform and Power BI helpers use a lower cap, see Get-ScubaRestRetryDefaults.
    .EXAMPLE
        Invoke-ScubaRestMethod -BaseUrl "https://api.bap.microsoft.com" `
            -AccessToken $Token -Endpoint "/providers/PowerPlatform.Governance/v1/tenants/settings"
        Calls the Power Platform tenant settings API using the default JSON content type.
 
    .EXAMPLE
        Invoke-ScubaRestMethod -BaseUrl "https://contoso-admin.sharepoint.com" `
            -AccessToken $Token -Endpoint "/_api/SPO.Tenant" `
            -ContentType "application/json;odata=verbose" `
            -Accept "application/json;odata=verbose"
        Calls the SharePoint Admin REST API with odata=verbose headers.
 
    .EXAMPLE
        Invoke-ScubaRestMethod -BaseUrl "https://api.bap.microsoft.com" `
            -AccessToken $Token -Endpoint "/providers/PowerPlatform.Governance/v1/tenants/settings" `
            -Method "POST" -Body '{"walkMeOptOut": true}'
        Makes a POST request to the Power Platform API with a JSON body.
 
    .EXAMPLE
        Invoke-ScubaRestMethod -BaseUrl $ApiEndpoint -AccessToken $Token -Endpoint "" `
            -Method "POST" -Body $Body -MaxRetries 3 -RetryDelaySeconds 5
        Makes a POST request with up to 3 retries on throttling/transient server errors.
 
    .FUNCTIONALITY
        Internal
    #>

    [CmdletBinding()]
    param(
        [Parameter(Mandatory = $true)]
        [string]$BaseUrl,

        [Parameter(Mandatory = $true)]
        [string]$AccessToken,

        [Parameter(Mandatory = $true)]
        [AllowEmptyString()]
        [string]$Endpoint,

        [Parameter(Mandatory = $false)]
        [string]$Method = "GET",

        [Parameter(Mandatory = $false)]
        [string]$Body = $null,

        [Parameter(Mandatory = $false)]
        [string]$ContentType = "application/json",

        [Parameter(Mandatory = $false)]
        [string]$Accept = $null,

        [Parameter(Mandatory = $false)]
        [hashtable]$AdditionalHeaders = $null,

        [Parameter(Mandatory = $false)]
        [ValidateRange(0, 300)]
        [int]$TimeoutSec = 0,

        [Parameter(Mandatory = $false)]
        [ValidateRange(0, 100)]
        [int]$MaxRetries = 0,

        [Parameter(Mandatory = $false)]
        [ValidateRange(0, 3600)]
        [int]$RetryDelaySeconds = 5,

        [Parameter(Mandatory = $false)]
        [ValidateRange(1, 3600)]
        [int]$MaxDelaySeconds = 3600
    )

    $Uri = "$BaseUrl$Endpoint"
    $Headers = @{
        "Authorization" = "Bearer $AccessToken"
        "Content-Type"  = $ContentType
    }

    if ($Accept) {
        $Headers["Accept"] = $Accept
    }

    if ($AdditionalHeaders) {
        $ProtectedHeaders = @('Authorization', 'Content-Type', 'Accept')
        foreach ($HeaderName in $AdditionalHeaders.Keys) {
            if ($HeaderName -in $ProtectedHeaders) {
                Write-Warning "Ignoring attempt to override protected header '$HeaderName' via AdditionalHeaders."
                continue
            }
            $Headers[$HeaderName] = $AdditionalHeaders[$HeaderName]
        }
    }

    $Params = @{
        Uri         = $Uri
        Method      = $Method
        Headers     = $Headers
        ErrorAction = "Stop"
    }

    if ($Body) {
        $Params.Body = $Body
    }

    if ($TimeoutSec -gt 0) {
        $Params.TimeoutSec = $TimeoutSec
    }

    for ($Attempt = 1; $Attempt -le ($MaxRetries + 1); $Attempt++) {
        try {
            $Response = Invoke-RestMethod @Params
            # Some services (e.g. the Teams admin API) send gzip bodies that Invoke-RestMethod does not
            # decompress, yielding the compressed bytes as a string that starts with the 0x1F magic byte.
            if ($Response -is [string] -and $Response.Length -gt 0 -and $Response[0] -eq [char]0x1F) {
                Write-Verbose "Response from '$Uri' was not decompressed; re-reading it as gzip."
                $Response = Read-ScubaCompressedRestResponse -RequestParams $Params
            }
            return $Response
        }
        # If an error occurs we want to capture the HTTP body because that commonly contains important troubleshooting details.
        catch {
            $ErrorRecord = $_
            $WebResponse = $ErrorRecord.Exception.Response
            $StatusCode = if ($WebResponse) { [int]$WebResponse.StatusCode } else { 0 }
            $IsLastAttempt = $Attempt -gt $MaxRetries

            if (-not $IsLastAttempt -and $StatusCode -eq 429) {
                $RetryAfter = Get-RetryAfterSeconds -HttpResponseObject $WebResponse -DefaultSeconds $RetryDelaySeconds
                $RetryAfter = [Math]::Min($RetryAfter, $MaxDelaySeconds)
                Write-Warning "Request to '$Uri' throttled (HTTP 429). Retrying in ${RetryAfter}s (attempt $Attempt of $MaxRetries)..."
                Start-Sleep -Seconds $RetryAfter
                $RetryDelaySeconds *= 2
                continue
            }

            if (-not $IsLastAttempt -and $StatusCode -in @(408, 500, 502, 503, 504)) {
                $Delay = Get-RetryAfterSeconds -HttpResponseObject $WebResponse -DefaultSeconds $RetryDelaySeconds
                $Delay = [Math]::Min($Delay, $MaxDelaySeconds)
                Write-Warning "Request to '$Uri' returned HTTP $StatusCode. Retrying in ${Delay}s (attempt $Attempt of $MaxRetries)..."
                Start-Sleep -Seconds $Delay
                $RetryDelaySeconds *= 2
                continue
            }

            if (-not $IsLastAttempt -and $null -eq $WebResponse -and (Test-ScubaTransientConnectionError -ErrorRecord $ErrorRecord)) {
                $Delay = [Math]::Min($RetryDelaySeconds, $MaxDelaySeconds)
                Write-Warning "Request to '$Uri' failed with a transient connection error ($($ErrorRecord.Exception.GetType().Name): $($ErrorRecord.Exception.Message)). Retrying in ${Delay}s (attempt $Attempt of $MaxRetries)..."
                Start-Sleep -Seconds $Delay
                $RetryDelaySeconds *= 2
                continue
            }

            if ($null -eq $WebResponse) {
                Write-Information "No HTTP response object was returned.`nException Type: $($ErrorRecord.Exception.GetType().FullName)`nMessage : $($ErrorRecord.Exception.Message)" -InformationAction Continue
                throw
            }

            $DetailedHttpMessage = Get-HttpResponseDetails -HttpResponseObject $WebResponse -ErrorDetailsMessage $ErrorRecord.ErrorDetails.Message
            Write-Information $DetailedHttpMessage -InformationAction Continue
            throw
        }
    }
}

function Read-ScubaCompressedRestResponse {
    <#
    .SYNOPSIS
        Re-issues a REST request with Invoke-WebRequest and returns the gzip-decompressed body,
        parsed as JSON when possible.
 
    .DESCRIPTION
        Used by Invoke-ScubaRestMethod when Invoke-RestMethod returns a gzip body as an undecoded
        string. The string form cannot be decompressed because text decoding has already corrupted
        the bytes, so the request is repeated and the raw bytes are read from RawContentStream.
 
    .PARAMETER RequestParams
        The Invoke-RestMethod parameter hashtable (Uri, Method, Headers, Body, TimeoutSec, ...).
 
    .FUNCTIONALITY
        Internal
    #>

    [CmdletBinding()]
    param(
        [Parameter(Mandatory = $true)]
        [hashtable]$RequestParams
    )

    $WebParams = $RequestParams.Clone()
    $WebParams.UseBasicParsing = $true
    $WebResponse = Invoke-WebRequest @WebParams
    $Bytes = $WebResponse.RawContentStream.ToArray()

    if ($Bytes.Length -ge 2 -and $Bytes[0] -eq 0x1F -and $Bytes[1] -eq 0x8B) {
        $GzipStream = [System.IO.Compression.GZipStream]::new(
            [System.IO.MemoryStream]::new($Bytes), [System.IO.Compression.CompressionMode]::Decompress)
        $Reader = [System.IO.StreamReader]::new($GzipStream, [System.Text.Encoding]::UTF8)
        try {
            $Text = $Reader.ReadToEnd()
        }
        finally {
            $Reader.Dispose()
        }
    }
    else {
        $Text = [System.Text.Encoding]::UTF8.GetString($Bytes)
    }

    if ([string]::IsNullOrWhiteSpace($Text)) {
        return $Text
    }
    try {
        return ($Text | ConvertFrom-Json -ErrorAction Stop)
    }
    catch {
        return $Text
    }
}

function Get-ScubaRestRetryDefaults {
    <#
    .SYNOPSIS
        Returns the throttling/transient-error retry settings that the Teams, SharePoint, Power Platform and Power BI REST helpers pass to Invoke-ScubaRestMethod.
 
    .DESCRIPTION
        Defined once so those provider REST helpers retry the same way: up to 3 retries, honoring a
        server-supplied Retry-After on HTTP 429, with no single wait longer than 120 seconds. Splat the
        result onto Invoke-ScubaRestMethod. The Exchange Online helper keeps its own settings (3 retries,
        5 second delay, default wait cap) and does not use this function.
 
    .EXAMPLE
        $Retry = Get-ScubaRestRetryDefaults
        Invoke-ScubaRestMethod -BaseUrl $BaseUrl -AccessToken $AccessToken -Endpoint $Endpoint -Method "GET" @Retry
 
    .FUNCTIONALITY
        Internal
    #>

    [CmdletBinding()]
    [OutputType([hashtable])]
    param()

    return @{
        MaxRetries        = 3
        RetryDelaySeconds = 5
        MaxDelaySeconds   = 120
    }
}

function Get-HttpResponseDetails {
    <#
    .SYNOPSIS
        Formats an HTTP response object into a human-readable diagnostic string.
 
    .DESCRIPTION
        Handles the three response object shapes ScubaGear's REST callers actually encounter:
        the WebResponseObject Invoke-WebRequest returns directly on success, System.Net.HttpWebResponse
        (PS 5.1 exception .Response), and System.Net.Http.HttpResponseMessage (PS 7+ exception .Response).
 
    .PARAMETER HttpResponseObject
        The response object to format (either a direct Invoke-WebRequest return value, or an
        exception's .Response property).
 
    .PARAMETER ErrorDetailsMessage
        Only used for HttpResponseMessage: PS 7+ disposes the response content stream by the time
        the catch block runs, so the body (when parseable) has to come from the caller's
        $ErrorRecord.ErrorDetails.Message instead.
 
    .FUNCTIONALITY
        Internal
    #>

    [CmdletBinding()]
    param(
        [Parameter(Mandatory = $true)]
        $HttpResponseObject,

        [Parameter(Mandatory = $false)]
        [string]$ErrorDetailsMessage
    )

    $StringBuffer = [System.Text.StringBuilder]::new()
    [void]$StringBuffer.AppendLine("`nResponse Type : $($HttpResponseObject.GetType().FullName)")

    if ($HttpResponseObject -is [Microsoft.PowerShell.Commands.WebResponseObject]) {
        # Direct return value of Invoke-WebRequest (e.g. HTTP 202/3xx) - Content is already a string.
        [void]$StringBuffer.AppendLine("Status Code : $([int]$HttpResponseObject.StatusCode)")
        [void]$StringBuffer.AppendLine("Status Text : $($HttpResponseObject.StatusDescription)")
        [void]$StringBuffer.AppendLine("")
        [void]$StringBuffer.AppendLine("=== Response Headers ===")
        foreach ($HeaderName in $HttpResponseObject.Headers.Keys) {
            [void]$StringBuffer.AppendLine("${HeaderName}: $($HttpResponseObject.Headers[$HeaderName])")
        }
        [void]$StringBuffer.AppendLine("")
        [void]$StringBuffer.AppendLine("=== Raw Response Body ===")
        [void]$StringBuffer.AppendLine($(if ([string]::IsNullOrWhiteSpace($HttpResponseObject.Content)) { "Empty response body." } else { $HttpResponseObject.Content }))
    }
    elseif ($HttpResponseObject.GetType().FullName -eq 'System.Net.Http.HttpResponseMessage') {
        # PowerShell 7+ HttpResponseException.Response
        [void]$StringBuffer.AppendLine("Status Code : $([int]$HttpResponseObject.StatusCode)")
        [void]$StringBuffer.AppendLine("Status Text : $($HttpResponseObject.ReasonPhrase)")
        [void]$StringBuffer.AppendLine("")
        [void]$StringBuffer.AppendLine("=== Response Headers ===")
        foreach ($Header in $HttpResponseObject.Headers) {
            [void]$StringBuffer.AppendLine("$($Header.Key): $($Header.Value -join ', ')")
        }
        [void]$StringBuffer.AppendLine("")
        [void]$StringBuffer.AppendLine("=== Raw Response Body ===")
        # On PS 7+, Invoke-RestMethod already reads and disposes the response content internally,
        # so re-reading .Content throws "Cannot access a disposed object." The body text (when
        # PowerShell can parse it) is instead surfaced via ErrorRecord.ErrorDetails.Message.
        [void]$StringBuffer.AppendLine($(if ([string]::IsNullOrWhiteSpace($ErrorDetailsMessage)) { "Empty response body." } else { $ErrorDetailsMessage }))
    }
    else {
        # PowerShell 5.1 WebException.Response (System.Net.HttpWebResponse)
        [void]$StringBuffer.AppendLine("Status Code : $([int]$HttpResponseObject.StatusCode)")
        [void]$StringBuffer.AppendLine("Status Text : $($HttpResponseObject.StatusDescription)")
        [void]$StringBuffer.AppendLine("Content Type : $($HttpResponseObject.ContentType)")
        [void]$StringBuffer.AppendLine("Content Length: $($HttpResponseObject.ContentLength)")
        [void]$StringBuffer.AppendLine("")
        [void]$StringBuffer.AppendLine("=== Response Headers ===")
        foreach ($HeaderName in $HttpResponseObject.Headers.AllKeys) {
            [void]$StringBuffer.AppendLine("${HeaderName}: $($HttpResponseObject.Headers[$HeaderName])")
        }
        [void]$StringBuffer.AppendLine("")
        [void]$StringBuffer.AppendLine("=== Raw Response Body ===")
        $HttpResponseStream = $HttpResponseObject.GetResponseStream()
        if ($null -eq $HttpResponseStream) {
            [void]$StringBuffer.AppendLine("No response stream in Error.Exception.Response object.")
        }
        else {
            $HttpResponseReader = New-Object System.IO.StreamReader($HttpResponseStream)
            try {
                $ResponseBody = $HttpResponseReader.ReadToEnd()
            }
            finally {
                $HttpResponseReader.Dispose()
                $HttpResponseStream.Dispose()
            }
            [void]$StringBuffer.AppendLine($(if ([string]::IsNullOrWhiteSpace($ResponseBody)) { "Empty response body." } else { $ResponseBody }))
        }
    }

    return $StringBuffer.ToString()
}

function Get-HttpRetryInfo {
    <#
    .SYNOPSIS
        Pulls out what a REST caller needs to decide whether a failed request is worth retrying.
 
    .DESCRIPTION
        Returns the HTTP status code (0 when the request never got a response), the Retry-After
        delay in seconds (0 when the header is missing), and whether the failure was a network-level
        error such as a timeout, dropped connection or DNS failure.
 
        Works with the exception shapes Invoke-WebRequest and Invoke-RestMethod throw on both
        PS 5.1 (WebException with an HttpWebResponse) and PS 7+ (HttpResponseException with an
        HttpResponseMessage, or TaskCanceledException on timeout).
 
    .PARAMETER Exception
        The exception caught from Invoke-WebRequest or Invoke-RestMethod.
 
    .FUNCTIONALITY
        Internal
    #>

    [CmdletBinding()]
    [OutputType([pscustomobject])]
    param(
        [Parameter(Mandatory = $true)]
        [System.Exception]
        $Exception
    )

    $StatusCode = 0
    $RetryAfterSeconds = 0
    $IsNetworkError = $false

    $ResponseProperty = $Exception.PSObject.Properties['Response']
    $Response = if ($null -ne $ResponseProperty) { $ResponseProperty.Value } else { $null }

    if ($null -ne $Response) {
        $StatusCode = [int]$Response.StatusCode
        $RetryAfterSeconds = Get-RetryAfterSeconds -HttpResponseObject $Response -DefaultSeconds 0
    }
    else {
        $IsNetworkError = Test-ScubaTransientConnectionError -ErrorRecord ([pscustomobject]@{ Exception = $Exception })
    }

    [pscustomobject]@{
        StatusCode        = $StatusCode
        RetryAfterSeconds = [Math]::Max(0, $RetryAfterSeconds)
        IsNetworkError    = $IsNetworkError
    }
}

function Get-ScubaGearCatalog {
    <#
    .Description
    Loads the full ScubaGear API catalog (schemas/ScubaGearApiCatalog.json).
    .Functionality
    Internal
    #>

    [CmdletBinding()]
    param()
    [string]$ResourceRoot = ($PWD.ProviderPath, $PSScriptRoot)[[bool]$PSScriptRoot]
    return (Get-Content -Path "$ResourceRoot\..\..\schemas\ScubaGearApiCatalog.json" -Raw | ConvertFrom-Json)
}

function Get-ScubaGearServiceEndpoint {
    <#
    .Description
    Returns the base service URL(s) for a product/environment (Graph connect or REST API host),
    substituting the {domain} placeholder (SharePoint) when supplied.
    .Functionality
    Internal
    #>

    [CmdletBinding()]
    param(
        [Parameter(Mandatory = $true, ValueFromPipeline = $true)]
        [string[]]$Product,

        [Parameter(Mandatory = $false)]
        [ValidateSet('commercial', 'gcc', 'gcchigh', 'dod')]
        [string]$Environment = 'commercial',

        [Parameter(Mandatory = $false)]
        [string]$Domain
    )
    process {
        if (($Product -contains 'sharepoint') -and -not $Domain) {
            Write-Error -Message "Parameter [-Domain] is required when resolving the SharePoint endpoint."
        }
        Get-ScubaGearCatalog | Where-Object {
            $item = $_
            ($item.entryType -in @('graphConnect', 'restBase')) -and
            ($Product | Where-Object { $item.scubaGearProduct -contains $_ }) -and
            ($item.supportedEnv -contains $Environment)
        } | ForEach-Object { $_.endpointPath -replace '\{domain\}', $Domain } | Select-Object -Unique
    }
}

function Get-ScubaGearOAuthScope {
    <#
    .Description
    Returns the OAuth2 scope(s) used to mint a token for a product/environment.
    .Functionality
    Internal
    #>

    [CmdletBinding()]
    param(
        [Parameter(Mandatory = $true, ValueFromPipeline = $true)]
        [string[]]$Product,

        [Parameter(Mandatory = $false)]
        [ValidateSet('commercial', 'gcc', 'gcchigh', 'dod')]
        [string]$Environment = 'commercial',

        [Parameter(Mandatory = $false)]
        [string]$Domain
    )
    process {
        Get-ScubaGearCatalog | Where-Object {
            $item = $_
            ($item.entryType -ne 'restHelper') -and
            ($Product | Where-Object { $item.scubaGearProduct -contains $_ }) -and
            ($item.supportedEnv -contains $Environment)
        } | ForEach-Object { $_.oauthScope -replace '\{domain\}', $Domain } |
            Where-Object { $_ -ne '' } | Select-Object -Unique
    }
}

function Get-ScubaGearGraphEndpoint {
    <#
    .Description
    Returns the full Microsoft Graph request URI for a given cmdlet name: the graphConnect base URL
    for the environment combined with the cmdlet's resource path and filter, substituting {id}.
    .Functionality
    Internal
    #>

    [CmdletBinding()]
    param(
        [Parameter(Mandatory = $true)]
        [string]$CmdletName,

        [Parameter(Mandatory = $false)]
        [ValidateSet('commercial', 'gcc', 'gcchigh', 'dod')]
        [string]$Environment = 'commercial',

        [Parameter(Mandatory = $false)]
        [string]$Id
    )
    $catalog = Get-ScubaGearCatalog
    $base = $catalog | Where-Object { $_.entryType -eq 'graphConnect' -and $_.supportedEnv -contains $Environment } |
        ForEach-Object { $_.endpointPath } | Select-Object -Unique

    $catalog | Where-Object {
        $_.functionName -eq $CmdletName -and $_.entryType -ne 'graphConnect' -and $_.supportedEnv -contains $Environment
    } | ForEach-Object {
        $resource = $_.endpointPath -replace '\{id\}', $Id
        if ($_.apiFilter) {
            "$base$resource" + ($_.apiFilter -replace '\{id\}', $Id)
        } else {
            "$base$resource"
        }
    } | Select-Object -Unique
}

function Get-ScubaGearApiHeader {
    <#
    .Description
    Returns the HTTP header object(s) a given Graph cmdlet requires, if any.
    .Functionality
    Internal
    #>

    [CmdletBinding()]
    param(
        [Parameter(Mandatory = $true)]
        [string]$CmdletName,

        [Parameter(Mandatory = $false)]
        [ValidateSet('commercial', 'gcc', 'gcchigh', 'dod')]
        [string]$Environment = 'commercial'
    )
    Get-ScubaGearCatalog | Where-Object {
        $_.functionName -eq $CmdletName -and $_.supportedEnv -contains $Environment
    } | Where-Object { @($_.apiHeader).Count -gt 0 } | ForEach-Object { $_.apiHeader } | Select-Object -Unique
}

function Get-ScubaGearRestEndpoint {
    <#
    .Description
    Looks up the fixed REST endpoint path for a ScubaGear provider REST helper function from the
    restHelper entries in ScubaGearApiCatalog.json, substituting any supplied {placeholder} values.
    .Parameter FunctionName
    The REST helper function name, matching the catalog's functionName field (e.g. "Get-SPOTenantRest").
    .Parameter PathParameters
    Optional hashtable of {placeholder} substitutions, e.g. @{ TenantId = $TenantId }.
    .Functionality
    Internal
    #>

    [CmdletBinding()]
    param(
        [Parameter(Mandatory = $true)]
        [string]$FunctionName,

        [Parameter(Mandatory = $false)]
        [hashtable]$PathParameters
    )

    $Catalog = Get-ScubaGearCatalog
    $Entry = $Catalog | Where-Object { $_.functionName -eq $FunctionName }
    if (-not $Entry) {
        throw "No REST API catalog entry found for function '$FunctionName' in ScubaGearApiCatalog.json"
    }

    $EndpointPath = $Entry.endpointPath
    if ([string]::IsNullOrWhiteSpace($EndpointPath)) {
        throw "Function '$FunctionName' has no fixed endpointPath in the REST API catalog."
    }

    # The catalog declares the placeholder keys this endpoint expects in $Entry.parameters; callers
    # supply their values via -PathParameters. Unsupplied placeholders are left intact.
    if ($PathParameters) {
        foreach ($Key in $PathParameters.Keys) {
            $EndpointPath = $EndpointPath.Replace("{$Key}", [string]$PathParameters[$Key])
        }
    }

    return $EndpointPath
}

Export-ModuleMember -Function @(
    'Get-Utf8NoBom',
    'Set-Utf8NoBom',
    'Invoke-GraphDirectly',
    'Resolve-ScubaOrganization',
    'ConvertFrom-GraphHashtable',
    'Invoke-GraphBatchRequest',
    'Invoke-ScubaRestMethod',
    'Get-ScubaRestRetryDefaults',
    'Get-HttpResponseDetails',
    'Get-HttpRetryInfo',
    'Get-ScubaGearCatalog',
    'Get-ScubaGearServiceEndpoint',
    'Get-ScubaGearOAuthScope',
    'Get-ScubaGearGraphEndpoint',
    'Get-ScubaGearApiHeader',
    'Get-ScubaGearRestEndpoint'
)

# SIG # Begin signature block
# MIIu9gYJKoZIhvcNAQcCoIIu5zCCLuMCAQExDzANBglghkgBZQMEAgEFADB5Bgor
# BgEEAYI3AgEEoGswaTA0BgorBgEEAYI3AgEeMCYCAwEAAAQQH8w7YFlLCE63JNLG
# KX7zUQIBAAIBAAIBAAIBAAIBADAxMA0GCWCGSAFlAwQCAQUABCC68SAX7FfYcURo
#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