# QBooking Print Client installer (zip flow — the setup.exe built by NSIS is the
# preferred distribution; this script is the scriptable equivalent).
# Run from the unzipped package folder:
#   Right-click install.bat -> Run as administrator
# or from an elevated PowerShell:
#   powershell -ExecutionPolicy Bypass -File .\install.ps1 -ApiUrl "https://api.qbooking.ai"
param(
  [string]$ApiUrl = ""
)

$ErrorActionPreference = "Stop"
$src = $PSScriptRoot
$dest = Join-Path $env:ProgramFiles "QBooking\PrintClient"

# Self-elevate if not running as admin.
$isAdmin = ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
if (-not $isAdmin) {
  Write-Output "Requesting administrator privileges..."
  $args = "-NoProfile -ExecutionPolicy Bypass -File `"$PSCommandPath`""
  if ($ApiUrl) { $args += " -ApiUrl `"$ApiUrl`"" }
  Start-Process powershell.exe -Verb RunAs -ArgumentList $args -Wait
  exit
}

if (-not $ApiUrl) {
  $ApiUrl = Read-Host "QBooking API base URL (e.g. https://api.qbooking.ai)"
}
if (-not $ApiUrl) {
  Write-Error "An API URL is required."
}

# Stop a running client before overwriting the exe.
Get-Process -Name "qbooking-print-client" -ErrorAction SilentlyContinue | Stop-Process -Force -ErrorAction SilentlyContinue
Start-Sleep -Seconds 1

New-Item -ItemType Directory -Force -Path $dest | Out-Null
Copy-Item -Path (Join-Path $src "*") -Destination $dest -Recurse -Force
Write-Output "Installed to $dest"

& (Join-Path $dest "configure.ps1") -ApiUrl $ApiUrl -InstallDir $dest
