# ============================================================================
# ShopDB Comprehensive Form Testing Script
# ============================================================================
# Tests form submissions across all key pages to verify no errors occur
# Run from PowerShell on a machine that can reach the dev server
#
# Features:
# - Tests all add/edit forms (machines, devices, printers, subnets, etc.)
# - Automatic test data cleanup
# - Detailed pass/fail reporting
# ============================================================================

param(
    [string]$BaseUrl = "http://192.168.122.151:8080",
    [switch]$Verbose,
    [switch]$SkipCleanup,
    [switch]$CleanupOnly
)

$ErrorActionPreference = "Continue"
$TestResults = @()
$TestTimestamp = Get-Date -Format "yyyyMMdd_HHmmss"
$TestPrefix = "AUTOTEST_$TestTimestamp"

# Track created records for cleanup
$CreatedRecords = @{
    Notifications = @()
    Machines = @()
    Printers = @()
    Subnets = @()
    Applications = @()
    KBArticles = @()
    Vendors = @()
    Models = @()
    NetworkDevices = @()
}

# ============================================================================
# HELPER FUNCTIONS
# ============================================================================

function Write-TestResult {
    param(
        [string]$TestName,
        [bool]$Passed,
        [string]$Message = ""
    )

    $status = if ($Passed) { "PASS" } else { "FAIL" }
    $color = if ($Passed) { "Green" } else { "Red" }

    Write-Host "[$status] $TestName" -ForegroundColor $color
    if ($Message -and $Verbose) {
        Write-Host "        $Message" -ForegroundColor Gray
    }

    $script:TestResults += [PSCustomObject]@{
        Test = $TestName
        Status = $status
        Message = $Message
    }
}

function Test-PageLoads {
    param([string]$Url, [string]$TestName, [string]$ExpectedContent = "")

    try {
        $response = Invoke-WebRequest -Uri $Url -UseBasicParsing -TimeoutSec 30
        $passed = $response.StatusCode -eq 200

        if ($passed -and $ExpectedContent) {
            $passed = $response.Content -match $ExpectedContent
        }

        # Check for ASP errors
        if ($response.Content -match "Microsoft VBScript|Error 500|ADODB\.") {
            $passed = $false
            Write-TestResult -TestName $TestName -Passed $false -Message "Page contains error text"
            return $false
        }

        Write-TestResult -TestName $TestName -Passed $passed -Message "Status: $($response.StatusCode)"
        return $passed
    }
    catch {
        Write-TestResult -TestName $TestName -Passed $false -Message $_.Exception.Message
        return $false
    }
}

function Test-FormSubmission {
    param(
        [string]$Url,
        [string]$TestName,
        [hashtable]$FormData,
        [string]$ExpectedRedirect = "",
        [string]$ExpectedContent = "",
        [string]$RecordType = "",
        [string]$RecordIdentifier = ""
    )

    try {
        $response = Invoke-WebRequest -Uri $Url -Method POST -Body $FormData -UseBasicParsing -TimeoutSec 30 -MaximumRedirection 0 -ErrorAction SilentlyContinue

        $passed = $true
        $message = "Status: $($response.StatusCode)"

        # Check for redirect (302) which usually means success
        if ($response.StatusCode -eq 302) {
            $message = "Redirected to: $($response.Headers.Location)"
            if ($ExpectedRedirect -and $response.Headers.Location -notmatch $ExpectedRedirect) {
                $passed = $false
            }
            # Track created record for cleanup
            if ($RecordType -and $RecordIdentifier) {
                $script:CreatedRecords[$RecordType] += $RecordIdentifier
            }
        }
        elseif ($response.StatusCode -eq 200) {
            if ($ExpectedContent -and $response.Content -notmatch $ExpectedContent) {
                $passed = $false
            }
            if ($response.Content -match "Microsoft VBScript|Error 500|ADODB\.") {
                $passed = $false
                $message = "Response contains ASP error"
            }
        }
        else {
            $passed = $false
        }

        Write-TestResult -TestName $TestName -Passed $passed -Message $message
        return $passed
    }
    catch {
        # 302 redirects throw exceptions with -MaximumRedirection 0
        if ($_.Exception.Response.StatusCode -eq 302 -or $_.Exception.Message -match "302") {
            if ($RecordType -and $RecordIdentifier) {
                $script:CreatedRecords[$RecordType] += $RecordIdentifier
            }
            Write-TestResult -TestName $TestName -Passed $true -Message "Redirected (success)"
            return $true
        }
        Write-TestResult -TestName $TestName -Passed $false -Message $_.Exception.Message
        return $false
    }
}

function Get-ExistingId {
    param(
        [string]$PageUrl,
        [string]$Pattern
    )
    try {
        $page = Invoke-WebRequest -Uri $PageUrl -UseBasicParsing -TimeoutSec 30
        if ($page.Content -match $Pattern) {
            return $Matches[1]
        }
    }
    catch {}
    return $null
}

# ============================================================================
# START TESTS
# ============================================================================

if (-not $CleanupOnly) {

Write-Host ""
Write-Host "============================================" -ForegroundColor Cyan
Write-Host "ShopDB Comprehensive Form Testing" -ForegroundColor Cyan
Write-Host "Started: $(Get-Date)" -ForegroundColor Cyan
Write-Host "Base URL: $BaseUrl" -ForegroundColor Cyan
Write-Host "Test Prefix: $TestPrefix" -ForegroundColor Cyan
Write-Host "============================================" -ForegroundColor Cyan
Write-Host ""

# ----------------------------------------------------------------------------
# 1. PAGE LOAD TESTS
# ----------------------------------------------------------------------------
Write-Host "--- PAGE LOAD TESTS ---" -ForegroundColor Yellow

Test-PageLoads -Url "$BaseUrl/default.asp" -TestName "Dashboard loads"
Test-PageLoads -Url "$BaseUrl/displaynotifications.asp" -TestName "Notifications list loads"
Test-PageLoads -Url "$BaseUrl/displayapplications.asp" -TestName "Applications list loads"
Test-PageLoads -Url "$BaseUrl/displayprinters.asp" -TestName "Printers list loads"
Test-PageLoads -Url "$BaseUrl/displaypcs.asp" -TestName "PCs list loads"
Test-PageLoads -Url "$BaseUrl/displaymachines.asp" -TestName "Equipment list loads"
Test-PageLoads -Url "$BaseUrl/network_devices.asp" -TestName "Network devices loads"
Test-PageLoads -Url "$BaseUrl/displaysubnets.asp" -TestName "Subnets list loads"
Test-PageLoads -Url "$BaseUrl/displayknowledgebase.asp" -TestName "Knowledge base loads"
Test-PageLoads -Url "$BaseUrl/machinemap.asp" -TestName "Machine map loads"
Test-PageLoads -Url "$BaseUrl/printermap.asp" -TestName "Printer map loads"

Write-Host ""

# ----------------------------------------------------------------------------
# 2. ADD FORM PAGE LOAD TESTS
# ----------------------------------------------------------------------------
Write-Host "--- ADD FORM PAGE LOAD TESTS ---" -ForegroundColor Yellow

Test-PageLoads -Url "$BaseUrl/addnotification.asp" -TestName "Add notification form loads"
Test-PageLoads -Url "$BaseUrl/addmachine.asp" -TestName "Add equipment form loads"
Test-PageLoads -Url "$BaseUrl/addprinter.asp" -TestName "Add printer form loads"
Test-PageLoads -Url "$BaseUrl/addsubnet.asp" -TestName "Add subnet form loads"
Test-PageLoads -Url "$BaseUrl/addapplication.asp" -TestName "Add application form loads"
Test-PageLoads -Url "$BaseUrl/addknowledgebase.asp" -TestName "Add KB article form loads"
Test-PageLoads -Url "$BaseUrl/addvendor.asp" -TestName "Add vendor form loads"
Test-PageLoads -Url "$BaseUrl/addmodel.asp" -TestName "Add model form loads"
Test-PageLoads -Url "$BaseUrl/deviceaccesspoint.asp" -TestName "Add access point form loads"
Test-PageLoads -Url "$BaseUrl/deviceswitch.asp" -TestName "Add switch form loads"
Test-PageLoads -Url "$BaseUrl/devicecamera.asp" -TestName "Add camera form loads"
Test-PageLoads -Url "$BaseUrl/deviceidf.asp" -TestName "Add IDF form loads"
Test-PageLoads -Url "$BaseUrl/deviceserver.asp" -TestName "Add server form loads"

Write-Host ""

# ----------------------------------------------------------------------------
# 3. NOTIFICATION FORM TESTS
# ----------------------------------------------------------------------------
Write-Host "--- NOTIFICATION FORM TESTS ---" -ForegroundColor Yellow

$notificationData = @{
    notification = "$TestPrefix - Test notification basic"
    notificationtypeid = "2"
    businessunitid = ""
    appid = ""
    ticketnumber = "GETEST123456"
    starttime = (Get-Date).ToString("yyyy-MM-ddTHH:mm")
    endtime = (Get-Date).AddDays(1).ToString("yyyy-MM-ddTHH:mm")
    isactive = "1"
    isshopfloor = "0"
}
Test-FormSubmission -Url "$BaseUrl/savenotificationdirect.asp" -TestName "Create notification (basic)" -FormData $notificationData -ExpectedRedirect "displaynotifications" -RecordType "Notifications" -RecordIdentifier "$TestPrefix - Test notification basic"

$notificationWithApp = @{
    notification = "$TestPrefix - Test notification with app"
    notificationtypeid = "3"
    businessunitid = ""
    appid = "6"
    ticketnumber = "GECHG123456"
    starttime = (Get-Date).ToString("yyyy-MM-ddTHH:mm")
    endtime = (Get-Date).AddHours(4).ToString("yyyy-MM-ddTHH:mm")
    isactive = "1"
    isshopfloor = "1"
}
Test-FormSubmission -Url "$BaseUrl/savenotificationdirect.asp" -TestName "Create notification (with app)" -FormData $notificationWithApp -ExpectedRedirect "displaynotifications" -RecordType "Notifications" -RecordIdentifier "$TestPrefix - Test notification with app"

Write-Host ""

# ----------------------------------------------------------------------------
# 4. EQUIPMENT (MACHINE) FORM TESTS
# ----------------------------------------------------------------------------
Write-Host "--- EQUIPMENT FORM TESTS ---" -ForegroundColor Yellow

$equipmentData = @{
    machinenumber = "$TestPrefix-EQ001"
    modelid = "1"
    businessunitid = "1"
    alias = "Test Equipment Alias"
    machinenotes = "Created by automated test script"
    ip1 = "192.168.99.101"
    mac1 = "00:11:22:33:44:55"
    ip2 = ""
    mac2 = ""
    ip3 = ""
    mac3 = ""
    controllingpc = ""
    dualpathid = ""
    thirdpartymanaged = "0"
    mapleft = ""
    maptop = ""
}
Test-FormSubmission -Url "$BaseUrl/savemachinedirect.asp" -TestName "Create equipment" -FormData $equipmentData -ExpectedRedirect "displaymachines|editmachine" -RecordType "Machines" -RecordIdentifier "$TestPrefix-EQ001"

Write-Host ""

# ----------------------------------------------------------------------------
# 5. PRINTER FORM TESTS
# ----------------------------------------------------------------------------
Write-Host "--- PRINTER FORM TESTS ---" -ForegroundColor Yellow

$printerData = @{
    printercsfname = "$TestPrefix-PRN001"
    printerwindowsname = "TestPrinter001"
    modelid = "1"
    serialnumber = "TESTPRN123456"
    ipaddress = "192.168.99.201"
    fqdn = "testprinter001.test.local"
    machineid = ""
    mapleft = ""
    maptop = ""
}
Test-FormSubmission -Url "$BaseUrl/saveprinterdirect.asp" -TestName "Create printer" -FormData $printerData -ExpectedRedirect "displayprinters|editprinter" -RecordType "Printers" -RecordIdentifier "$TestPrefix-PRN001"

Write-Host ""

# ----------------------------------------------------------------------------
# 6. SUBNET FORM TESTS
# ----------------------------------------------------------------------------
Write-Host "--- SUBNET FORM TESTS ---" -ForegroundColor Yellow

$subnetData = @{
    ipstart = "192.168.99.0"
    cidr = "24"
    vlan = "999"
    subnettypeid = "1"
    description = "$TestPrefix - Test subnet"
}
Test-FormSubmission -Url "$BaseUrl/addsubnetbackenddirect.asp" -TestName "Create subnet" -FormData $subnetData -ExpectedRedirect "displaysubnets" -RecordType "Subnets" -RecordIdentifier "192.168.99.0"

Write-Host ""

# ----------------------------------------------------------------------------
# 7. APPLICATION FORM TESTS
# ----------------------------------------------------------------------------
Write-Host "--- APPLICATION FORM TESTS ---" -ForegroundColor Yellow

$applicationData = @{
    applicationname = "$TestPrefix-App001"
    appdescription = "Test application created by automated test"
    supportteamid = "1"
    appownerid = ""
    skilllevelid = ""
}
Test-FormSubmission -Url "$BaseUrl/saveapplicationdirect.asp" -TestName "Create application" -FormData $applicationData -ExpectedRedirect "displayapplications|displayapplication" -RecordType "Applications" -RecordIdentifier "$TestPrefix-App001"

Write-Host ""

# ----------------------------------------------------------------------------
# 8. KNOWLEDGE BASE FORM TESTS
# ----------------------------------------------------------------------------
Write-Host "--- KNOWLEDGE BASE FORM TESTS ---" -ForegroundColor Yellow

$kbData = @{
    shortdescription = "$TestPrefix - Test KB Article"
    applicationid = "1"
    keywords = "test automated testing"
    linkurl = "https://example.com/test"
    topicid = "1"
}
Test-FormSubmission -Url "$BaseUrl/addlinkdirect.asp" -TestName "Create KB article" -FormData $kbData -ExpectedRedirect "displayknowledgebase|displayknowledgearticle" -RecordType "KBArticles" -RecordIdentifier "$TestPrefix - Test KB Article"

Write-Host ""

# ----------------------------------------------------------------------------
# 9. VENDOR FORM TESTS
# ----------------------------------------------------------------------------
Write-Host "--- VENDOR FORM TESTS ---" -ForegroundColor Yellow

$vendorData = @{
    vendor = "$TestPrefix-Vendor001"
}
Test-FormSubmission -Url "$BaseUrl/savevendordirect.asp" -TestName "Create vendor" -FormData $vendorData -ExpectedRedirect "addmodel|displayvendors" -RecordType "Vendors" -RecordIdentifier "$TestPrefix-Vendor001"

Write-Host ""

# ----------------------------------------------------------------------------
# 10. MODEL FORM TESTS
# ----------------------------------------------------------------------------
Write-Host "--- MODEL FORM TESTS ---" -ForegroundColor Yellow

$modelData = @{
    modelnumber = "$TestPrefix-Model001"
    vendorid = "1"
    machinetypeid = "1"
    notes = "Test model created by automated test"
}
Test-FormSubmission -Url "$BaseUrl/savemodeldirect.asp" -TestName "Create model" -FormData $modelData -ExpectedRedirect "addmachine|displaymodels" -RecordType "Models" -RecordIdentifier "$TestPrefix-Model001"

Write-Host ""

# ----------------------------------------------------------------------------
# 11. NETWORK DEVICE FORM TESTS
# ----------------------------------------------------------------------------
Write-Host "--- NETWORK DEVICE FORM TESTS ---" -ForegroundColor Yellow

# Access Point
$apData = @{
    type = "new"
    apname = "$TestPrefix-AP001"
    serialnumber = "TESTAP123456"
    ipaddress = "192.168.99.50"
    fqdn = "testap001.test.local"
    modelid = ""
    description = "Test access point"
    isactive = "1"
    mapleft = ""
    maptop = ""
}
Test-FormSubmission -Url "$BaseUrl/deviceaccesspoint.asp" -TestName "Create access point" -FormData $apData -ExpectedRedirect "network_devices|deviceaccesspoint" -RecordType "NetworkDevices" -RecordIdentifier "$TestPrefix-AP001"

# Switch
$switchData = @{
    type = "new"
    alias = "$TestPrefix-SW001"
    serialnumber = "TESTSW123456"
    ipaddress = "192.168.99.51"
    fqdn = "testsw001.test.local"
    modelid = ""
    machinenotes = "Test switch"
    isactive = "1"
    mapleft = ""
    maptop = ""
}
Test-FormSubmission -Url "$BaseUrl/deviceswitch.asp" -TestName "Create switch" -FormData $switchData -ExpectedRedirect "network_devices|deviceswitch" -RecordType "NetworkDevices" -RecordIdentifier "$TestPrefix-SW001"

# Camera
$cameraData = @{
    type = "new"
    alias = "$TestPrefix-CAM001"
    serialnumber = "TESTCAM123456"
    ipaddress = "192.168.99.52"
    fqdn = "testcam001.test.local"
    modelid = ""
    machinenotes = "Test camera"
    isactive = "1"
    mapleft = ""
    maptop = ""
}
Test-FormSubmission -Url "$BaseUrl/devicecamera.asp" -TestName "Create camera" -FormData $cameraData -ExpectedRedirect "network_devices|devicecamera" -RecordType "NetworkDevices" -RecordIdentifier "$TestPrefix-CAM001"

# IDF
$idfData = @{
    type = "new"
    alias = "$TestPrefix-IDF001"
    serialnumber = "TESTIDF123456"
    ipaddress = "192.168.99.53"
    fqdn = "testidf001.test.local"
    modelid = ""
    machinenotes = "Test IDF"
    isactive = "1"
    mapleft = ""
    maptop = ""
}
Test-FormSubmission -Url "$BaseUrl/deviceidf.asp" -TestName "Create IDF" -FormData $idfData -ExpectedRedirect "network_devices|deviceidf" -RecordType "NetworkDevices" -RecordIdentifier "$TestPrefix-IDF001"

# Server
$serverData = @{
    type = "new"
    alias = "$TestPrefix-SRV001"
    serialnumber = "TESTSRV123456"
    fqdn = "testsrv001.test.local"
    modelid = ""
    machinenotes = "Test server"
    isactive = "1"
    mapleft = ""
    maptop = ""
}
Test-FormSubmission -Url "$BaseUrl/deviceserver.asp" -TestName "Create server" -FormData $serverData -ExpectedRedirect "network_devices|deviceserver" -RecordType "NetworkDevices" -RecordIdentifier "$TestPrefix-SRV001"

Write-Host ""

# ----------------------------------------------------------------------------
# 12. EDIT FORM TESTS
# ----------------------------------------------------------------------------
Write-Host "--- EDIT FORM TESTS ---" -ForegroundColor Yellow

# Test editing a notification
$testNotifId = Get-ExistingId -PageUrl "$BaseUrl/displaynotifications.asp" -Pattern 'editnotification\.asp\?notificationid=(\d+)'
if ($testNotifId) {
    Test-PageLoads -Url "$BaseUrl/editnotification.asp?notificationid=$testNotifId" -TestName "Edit notification form loads"
} else {
    Write-TestResult -TestName "Edit notification form loads" -Passed $false -Message "No notifications found"
}

# Test editing equipment
$testMachineId = Get-ExistingId -PageUrl "$BaseUrl/displaymachines.asp" -Pattern 'editmachine\.asp\?machineid=(\d+)'
if ($testMachineId) {
    Test-PageLoads -Url "$BaseUrl/editmachine.asp?machineid=$testMachineId" -TestName "Edit equipment form loads"
} else {
    Write-TestResult -TestName "Edit equipment form loads" -Passed $false -Message "No equipment found"
}

# Test editing PC
$testPCId = Get-ExistingId -PageUrl "$BaseUrl/displaypcs.asp" -Pattern 'editpc\.asp\?machineid=(\d+)'
if ($testPCId) {
    Test-PageLoads -Url "$BaseUrl/editpc.asp?machineid=$testPCId" -TestName "Edit PC form loads"
} else {
    Write-TestResult -TestName "Edit PC form loads" -Passed $false -Message "No PCs found"
}

# Test editing printer
$testPrinterId = Get-ExistingId -PageUrl "$BaseUrl/displayprinters.asp" -Pattern 'editprinter\.asp\?printerid=(\d+)'
if ($testPrinterId) {
    Test-PageLoads -Url "$BaseUrl/editprinter.asp?printerid=$testPrinterId" -TestName "Edit printer form loads"
} else {
    Write-TestResult -TestName "Edit printer form loads" -Passed $false -Message "No printers found"
}

# Test editing KB article
$testLinkId = Get-ExistingId -PageUrl "$BaseUrl/displayknowledgebase.asp" -Pattern 'editlink\.asp\?linkid=(\d+)'
if ($testLinkId) {
    Test-PageLoads -Url "$BaseUrl/editlink.asp?linkid=$testLinkId" -TestName "Edit KB article form loads"
} else {
    Write-TestResult -TestName "Edit KB article form loads" -Passed $false -Message "No KB articles found"
}

Write-Host ""

# ----------------------------------------------------------------------------
# 13. API ENDPOINT TESTS
# ----------------------------------------------------------------------------
Write-Host "--- API ENDPOINT TESTS ---" -ForegroundColor Yellow

Test-PageLoads -Url "$BaseUrl/api.asp?action=getDashboardData" -TestName "API getDashboardData" -ExpectedContent "success"
Test-PageLoads -Url "$BaseUrl/api.asp?action=getShopfloorPCs" -TestName "API getShopfloorPCs" -ExpectedContent "success"
Test-PageLoads -Url "$BaseUrl/apiprinters.asp" -TestName "API printers" -ExpectedContent "printerid"
Test-PageLoads -Url "$BaseUrl/apibusinessunits.asp" -TestName "API business units" -ExpectedContent "businessunit"

# Test API POST
$apiTestData = @{
    action = "updateCompleteAsset"
    hostname = "$TestPrefix-PC001"
    serialNumber = "TESTSERIAL123"
    model = "Test Model"
    manufacturer = "Dell"
    osVersion = "Windows 11 Pro"
    pcType = "Standard"
}
Test-FormSubmission -Url "$BaseUrl/api.asp" -TestName "API updateCompleteAsset" -FormData $apiTestData -ExpectedContent "success"

Write-Host ""

# ----------------------------------------------------------------------------
# 14. VALIDATION TESTS
# ----------------------------------------------------------------------------
Write-Host "--- VALIDATION TESTS ---" -ForegroundColor Yellow

# Test missing required fields on notification
$invalidNotification = @{
    notification = ""
    notificationtypeid = "1"
    starttime = ""
}
try {
    $response = Invoke-WebRequest -Uri "$BaseUrl/savenotificationdirect.asp" -Method POST -Body $invalidNotification -UseBasicParsing -MaximumRedirection 0 -ErrorAction SilentlyContinue
    $passed = $response.Content -match "Required|missing|error" -or $response.StatusCode -ne 302
    Write-TestResult -TestName "Reject empty notification" -Passed $passed -Message "Handled gracefully"
}
catch {
    if ($_.Exception.Message -match "302") {
        Write-TestResult -TestName "Reject empty notification" -Passed $false -Message "Should not redirect with missing fields"
    } else {
        Write-TestResult -TestName "Reject empty notification" -Passed $true -Message "Validation working"
    }
}

Write-Host ""

} # End if not CleanupOnly

# ============================================================================
# CLEANUP
# ============================================================================

if (-not $SkipCleanup) {
    Write-Host "--- CLEANUP ---" -ForegroundColor Yellow
    Write-Host "Cleaning up test records with prefix: $TestPrefix" -ForegroundColor Gray
    Write-Host ""
    Write-Host "NOTE: Cleanup requires direct database access." -ForegroundColor Magenta
    Write-Host "Run the following SQL to clean up test data:" -ForegroundColor Magenta
    Write-Host ""
    Write-Host "-- Cleanup SQL for test run: $TestPrefix" -ForegroundColor DarkGray
    Write-Host "DELETE FROM notifications WHERE notification LIKE '$TestPrefix%';" -ForegroundColor DarkGray
    Write-Host "DELETE FROM machines WHERE machinenumber LIKE '$TestPrefix%' OR alias LIKE '$TestPrefix%';" -ForegroundColor DarkGray
    Write-Host "DELETE FROM printers WHERE printercsfname LIKE '$TestPrefix%';" -ForegroundColor DarkGray
    Write-Host "DELETE FROM subnets WHERE description LIKE '$TestPrefix%';" -ForegroundColor DarkGray
    Write-Host "DELETE FROM applications WHERE applicationname LIKE '$TestPrefix%';" -ForegroundColor DarkGray
    Write-Host "DELETE FROM knowledgebase WHERE shortdescription LIKE '$TestPrefix%';" -ForegroundColor DarkGray
    Write-Host "DELETE FROM vendors WHERE vendor LIKE '$TestPrefix%';" -ForegroundColor DarkGray
    Write-Host "DELETE FROM models WHERE modelnumber LIKE '$TestPrefix%';" -ForegroundColor DarkGray
    Write-Host ""
}

# ============================================================================
# SUMMARY
# ============================================================================

if (-not $CleanupOnly) {

Write-Host "============================================" -ForegroundColor Cyan
Write-Host "TEST SUMMARY" -ForegroundColor Cyan
Write-Host "============================================" -ForegroundColor Cyan

$passed = ($TestResults | Where-Object { $_.Status -eq "PASS" }).Count
$failed = ($TestResults | Where-Object { $_.Status -eq "FAIL" }).Count
$total = $TestResults.Count

Write-Host ""
Write-Host "Total Tests: $total" -ForegroundColor White
Write-Host "Passed: $passed" -ForegroundColor Green
Write-Host "Failed: $failed" -ForegroundColor $(if ($failed -gt 0) { "Red" } else { "Green" })
Write-Host ""

if ($failed -gt 0) {
    Write-Host "FAILED TESTS:" -ForegroundColor Red
    $TestResults | Where-Object { $_.Status -eq "FAIL" } | ForEach-Object {
        Write-Host "  - $($_.Test): $($_.Message)" -ForegroundColor Red
    }
    Write-Host ""
}

# Export results to file
$resultsFile = "test_results_$TestTimestamp.csv"
$TestResults | Export-Csv -Path $resultsFile -NoTypeInformation
Write-Host "Results exported to: $resultsFile" -ForegroundColor Gray

Write-Host ""
Write-Host "Testing completed at $(Get-Date)" -ForegroundColor Cyan
Write-Host "Test prefix for cleanup: $TestPrefix" -ForegroundColor Yellow

}
