param(
    [string]$DumpFile = "$PSScriptRoot\aufmassweb_export.dump",
    [string]$PgBin = "C:\Program Files\PostgreSQL\16\bin",
    [string]$DbHost = "localhost",
    [string]$DbPort = "5432",
    [string]$DbUser = "aufmass",
    [string]$DbName = "aufmassweb"
)

$pg_dump = Join-Path $PgBin "pg_dump.exe"
if (-not (Test-Path $pg_dump)) {
    Write-Error "pg_dump nicht gefunden unter: $pg_dump"
    exit 1
}

Write-Host "=== AufmaßWeb – Datenexport vom Laptop ===" -ForegroundColor Cyan
Write-Host "Ziel:   $DumpFile"
Write-Host "DB:     $DbHost:$DbPort/$DbName"
Write-Host "User:   $DbUser"
Write-Host ""

$env:PGPASSWORD = Read-Host "Passwort für PostgreSQL-User '$DbUser'" -AsSecureString
$BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($env:PGPASSWORD)
$env:PGPASSWORD = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)

Write-Host "Exportiere Datenbank (custom-format) ..."
& $pg_dump -h $DbHost -p $DbPort -U $DbUser -d $DbName -F c -f $DumpFile --verbose

if ($LASTEXITCODE -eq 0) {
    $size = (Get-Item $DumpFile).Length / 1MB
    Write-Host "Export erfolgreich: $DumpFile ({0:N1} MB)" -f $size -ForegroundColor Green
    Write-Host "Übertrage die Datei auf den Ziel-PC und führe dort import_from_dump.ps1 aus." -ForegroundColor Yellow
} else {
    Write-Error "Export fehlgeschlagen (Exit-Code: $LASTEXITCODE)"
    Remove-Variable PGPASSWORD -ErrorAction SilentlyContinue
    exit 1
}

Remove-Variable PGPASSWORD -ErrorAction SilentlyContinue
