# HS Data Collector - Instalador
# Requer privilégios de administrador

param(
    [string]$InstallPath = "C:\Program Files\HS Data Collector"
)

# URL fixa da API
$apiUrl = "https://ingestapi.hellosales.app"

# Verificar privilégios de administrador
$isAdmin = ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")
if (-not $isAdmin) {
    Write-Host "Erro: Este instalador requer privilégios de administrador!"
    Read-Host "Pressione ENTER para sair"
    exit 1
}

Clear-Host
Write-Host "HS Data Collector - Instalador"
Write-Host "================================"
Write-Host ""

# Passo 1: Credenciais da API
Write-Host "Passo 1 de 2: Configuracao da API"
Write-Host ""
Write-Host "API: $apiUrl"
Write-Host ""

$agentId = Read-Host "ID do Agente"
$apiKey = Read-Host "Chave de API"

# Validar credenciais
Write-Host ""
Write-Host "Validando credenciais..."

try {
    $body = @{
        agentId = $agentId
        apiKey = $apiKey
        agentVersion = "1.0.0"
        os = "windows"
        machineName = $env:COMPUTERNAME
    } | ConvertTo-Json

    $response = Invoke-WebRequest -Uri "$apiUrl/api/auth/token" `
        -Method POST `
        -Headers @{"Content-Type" = "application/json"} `
        -Body $body `
        -TimeoutSec 10 `
        -ErrorAction Stop

    Write-Host ""
    Write-Host "OK - Credenciais validadas" -ForegroundColor Green
}
catch {
    Write-Host "Erro ao validar credenciais: $($_.Exception.Message)"
    Read-Host "Pressione ENTER para sair"
    exit 1
}

# Passo 2: Localização de instalação
Write-Host ""
Write-Host "Passo 2 de 2: Localizacao de Instalacao"
Write-Host ""

$installPathChoice = Read-Host "Caminho de instalacao ($InstallPath)"
if (-not [string]::IsNullOrWhiteSpace($installPathChoice)) {
    $InstallPath = $installPathChoice
}

# Instalação
Write-Host ""
Write-Host "Instalando..."

# Criar diretório
if (-not (Test-Path $InstallPath)) {
    New-Item -ItemType Directory -Path $InstallPath -Force | Out-Null
}

# Copiar arquivos do mesmo diretório do script (excluindo o próprio script)
$scriptPath = Split-Path -Parent $MyInvocation.MyCommand.Path
$scriptName = Split-Path -Leaf $MyInvocation.MyCommand.Path

Get-ChildItem -Path $scriptPath -Exclude $scriptName | ForEach-Object {
    if ($_.PSIsContainer) {
        Copy-Item -Path $_.FullName -Destination $InstallPath -Recurse -Force
    } else {
        Copy-Item -Path $_.FullName -Destination $InstallPath -Force
    }
}

# Criar diretórios
New-Item -ItemType Directory -Path "$InstallPath\logs" -Force | Out-Null
New-Item -ItemType Directory -Path "$InstallPath\spool" -Force | Out-Null

# Criar arquivo de configuração
$config = @{
    Logging = @{
        LogLevel = @{
            Default = "Information"
            Microsoft = "Warning"
        }
    }
    ApiSettings = @{
        BaseUrl = $apiUrl
        AuthEndpoint = "/api/auth/token"
        CheckInEndpoint = "/api/agent/checkin"
        IngestBatchEndpoint = "/api/ingestion/runs/{runId}/batches"
        CommitRunEndpoint = "/api/ingestion/runs/{runId}/commit"
        StartRunEndpoint = "/api/ingestion/runs/start"
        GetRunStatusEndpoint = "/api/ingestion/runs/{runId}"
        RequestTimeoutSeconds = 300
    }
    AgentSettings = @{
        AgentId = $agentId
        ApiKey = $apiKey
        AgentVersion = "1.0.0"
        CheckInIntervalSeconds = 300
        MaxRowsPerBatch = 50000
        MaxBytesPerBatch = 52428800
        ParallelUploads = 2
        RetryMaxAttempts = 3
        RetryDelaySeconds = 5
        LocalSpoolPath = "$InstallPath\spool"
    }
    Serilog = @{
        MinimumLevel = "Information"
        WriteTo = @(
            @{ Name = "Console" },
            @{
                Name = "File"
                Args = @{
                    path = "$InstallPath\logs\agent-.txt"
                    rollingInterval = "Day"
                }
            }
        )
    }
} | ConvertTo-Json -Depth 10

$config | Out-File -FilePath "$InstallPath\appsettings.json" -Encoding UTF8

# Criar Windows Service (apenas se não existir)
$serviceName = "HsDataCollector"
$existingService = Get-Service -Name $serviceName -ErrorAction SilentlyContinue

if (-not $existingService) {
    $exePath = "$InstallPath\HsDataCollector.exe"
    New-Service -Name $serviceName `
        -BinaryPathName $exePath `
        -DisplayName "HS Data Collector Agent" `
        -Description "Agente de coleta de dados para HelloSales" `
        -StartupType Automatic | Out-Null
}

# Iniciar o serviço
Write-Host ""
Write-Host "Iniciando o servico..." -ForegroundColor Yellow
Start-Service -Name $serviceName -ErrorAction SilentlyContinue
Start-Sleep -Seconds 3

# Verificar status
$service = Get-Service -Name $serviceName
if ($service.Status -eq "Running") {
    Write-Host "[OK] Servico iniciado com sucesso!" -ForegroundColor Green
} else {
    Write-Host "[AVISO] Servico criado mas nao iniciou automaticamente" -ForegroundColor Yellow
    Write-Host "  Verifique os logs em: $InstallPath\logs\" -ForegroundColor Yellow
}

Write-Host ""
Write-Host "=====================================" -ForegroundColor Green
Write-Host "Instalacao concluida!" -ForegroundColor Green
Write-Host "=====================================" -ForegroundColor Green
Write-Host ""
Write-Host "Informacoes:" -ForegroundColor Green
Write-Host "  Caminho: $InstallPath" -ForegroundColor Green
Write-Host "  Servico: $serviceName" -ForegroundColor Green
Write-Host "  Status: $($service.Status)" -ForegroundColor Green
Write-Host "  Logs: $InstallPath\logs\" -ForegroundColor Green
Write-Host ""
Write-Host "Comandos uteis:" -ForegroundColor Green
Write-Host "  Ver status: Get-Service -Name $serviceName" -ForegroundColor Gray
Write-Host "  Parar: Stop-Service -Name $serviceName" -ForegroundColor Gray
Write-Host "  Iniciar: Start-Service -Name $serviceName" -ForegroundColor Gray
Write-Host "  Ver logs: Get-Content '$InstallPath\logs\agent-*.txt' -Tail 50" -ForegroundColor Gray
Write-Host ""

Write-Host "Pressione ENTER para fechar" -ForegroundColor Yellow
Read-Host "Aguardando ... "
