# Test error logging by attempting a known-failing file push
$password = ConvertTo-SecureString "Paper123!@#" -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential("INTRANET\sysadmin", $password)

Write-Host "=== Testing Error Logging ===" -ForegroundColor Cyan
Write-Host ""

Invoke-Command -ComputerName 192.168.0.6 -Credential $cred -ScriptBlock {
    Write-Host "[1] Loading sync script to test Copy-ToNAS" -ForegroundColor Yellow

    # Dot-source the sync script to load functions
    . "C:\Shares\test\scripts\Sync-FromNAS.ps1"

    Write-Host "[2] Attempting to push a file that will fail" -ForegroundColor Yellow
    Write-Host "    (lowercase .dat file in HVDATA subdirectory)" -ForegroundColor Gray
    Write-Host ""

    # Try pushing one of the known-failing files
    $testFile = "C:\Shares\test\TS-1L\ProdSW\HVDATA\hvin.dat"

    if (Test-Path $testFile) {
        Write-Host "[OK] Test file exists: $testFile" -ForegroundColor Green
        Write-Host "[TESTING] Calling Copy-ToNAS..." -ForegroundColor Cyan

        # Call Copy-ToNAS directly
        $result = Copy-ToNAS -LocalPath $testFile -RemotePath "/data/test/TS-1L/ProdSW/HVDATA/hvin.dat"

        Write-Host ""
        if ($result) {
            Write-Host "[UNEXPECTED] File pushed successfully!" -ForegroundColor Yellow
        } else {
            Write-Host "[EXPECTED] File push failed" -ForegroundColor Green
        }

        Write-Host ""
        Write-Host "[3] Checking log for detailed error" -ForegroundColor Yellow
        Write-Host "=" * 80 -ForegroundColor Gray

        $recentLog = Get-Content "C:\Shares\test\scripts\sync-from-nas.log" -Tail 5

        $scpError = $recentLog | Where-Object { $_ -match "SCP PUSH ERROR" }

        if ($scpError) {
            Write-Host "[SUCCESS] Detailed error logged!" -ForegroundColor Green
            Write-Host ""
            $scpError | ForEach-Object {
                Write-Host $_ -ForegroundColor Red
            }
        } else {
            Write-Host "[FAIL] No detailed SCP error found in recent log" -ForegroundColor Red
            Write-Host ""
            Write-Host "Recent log entries:" -ForegroundColor Yellow
            $recentLog | ForEach-Object {
                Write-Host "  $_" -ForegroundColor Gray
            }
        }
    } else {
        Write-Host "[ERROR] Test file not found: $testFile" -ForegroundColor Red
    }
}

Write-Host ""
Write-Host "=== Test Complete ===" -ForegroundColor Cyan
