# Funktion zur Bereinigung beim Beenden
function OnExit {
    Write-Host "`n[DPS] Cleaning up..."
    if ($backendProcess -and !$backendProcess.HasExited) {
        $backendProcess.Kill()
    }
    if ($frontendProcess -and !$frontendProcess.HasExited) {
        $frontendProcess.Kill()
    }
    Write-Host "[DPS] Cleaned up..."

    # Einen Ordner höher gehen
    Set-Location (Resolve-Path "..").Path
    Write-Host "[DPS] Returned to parent directory: $(Get-Location)"

    exit
}

Write-Host "[DPS] trapped"

# Backend starten
Set-Location ./00-backend
$backendOutLog = "../backend_latest.out.log"
$backendErrLog = "../backend_latest.err.log"
$backendProcess = Start-Process "java" -ArgumentList "-jar", "target/webshop-0.0.1-SNAPSHOT.jar" `
    -RedirectStandardOutput $backendOutLog `
    -RedirectStandardError $backendErrLog `
    -NoNewWindow -PassThru
Write-Host "[DPS] Backend started with PID $($backendProcess.Id)"

# Frontend starten (ohne cmd.exe)
Set-Location ../01-frontend
$frontendOutLog = "../frontend_latest.out.log"
$frontendErrLog = "../frontend_latest.err.log"

$frontendProcess = Start-Process "node" `
    -ArgumentList "node_modules/.bin/react-scripts", "start" `
    -RedirectStandardOutput $frontendOutLog `
    -RedirectStandardError $frontendErrLog `
    -NoNewWindow -PassThru

Write-Host "[DPS] Frontend started with PID $($frontendProcess.Id)"

Write-Host "[DPS] Ctrl+C to stop"

Register-EngineEvent PowerShell.Exiting -Action { OnExit } -SupportEvent

try {
    while ($true) {
    Start-Sleep -Seconds 1
    if ($backendProcess.HasExited -and $frontendProcess.HasExited) {
        break
    }
}
}
catch {
    if ($_.Exception -is [System.Management.Automation.PipelineStoppedException]) {
        # This block will not execute on CTRL-C
    }
}
