# pharma-sync — instalação no Windows Server
# Uso: Abrir PowerShell como Administrador, cd C:\pharma_sync, .\install-service.ps1

$ErrorActionPreference = "Stop"

Write-Host "=== pharma-sync installer ===" -ForegroundColor Cyan

# 1. Verifica admin
$principal = [Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()
if (-not $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
    Write-Host "ERRO: Execute este script como Administrador." -ForegroundColor Red
    exit 1
}

$InstallDir = "C:\pharma_sync"
if (-not (Test-Path $InstallDir)) {
    Write-Host "Criando $InstallDir..." -ForegroundColor Yellow
    New-Item -ItemType Directory -Path $InstallDir | Out-Null
}

# 2. Copia arquivos
Copy-Item "$PSScriptRoot\pharma-sync.exe" "$InstallDir\" -Force
if (Test-Path "$PSScriptRoot\config.example.toml") {
    Copy-Item "$PSScriptRoot\config.example.toml" "$InstallDir\" -Force
}

# 3. Autodiscover
Write-Host "`nDetectando FarmaFácil..." -ForegroundColor Cyan
Push-Location $InstallDir
& .\pharma-sync.exe autodiscover
Pop-Location

Write-Host "`n=== Próximos passos ===" -ForegroundColor Green
Write-Host "1. Edite C:\pharma_sync\config.toml com a senha do PostgreSQL e o token da farmácia"
Write-Host "2. Teste com:  cd C:\pharma_sync; .\pharma-sync.exe --once"
Write-Host "3. Instale serviço:  .\pharma-sync.exe install-service"
Write-Host "4. Inicie:  Start-Service pharma-sync"
Write-Host "5. Verifique:  Get-Service pharma-sync"
