O365-Toolkit.psm1

# Get the path to the module's private and public directories
# Get the path to the module's private and public directories
$PrivatePath = Join-Path -Path $PSScriptRoot -ChildPath 'Private'
$PublicPath = Join-Path -Path $PSScriptRoot -ChildPath 'Public'

# Run the bundled resolver once per session to avoid PnP/Graph assembly conflicts
if (-not $script:PnPGraphConflictsResolved) {
    $conflictFixScript = Join-Path $PSScriptRoot 'Resolve-TAPnPPowerShellConflicts.ps1'
    if (Test-Path $conflictFixScript) {
        try {
            Write-Verbose "Running PnP/Graph conflict fix..."
            & $conflictFixScript
            $script:PnPGraphConflictsResolved = $true
        }
        catch {
            Write-Warning "PnP/Graph conflict fix failed: $($_.Exception.Message)"
        }
    }
    else {
        Write-Verbose "Conflict resolver script not found at $conflictFixScript"
    }
}

# CRITICAL: Pre-load Microsoft.Graph modules to avoid assembly version conflicts with PnP.PowerShell
# PnP.PowerShell 3.1.0 bundles an old Microsoft.Graph.Core (1.25.1), which causes assembly binding failures
# Loading Microsoft.Graph first ensures the correct versions are in memory
$GraphAuthLoaded = $false
try {
    Write-Verbose "Pre-loading Microsoft.Graph.Authentication to establish correct assembly versions..."
    $graphAuthModule = Get-Module Microsoft.Graph.Authentication -ListAvailable | Sort-Object Version -Descending | Select-Object -First 1
    if ($graphAuthModule) {
        Import-Module $graphAuthModule -ErrorAction SilentlyContinue -WarningAction SilentlyContinue | Out-Null
        $GraphAuthLoaded = $?
        if (-not $GraphAuthLoaded) {
            Write-Verbose "Failed to load Microsoft.Graph.Authentication from $($graphAuthModule.ModuleBase)"
        }
    } else {
        Write-Verbose "Microsoft.Graph.Authentication module not found - it will be needed for Graph operations"
    }
} catch {
    Write-Verbose "Error pre-loading Microsoft.Graph: $($_)"
}

# Import all modules from the public folder
Get-ChildItem -Path $PublicPath -Filter '*.ps1' -Recurse | ForEach-Object {
    . $_.FullName
}

# Import all modules from the private folder
Get-ChildItem -Path $PrivatePath -Filter '*.ps1' -Recurse | ForEach-Object {
    . $_.FullName
}