# Check if Node.js server is running on AD2
Write-Host "[OK] Checking Node.js server status..." -ForegroundColor Green

# Test 1: Check port 3000
Write-Host "`n[TEST 1] Testing port 3000..." -ForegroundColor Cyan
$portTest = Test-NetConnection -ComputerName 192.168.0.6 -Port 3000 -WarningAction SilentlyContinue -InformationLevel Quiet

if ($portTest) {
    Write-Host "  [OK] Port 3000 is OPEN" -ForegroundColor Green
} else {
    Write-Host "  [ERROR] Port 3000 is CLOSED" -ForegroundColor Red
    Write-Host "  [INFO] Node.js server is not running" -ForegroundColor Yellow
}

# Test 2: Check Node.js processes (via SMB)
Write-Host "`n[TEST 2] Checking for Node.js processes..." -ForegroundColor Cyan
$password = ConvertTo-SecureString 'Paper123!@#' -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential('INTRANET\sysadmin', $password)

try {
    $nodeProcs = Invoke-Command -ComputerName 192.168.0.6 -Credential $cred -ScriptBlock {
        Get-Process node -ErrorAction SilentlyContinue | Select-Object Id, ProcessName, @{Name='Memory(MB)';Expression={[math]::Round($_.WorkingSet64/1MB,2)}}, Path
    } -ErrorAction Stop

    if ($nodeProcs) {
        Write-Host "  [OK] Node.js process(es) found:" -ForegroundColor Green
        $nodeProcs | Format-Table -AutoSize
    } else {
        Write-Host "  [ERROR] No Node.js process found" -ForegroundColor Red
    }
} catch {
    Write-Host "  [WARNING] WinRM check failed: $($_.Exception.Message)" -ForegroundColor Yellow
    Write-Host "  [INFO] Cannot verify via WinRM, but port test is more reliable" -ForegroundColor Cyan
}

Write-Host "`n[SUMMARY]" -ForegroundColor Cyan
if (!$portTest) {
    Write-Host "  Node.js server is NOT running" -ForegroundColor Red
    Write-Host "`n  [ACTION] Start the server on AD2:" -ForegroundColor Yellow
    Write-Host "    cd C:\Shares\testdatadb" -ForegroundColor Cyan
    Write-Host "    node server.js" -ForegroundColor Cyan
} else {
    Write-Host "  Node.js server appears to be running" -ForegroundColor Green
    Write-Host "  But API endpoints are not responding - check server logs" -ForegroundColor Yellow
}

Write-Host "`n[OK] Done" -ForegroundColor Green
