$ErrorActionPreference = "Stop"

$root = Split-Path -Parent $PSScriptRoot
$publishDir = Join-Path $root "publish\DentalClinic"
$baseInstallDir = Join-Path $env:LOCALAPPDATA "DentalClinicApp"
$installDir = Join-Path $baseInstallDir ("app-" + (Get-Date -Format "yyyyMMddHHmmss"))
$exeName = "DentalClinic.Desktop.exe"
$sourceExe = Join-Path $publishDir $exeName
$installedExe = Join-Path $installDir $exeName

Write-Host ""
Write-Host "DentalPro Clinic ready installer" -ForegroundColor Cyan
Write-Host "================================" -ForegroundColor Cyan

Write-Host "Closing any running instances of DentalPro Clinic..."
Get-Process -Name "DentalClinic.Desktop" -ErrorAction SilentlyContinue | Stop-Process -Force -ErrorAction SilentlyContinue
Start-Sleep -Seconds 1

if (-not (Test-Path $sourceExe)) {
    Write-Host "ERROR: Published app was not found at $sourceExe" -ForegroundColor Red
    Write-Host "Run Setup-DentalClinic.bat once to create the published app, then try again."
    exit 1
}

Write-Host "Installing to $installDir"
New-Item -ItemType Directory -Force -Path $baseInstallDir | Out-Null
New-Item -ItemType Directory -Force -Path $installDir | Out-Null
Copy-Item -Path (Join-Path $publishDir "*") -Destination $installDir -Recurse -Force

Set-Content -Path (Join-Path $baseInstallDir "current.txt") -Value $installedExe -Encoding UTF8

$shell = New-Object -ComObject WScript.Shell
$desktopShortcut = Join-Path ([Environment]::GetFolderPath("Desktop")) "DentalPro Clinic.lnk"
$startMenuDir = Join-Path ([Environment]::GetFolderPath("StartMenu")) "Programs\DentalPro Clinic"
$startMenuShortcut = Join-Path $startMenuDir "DentalPro Clinic.lnk"
New-Item -ItemType Directory -Force -Path $startMenuDir | Out-Null

foreach ($shortcutPath in @($desktopShortcut, $startMenuShortcut)) {
    $shortcut = $shell.CreateShortcut($shortcutPath)
    $shortcut.TargetPath = $installedExe
    $shortcut.WorkingDirectory = $installDir
    $shortcut.Description = "DentalPro Clinic Management System"
    $shortcut.Save()
}

Write-Host "Setup completed successfully." -ForegroundColor Green
Write-Host "Starting DentalPro Clinic..."
Start-Process -FilePath $installedExe -WorkingDirectory $installDir
