<#
    healthcheck.ps1 — VelaPanel automatic module/health check (Option A wrapper)

    Runs the outside-observable smoke checks and the unit-test suite. The deep per-module
    integration probe (IIS, MySQL, mail COM, DNS, etc.) lives in the panel UI at
    /admin/health (Admin only) and the API at GET /api/health/modules.

    Usage:
        powershell -ExecutionPolicy Bypass -File C:\velapanel.com\tools\healthcheck.ps1
        ...\healthcheck.ps1 -SkipTests     # skip the xUnit run (faster)
        ...\healthcheck.ps1 -Port 5100

    Exit code 0 = all checks passed, 1 = one or more failed.
#>
param(
    [int]    $Port      = 5100,
    [string] $Scheme    = "http",
    [switch] $SkipTests
)

$ErrorActionPreference = "Continue"
$fail = 0

# Windows PowerShell 5.1 has no -SkipCertificateCheck on Invoke-WebRequest. When probing
# https with a self-signed panel cert, disable validation the 5.1 way (process-wide callback).
if ($Scheme -eq "https" -and $PSVersionTable.PSVersion.Major -lt 6) {
    try {
        Add-Type @"
using System.Net;
using System.Security.Cryptography.X509Certificates;
public class VelaCertBypass {
    public static void Enable() {
        ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
        ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
    }
}
"@ -ErrorAction SilentlyContinue
        [VelaCertBypass]::Enable()
    } catch { }
}

function Check($name, [scriptblock]$test) {
    try {
        $ok, $detail = & $test
        if ($ok) { Write-Host ("[ OK ] {0,-28} {1}" -f $name, $detail) -ForegroundColor Green }
        else     { Write-Host ("[FAIL] {0,-28} {1}" -f $name, $detail) -ForegroundColor Red; $script:fail++ }
    } catch {
        Write-Host ("[FAIL] {0,-28} {1}" -f $name, $_.Exception.Message) -ForegroundColor Red
        $script:fail++
    }
}

Write-Host "`n=== VelaPanel Health Check ===`n" -ForegroundColor Cyan

# 1. Windows service state
Check "VelaPanel service" {
    $s = Get-Service -Name VelaPanel -ErrorAction Stop
    ($s.Status -eq 'Running'), $s.Status
}

# 2. Port listening
Check "Port $Port listening" {
    $c = Test-NetConnection -ComputerName localhost -Port $Port -WarningAction SilentlyContinue
    $c.TcpTestSucceeded, ("TcpTestSucceeded=" + $c.TcpTestSucceeded)
}

# 3. Anonymous liveness endpoint (web host + panel DB)
Check "Liveness /api/health/live" {
    $r = Invoke-WebRequest -Uri "$($Scheme)://localhost:$Port/api/health/live" `
            -UseBasicParsing -TimeoutSec 15 -ErrorAction Stop
    ($r.StatusCode -eq 200), ("HTTP " + $r.StatusCode + " " + $r.Content)
}

# 4. Login page responds
Check "Login page" {
    $r = Invoke-WebRequest -Uri "$($Scheme)://localhost:$Port/login" `
            -UseBasicParsing -TimeoutSec 15 -ErrorAction Stop
    ($r.StatusCode -eq 200), ("HTTP " + $r.StatusCode)
}

# 5. Core data files present
Check "panel.db present" {
    $p = "C:\velapanel.com\data\panel.db"; (Test-Path $p), $p
}
Check "encryption.key present" {
    $p = "C:\velapanel.com\data\encryption.key"; (Test-Path $p), $p
}

# 6. Unit test suite
if (-not $SkipTests) {
    $dotnet = if (Test-Path "C:\dotnet\dotnet.exe") { "C:\dotnet\dotnet.exe" } else { "dotnet" }
    $proj   = "C:\velapanel.com\VelaPanel.Tests\VelaPanel.Tests.csproj"
    Check "Unit tests (xUnit)" {
        $out = & $dotnet test $proj --nologo --verbosity quiet 2>&1 | Out-String
        $passed = $out -match "Passed!" -or ($out -match "Failed:\s*0")
        $summary = ($out -split "`n" | Where-Object { $_ -match "Passed|Failed|error" } | Select-Object -Last 1)
        $passed, ($summary -replace '\s+', ' ').Trim()
    }
}

Write-Host ""
if ($fail -eq 0) {
    Write-Host "ALL CHECKS PASSED" -ForegroundColor Green
    Write-Host "Deep per-module probe: open $($Scheme)://localhost:$Port/admin/health (Admin login)" -ForegroundColor DarkGray
    exit 0
} else {
    Write-Host "$fail CHECK(S) FAILED" -ForegroundColor Red
    exit 1
}
