# =============================================================================
# WEBMoney Frontend - Script de Deploy para Windows
# =============================================================================
# Este script faz build e deploy do frontend para o servidor de producao
# Uso: .\deploy.ps1
# Requer: Node.js, npm, PuTTY (pscp, plink) instalados no PATH
# =============================================================================

$ErrorActionPreference = "Stop"

# Configuracoes
$SERVER_USER = "root"
$SERVER_HOST = "213.165.93.60"
$SERVER_PASS = "Master9354"
$REMOTE_PATH = "/var/www/webmoney/frontend/dist"
$LOCAL_DIST = ".\dist"

# Cores
function Write-Color {
    param([string]$Text, [string]$Color = "White")
    Write-Host $Text -ForegroundColor $Color
}

Write-Host ""
Write-Color "========================================" "Cyan"
Write-Color "   WEBMoney Frontend - Deploy Script   " "Cyan"
Write-Color "========================================" "Cyan"
Write-Host ""

# 1. Build
Write-Color "[1/4] Fazendo build do frontend..." "Yellow"

if (Test-Path $LOCAL_DIST) {
    Remove-Item -Recurse -Force $LOCAL_DIST
}

npm run build

if (-not (Test-Path $LOCAL_DIST)) {
    Write-Color "ERRO: Build falhou - pasta dist nao encontrada" "Red"
    exit 1
}

Write-Color "Build concluido" "Green"
Write-Host ""

# 2. Limpar diretorio remoto
Write-Color "[2/4] Limpando diretorio remoto..." "Yellow"
plink -batch -pw $SERVER_PASS "$SERVER_USER@$SERVER_HOST" "rm -rf $REMOTE_PATH/*"

Write-Color "Diretorio remoto limpo" "Green"
Write-Host ""

# 3. Enviar arquivos
Write-Color "[3/4] Enviando arquivos para $REMOTE_PATH ..." "Yellow"
pscp -r -batch -pw $SERVER_PASS "$LOCAL_DIST\*" "${SERVER_USER}@${SERVER_HOST}:${REMOTE_PATH}/"

Write-Color "Arquivos enviados" "Green"
Write-Host ""

# 4. Verificar deploy
Write-Color "[4/5] Verificando deploy..." "Yellow"
$result = plink -batch -pw $SERVER_PASS "$SERVER_USER@$SERVER_HOST" "ls $REMOTE_PATH/index.html 2>/dev/null"

if (-not $result) {
    Write-Color "========================================" "Red"
    Write-Color "   ERRO: index.html nao encontrado     " "Red"
    Write-Color "========================================" "Red"
    exit 1
}

Write-Color "Arquivos verificados" "Green"
Write-Host ""

# 5. Reiniciar Nginx para limpar cache
Write-Color "[5/5] Reiniciando Nginx para limpar cache..." "Yellow"
plink -batch -pw $SERVER_PASS "$SERVER_USER@$SERVER_HOST" "systemctl restart nginx"

Write-Color "Nginx reiniciado" "Green"
Write-Host ""

Write-Host ""
Write-Color "========================================" "Green"
Write-Color "   Deploy concluido com sucesso!       " "Green"
Write-Color "========================================" "Green"
Write-Host ""
Write-Host "Acesse: https://webmoney.cnxifly.com"
Write-Host ""
Write-Host "Dica: Use Ctrl+Shift+R no navegador para limpar o cache local"
Write-Host ""
