#Requires -Version 5.1

[CmdletBinding()]
param([string] $NodePath)

Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'

if ([string]::IsNullOrWhiteSpace($NodePath)) {
    $command = Get-Command node -CommandType Application -ErrorAction SilentlyContinue |
        Select-Object -First 1
    if ($null -ne $command) {
        $NodePath = $command.Source
    }
    else {
        $bundledNode = Join-Path $env:USERPROFILE `
            '.cache\codex-runtimes\codex-primary-runtime\dependencies\node\bin\node.exe'
        if (Test-Path -LiteralPath $bundledNode -PathType Leaf) {
            $NodePath = $bundledNode
        }
    }

    if ([string]::IsNullOrWhiteSpace($NodePath)) {
        throw 'Node.js was not found. Pass an absolute executable path with -NodePath.'
    }
}

if (-not [IO.Path]::IsPathRooted($NodePath) -or
    -not (Test-Path -LiteralPath $NodePath -PathType Leaf)) {
    throw 'NodePath must identify an existing absolute node executable.'
}

$repositoryRoot = [IO.Path]::GetFullPath((Join-Path $PSScriptRoot '..'))
$appScript = Join-Path $repositoryRoot 'src\MBN_STOCK_WEBVIEW.LegacyParityApp\Web\app.js'
$testRoot = Join-Path $repositoryRoot 'tests\LegacyParityWeb'
$testFiles = @(
    Get-ChildItem -LiteralPath $testRoot -Filter '*.test.cjs' -File |
        Sort-Object -Property FullName |
        Select-Object -ExpandProperty FullName
)

if ($testFiles.Count -eq 0) {
    throw 'No Legacy parity Web test files were found.'
}

& $NodePath --check $appScript
if ($LASTEXITCODE -ne 0) {
    throw "Legacy parity JavaScript syntax validation failed with exit code $LASTEXITCODE."
}

& $NodePath --test @testFiles
if ($LASTEXITCODE -ne 0) {
    throw "Legacy parity Web tests failed with exit code $LASTEXITCODE."
}
