src/Private/Connect-ReclaimGraph.ps1

function Connect-ReclaimGraph {
    <#
    .SYNOPSIS
        Establishes a read-only Microsoft Graph session for the license scan.
    .DESCRIPTION
        Thin wrapper over Connect-MgGraph (Microsoft.Graph.Authentication). Requests the minimum
        read scopes the scan needs. Supports interactive/delegated sign-in (default) or app-only
        (client credentials) when a TenantId + ClientId + certificate thumbprint are supplied.

        If a usable Graph context already exists it is reused rather than forcing a new sign-in.
    .NOTES
        Scopes (least privilege, all read):
          User.Read.All - read user accounts and their assignedLicenses
          Organization.Read.All - read the tenant's subscribedSkus / license inventory
        Directory.Read.All can substitute for both where org policy prefers a single scope.
    #>

    [CmdletBinding()]
    param(
        [string]   $TenantId,
        [string]   $ClientId,
        [string]   $CertificateThumbprint,
        [string[]] $Scopes = @('User.Read.All', 'Organization.Read.All')
    )

    if (-not (Get-Command Connect-MgGraph -ErrorAction SilentlyContinue)) {
        throw "Microsoft.Graph.Authentication is required. Install-Module Microsoft.Graph.Authentication -Scope CurrentUser"
    }

    $existing = Get-MgContext -ErrorAction SilentlyContinue
    if ($existing) {
        Write-Verbose "Reusing existing Graph context for tenant $($existing.TenantId)."
        return $existing
    }

    if ($TenantId -and $ClientId -and $CertificateThumbprint) {
        Write-Verbose "Connecting to Graph app-only (client credentials) for tenant $TenantId."
        Connect-MgGraph -TenantId $TenantId -ClientId $ClientId -CertificateThumbprint $CertificateThumbprint -NoWelcome -ErrorAction Stop | Out-Null
    }
    else {
        Write-Verbose "Connecting to Graph interactively with scopes: $($Scopes -join ', ')."
        Connect-MgGraph -Scopes $Scopes -NoWelcome -ErrorAction Stop | Out-Null
    }

    return Get-MgContext
}