# Restaurant ERP — Windows service installer (V1)
# Usage (PowerShell, as Administrator):
#   .\install-service.ps1 -InstallDir "C:\RestaurantERP" -DbUrl "postgres://erp:password@localhost:5432/restaurant_erp?sslmode=disable"
#
# Requires PostgreSQL 16 installed on the same machine (or reachable on the LAN).
# The app is a single self-contained exe; this script registers it as a
# Windows service that auto-starts and restarts on failure.

param(
    [string]$InstallDir = "C:\RestaurantERP",
    [string]$DbUrl = "",
    [string]$Port = "8080"
)

$ErrorActionPreference = "Stop"
$exe = Join-Path $InstallDir "restaurant-erp.exe"
$svcName = "RestaurantERP"

if (-not (Test-Path $exe)) {
    throw "Binary not found at $exe — copy bin/restaurant-erp.exe to $InstallDir first."
}
if (-not $DbUrl) {
    throw "Provide -DbUrl (ERP_DATABASE_URL) — e.g. postgres://erp:secret@localhost:5432/restaurant_erp?sslmode=disable"
}

# 1. Prepare folders (data / backups / logs) — created by the app too, but explicit here.
New-Item -ItemType Directory -Force -Path (Join-Path $InstallDir "data")    | Out-Null
New-Item -ItemType Directory -Force -Path (Join-Path $InstallDir "backups") | Out-Null
New-Item -ItemType Directory -Force -Path (Join-Path $InstallDir "logs")    | Out-Null

# 2. Register with sc.exe — runs as LocalSystem, auto-start, restart on failure.
& sc.exe create $svcName binPath= "\"`"$exe`"\"" start= auto DisplayName= "Restaurant ERP (LAN)"
if ($LASTEXITCODE -ne 0 -and $LASTEXITCODE -ne 1073) { throw "sc create failed: $LASTEXITCODE" }  # 1073 = already exists

& sc.exe description $svcName "Local-First restaurant ERP: POS, KDS, inventory, purchasing, reservations, reports. LAN-only; no cloud dependency."
& sc.exe failure $svcName reset= 86400 actions= restart/5000/restart/10000/restart/30000 | Out-Null

# 3. Persist service environment (no secrets in plain command line).
$reg = "HKLM:\SYSTEM\CurrentControlSet\Services\$svcName"
New-ItemProperty -Path $reg -Name "Environment" -PropertyType MultiString -Value @(
    "ERP_DATABASE_URL=$DbUrl",
    "ERP_ENV=production",
    "ERP_HTTP_ADDR=0.0.0.0:$Port",
    "ERP_DATA_DIR=$InstallDir\data",
    "ERP_BACKUP_DIR=$InstallDir\backups"
) -Force | Out-Null

# 4. Local firewall rule: allow inbound on the LAN for the ERP port.
& netsh advfirewall firewall delete rule name="Restaurant ERP $Port" | Out-Null
& netsh advfirewall firewall add rule name="Restaurant ERP $Port" dir=in action=allow protocol=TCP localport=$Port | Out-Null

# 5. Start it.
& sc.exe start $svcName | Out-Null
Start-Sleep -Seconds 3
& sc.exe query $svcName

Write-Host ""
Write-Host "Restaurant ERP service installed and started."
Write-Host "  URL : http://<this-machine-ip>:$Port"
Write-Host "  Stop : sc.exe stop $svcName   |   Start: sc.exe start $svcName"
Write-Host "  Logs : $InstallDir\logs  |  Backups: $InstallDir\backups"
Write-Host "Uninstall: .\uninstall-service.ps1 (keeps data/backups)"
