$setupToolsScript = (Resolve-Path -LiteralPath (Join-Path $PSScriptRoot '..\scripts\setup-tools.ps1')).Path
$expectedOutput = @(
    'Preparing environment...'
    ''
    'Initializing PowerShell environment...'
    'PowerShell environment initialized.'
    ''
    'Environment preparation complete!'
) -join "`n"

Describe 'setup-tools.ps1' {
    It 'imports powershell-yaml and preserves the user-facing output' {
        $originalModulePath = $env:PSModulePath
        try {
            $moduleRoot = Join-Path $TestDrive 'available-modules'
            $moduleDirectory = Join-Path $moduleRoot 'powershell-yaml'
            $null = New-Item -ItemType Directory -Path $moduleDirectory
            Set-Content -LiteralPath (Join-Path $moduleDirectory 'powershell-yaml.psm1') -Value ''
            $env:PSModulePath = $moduleRoot

            $escapedScriptPath = $setupToolsScript.Replace("'", "''")
            $command = "& '$escapedScriptPath'; if (-not (Get-Module -Name powershell-yaml)) { exit 42 }"

            $output = @(& pwsh -NoProfile -Command $command 6>&1 | ForEach-Object { $_.ToString() })

            $LASTEXITCODE | Should Be 0
            ($output -join "`n") | Should Be $expectedOutput
        }
        finally {
            $env:PSModulePath = $originalModulePath
        }
    }

    It 'continues successfully when powershell-yaml is unavailable' {
        $originalModulePath = $env:PSModulePath
        try {
            $env:PSModulePath = Join-Path $TestDrive 'missing-modules'

            $output = @(& pwsh -NoProfile -File $setupToolsScript 6>&1 | ForEach-Object { $_.ToString() })

            $LASTEXITCODE | Should Be 0
            ($output -join "`n") | Should Be $expectedOutput
        }
        finally {
            $env:PSModulePath = $originalModulePath
        }
    }
}
