[CmdletBinding()]
param(
    [string]$DotNet = 'dotnet.exe'
)

$ErrorActionPreference = 'Stop'
$packageRoot = Split-Path -Parent $PSScriptRoot
$feed = Join-Path $packageRoot 'install'
$project = Join-Path $PSScriptRoot 'DataAINuGetSmokeTest.csproj'
$packages = Join-Path $PSScriptRoot '.packages'

foreach ($path in @(
    (Join-Path $feed 'Yanbor.DataAI.Etl.Spark.0.1.0-evaluation.1.nupkg'),
    (Join-Path $feed 'Yanbor.DataAI.Etl.Spark.Runtime.0.1.0-evaluation.1.nupkg'),
    $project)) {
    if (-not (Test-Path -LiteralPath $path -PathType Leaf)) {
        throw "Required NuGet smoke-test file was not found: $path"
    }
}

$dotnetCommand = Get-Command -Name $DotNet -ErrorAction Stop
$dotnetExecutable = if ($dotnetCommand.Source) { $dotnetCommand.Source } else { $dotnetCommand.Path }
& $dotnetExecutable restore $project --source $feed --packages $packages --ignore-failed-sources
if ($LASTEXITCODE -ne 0) {
    throw "NuGet smoke-test restore failed with exit code $LASTEXITCODE."
}
$output = & $dotnetExecutable run --project $project --no-restore 2>&1
$exitCode = $LASTEXITCODE
$output | ForEach-Object { Write-Host $_ }
if ($exitCode -ne 0) {
    throw "NuGet smoke test failed with exit code $exitCode."
}
if (-not (($output | Out-String) -match 'DATAAI_NUGET_SMOKE_TEST_PASS')) {
    throw 'NuGet smoke test did not emit DATAAI_NUGET_SMOKE_TEST_PASS.'
}
