param(
  [Parameter(Mandatory=$true)][string]$ServerURL,
  [Parameter(Mandatory=$true)][string]$CNPJ,
  [Parameter(Mandatory=$true)][string]$EnrollmentCode,
  [string]$SourceExecutable = "$PSScriptRoot\ProsperoConnector.exe",
  [string]$InstallDirectory = 'C:\Prospero\Connector',
  [string]$LocalAPIURL = 'http://127.0.0.1:3001',
  [switch]$AllowInsecureHTTP
)

$ErrorActionPreference = 'Stop'
$identity = [Security.Principal.WindowsIdentity]::GetCurrent()
$principal = New-Object Security.Principal.WindowsPrincipal($identity)
if (-not $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
  throw 'Execute este instalador como Administrador.'
}
if (-not (Test-Path -LiteralPath $SourceExecutable)) {
  throw "Executável não encontrado: $SourceExecutable"
}
$digits = $CNPJ -replace '\D',''
if ($digits.Length -ne 14) { throw 'Informe um CNPJ com 14 dígitos.' }
if ($ServerURL -notmatch '^https://' -and -not $AllowInsecureHTTP) {
  throw 'O servidor final precisa usar HTTPS. Use AllowInsecureHTTP somente em homologação.'
}

New-Item -ItemType Directory -Path $InstallDirectory -Force | Out-Null
$target = Join-Path $InstallDirectory 'ProsperoConnector.exe'
$ini = Join-Path $InstallDirectory 'ProsperoConnector.ini'
Copy-Item -LiteralPath $SourceExecutable -Destination $target -Force
$section = "Connector_$digits"
$content = @"
[$section]
Ativo=1
Servidor=$($ServerURL.TrimEnd('/'))
CNPJ=$digits
CodigoVinculacao=$($EnrollmentCode.Trim().ToUpperInvariant())
ConnectorID=
ConnectorSecretEnc=
APILocal=$($LocalAPIURL.TrimEnd('/'))
IntervaloConsultaMS=3000
PermitirHTTPInseguro=$(if ($AllowInsecureHTTP) { '1' } else { '0' })
"@
Set-Content -LiteralPath $ini -Value $content -Encoding UTF8

$serviceName = 'ProsperoConnector'
$existing = Get-Service -Name $serviceName -ErrorAction SilentlyContinue
if ($existing) {
  if ($existing.Status -ne 'Stopped') {
    Stop-Service -Name $serviceName -Force
    $existing.WaitForStatus('Stopped', [TimeSpan]::FromSeconds(20))
  }
  & sc.exe delete $serviceName | Out-Null
  Start-Sleep -Seconds 1
}
& sc.exe create $serviceName "binPath= `"$target`"" "start= delayed-auto" "DisplayName= Próspero Connector" | Out-Null
& sc.exe failure $serviceName "reset= 86400" "actions= restart/5000/restart/15000/restart/60000" | Out-Null
Start-Service -Name $serviceName
Write-Host 'Próspero Connector instalado. Nenhuma porta de entrada foi aberta no firewall.'
