Private/Authentication/Microsoft/Initialize-TokenCache.ps1

function Initialize-TokenCache {
    [CmdletBinding()]
    param()
    
    try {
        # Create cache directory if it doesn't exist
        $cacheDir = Split-Path $script:TokenCacheConfig.PersistencePath -Parent
        if (-not (Test-Path $cacheDir)) {
            New-Item -Path $cacheDir -ItemType Directory -Force | Out-Null
        }

        # Initialize empty hashtable
        $script:TokenCache = @{}

        # Load cached tokens if they exist
        if (Test-Path $script:TokenCacheConfig.PersistencePath) {
            try {
                $importedCache = Import-Clixml -Path $script:TokenCacheConfig.PersistencePath
                # Only import non-expired tokens
                $importedCache.GetEnumerator() | 
                Where-Object { $_.Value.ExpirationDateTime -gt (Get-Date) } |
                ForEach-Object { 
                    $script:TokenCache[$_.Key] = $_.Value 
                }
            }
            catch {
                Write-ModuleLog -Message "Failed to load token cache from disk" -Level Warning -Component 'TokenCache'
            }
        }
    }
    catch {
        Write-ModuleLog -Message "Failed to initialize token cache" -Level Warning -Component 'TokenCache'
        $script:TokenCache = @{}
    }
}
function Save-TokenCache {
    [CmdletBinding()]
    param()
    
    try {
        if((Test-Path $script:TokenCacheConfig.PersistencePath) -and ($Script:TokenCache.Count -ne 0)) {
            $script:TokenCache | Export-Clixml -Path $script:TokenCacheConfig.PersistencePath -Force
        }
    }
    catch {
        Write-ModuleLog -Message "Failed to save token cache to disk" -Level Error -Component 'Tokencache' `
            -ErrorRecord $_ -ThrowError -ErrorOperation 'SaveToDisk' -ErrorMessage 'Failed to save token cache to disk'
    }
}