[CmdletBinding()]
param(
    [switch]$Force
)

$appRoot = Split-Path -Parent (Split-Path -Parent $PSScriptRoot)
$Global:AppRoot = $appRoot

. (Join-Path $PSScriptRoot 'Get-ToolADFunctions.ps1')

$adDataPath = Join-Path $appRoot 'AD_Data'
$userSource = Join-Path $adDataPath 'AFUsersDB_AD.json'
$groupSource = Join-Path $adDataPath 'AFGroupsDB_AD.json'
$userCache = Join-Path $adDataPath 'SimADUsers.cache.json'
$groupCache = Join-Path $adDataPath 'SimADGroups.cache.json'

if (-not (Test-Path $adDataPath)) {
    throw "AD_Data folder not found: $adDataPath"
}

if (-not (Test-Path $userSource)) {
    throw "User AD export not found: $userSource"
}

if (-not (Test-Path $groupSource)) {
    throw "Group AD export not found: $groupSource"
}

if (-not $Force -and (Test-Path $userCache) -and (Test-Path $groupCache)) {
    Write-Host "Simulation cache files already exist. Use -Force to rebuild."
    Write-Host "  $userCache"
    Write-Host "  $groupCache"
    return
}

$sw = [System.Diagnostics.Stopwatch]::StartNew()

Write-Host "Building simulation user cache..."
$users = @(Read-ToolADJsonObjects -FilePath $userSource)
$users | ConvertTo-Json -Depth 8 | Set-Content -Path $userCache -Encoding UTF8
Write-Host "  Users cached: $($users.Count)"

Write-Host "Building simulation group cache..."
$groups = @(Read-ToolADJsonObjects -FilePath $groupSource)
$groups | ConvertTo-Json -Depth 8 | Set-Content -Path $groupCache -Encoding UTF8
Write-Host "  Groups cached: $($groups.Count)"

$sw.Stop()
Write-Host "Simulation cache complete in $([math]::Round($sw.Elapsed.TotalSeconds, 2)) second(s)."
Write-Host "Cache files:"
Write-Host "  $userCache"
Write-Host "  $groupCache"
