<#
.SYNOPSIS
    Startet den Krisenvorrat Dev-Server im LAN.
.DESCRIPTION
    Baut das Fat-JAR (falls nötig) und startet den Server auf Port 8080.
    Der Server ist unter der LAN-IP des Rechners erreichbar.
.PARAMETER Build
    Erzwingt einen Neubau des Fat-JARs, auch wenn es bereits existiert.
.PARAMETER ApiKey
    Setzt einen benutzerdefinierten API-Key. Standard: "dev-api-key-change-in-production"
.EXAMPLE
    .\start-server.ps1
    .\start-server.ps1 -Build
    .\start-server.ps1 -ApiKey "mein-geheimer-key"
#>
param(
    [switch]$Build,
    [string]$ApiKey = "dev-api-key-change-in-production"
)

$ErrorActionPreference = "Stop"
Set-Location $PSScriptRoot

$jarPath = "server/build/libs/server.jar"

# Fat-JAR bauen falls nötig
if ($Build -or -not (Test-Path $jarPath)) {
    Write-Host "Building server fat JAR..." -ForegroundColor Cyan
    & .\gradlew.bat :server:buildFatJar 2>&1 | Out-String | Write-Host
    if ($LASTEXITCODE -ne 0) {
        Write-Error "Build failed with exit code $LASTEXITCODE"
        exit 1
    }
    Write-Host "Build successful." -ForegroundColor Green
}

# LAN-IP ermitteln
$lanIp = (Get-NetIPAddress -AddressFamily IPv4 |
    Where-Object { $_.InterfaceAlias -notmatch "Loopback" -and $_.IPAddress -notmatch "^169\." } |
    Select-Object -First 1).IPAddress

Write-Host ""
Write-Host "=== Krisenvorrat Dev-Server ===" -ForegroundColor Green
Write-Host "Local:  http://localhost:8080" -ForegroundColor Yellow
if ($lanIp) {
    Write-Host "LAN:    http://${lanIp}:8080" -ForegroundColor Yellow
}
Write-Host "API-Key: $ApiKey" -ForegroundColor Yellow
Write-Host "Press Ctrl+C to stop" -ForegroundColor Gray
Write-Host ""

# Server starten
$env:KRISENVORRAT_API_KEY = $ApiKey
java -jar $jarPath
