# Check for detailed SCP error messages in the log
$password = ConvertTo-SecureString "Paper123!@#" -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential("INTRANET\sysadmin", $password)

Invoke-Command -ComputerName 192.168.0.6 -Credential $cred -ScriptBlock {
    $logFile = "C:\Shares\test\scripts\sync-from-nas.log"

    Write-Host "=== Checking for SCP Error Details ===" -ForegroundColor Cyan
    Write-Host ""

    Write-Host "[1] Looking for 'SCP ERROR' messages in recent log" -ForegroundColor Yellow
    $scpErrors = Get-Content $logFile -Tail 200 | Select-String -Pattern "SCP ERROR"

    if ($scpErrors) {
        Write-Host "[FOUND] $($scpErrors.Count) detailed SCP error(s):" -ForegroundColor Green
        Write-Host "=" * 80 -ForegroundColor Gray
        $scpErrors | ForEach-Object {
            Write-Host $_ -ForegroundColor Red
        }
    } else {
        Write-Host "[NOT FOUND] No 'SCP ERROR' messages in recent log" -ForegroundColor Yellow
    }

    Write-Host ""
    Write-Host "[2] Checking for generic ERROR messages" -ForegroundColor Yellow
    $genericErrors = Get-Content $logFile -Tail 100 | Select-String -Pattern "^\s*\d{4}-\d{2}-\d{2}.*ERROR: Failed to" | Select-Object -First 5

    if ($genericErrors) {
        Write-Host "[FOUND] Generic error messages (without details):" -ForegroundColor Yellow
        Write-Host "=" * 80 -ForegroundColor Gray
        $genericErrors | ForEach-Object {
            Write-Host $_ -ForegroundColor Red
        }
    }

    Write-Host ""
    Write-Host "[3] Checking Copy-ToNAS function in script" -ForegroundColor Yellow
    $scriptContent = Get-Content "C:\Shares\test\scripts\Sync-FromNAS.ps1" -Raw

    if ($scriptContent -match 'function Copy-ToNAS') {
        Write-Host "[INFO] Looking at Copy-ToNAS function..." -ForegroundColor Cyan

        $lines = Get-Content "C:\Shares\test\scripts\Sync-FromNAS.ps1"
        $inFunction = $false
        $lineNum = 0

        foreach ($line in $lines) {
            $lineNum++
            if ($line -match 'function Copy-ToNAS') {
                $inFunction = $true
            }
            if ($inFunction) {
                Write-Host "Line $lineNum : $line" -ForegroundColor Gray
                if ($line -match '^\}' -and $inFunction) {
                    break
                }
            }
        }
    }
}
