# =============================================================================
# WEBMoney - Script de Deploy Unificado
# =============================================================================
# Este script faz deploy do frontend, backend ou ambos para o servidor
# 
# Uso:
#   .\deploy.ps1                    # Deploy de ambos (frontend + backend)
#   .\deploy.ps1 -Target frontend   # Apenas frontend
#   .\deploy.ps1 -Target backend    # Apenas backend
#   .\deploy.ps1 -Target both       # Ambos (padrao)
#
# Requer: Node.js, npm, PuTTY (pscp, plink) instalados no PATH
# =============================================================================

param(
    [ValidateSet('frontend', 'backend', 'both')]
    [string]$Target = 'both'
)

$ErrorActionPreference = "Stop"

# Configuracoes
$SERVER_USER = "root"
$SERVER_HOST = "213.165.93.60"
$SERVER_PASS = "Master9354"
$PROJECT_ROOT = $PSScriptRoot

# Paths
$FRONTEND_LOCAL = "$PROJECT_ROOT\frontend"
$FRONTEND_DIST = "$FRONTEND_LOCAL\dist"
$FRONTEND_REMOTE = "/var/www/webmoney/frontend/dist"

$BACKEND_LOCAL = "$PROJECT_ROOT\backend"
$BACKEND_REMOTE = "/var/www/webmoney/backend"

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

function Write-Header {
    param([string]$Text)
    Write-Host ""
    Write-Color "========================================" "Cyan"
    Write-Color "  $Text" "Cyan"
    Write-Color "========================================" "Cyan"
    Write-Host ""
}

function Write-Step {
    param([string]$Step, [string]$Text)
    Write-Color "[$Step] $Text" "Yellow"
}

function Write-OK {
    param([string]$Text)
    Write-Color "[OK] $Text" "Green"
}

function Write-Fail {
    param([string]$Text)
    Write-Color "[ERRO] $Text" "Red"
}

# =============================================================================
# DEPLOY FRONTEND
# =============================================================================
function Deploy-Frontend {
    Write-Header "DEPLOY FRONTEND"
    
    # 1. Build
    Write-Step "1/4" "Fazendo build do frontend..."
    Set-Location $FRONTEND_LOCAL
    
    if (Test-Path $FRONTEND_DIST) {
        Remove-Item -Recurse -Force $FRONTEND_DIST
    }
    
    npm run build
    
    if (-not (Test-Path $FRONTEND_DIST)) {
        Write-Fail "Build falhou - pasta dist nao encontrada"
        exit 1
    }
    Write-OK "Build concluido"
    Write-Host ""
    
    # 2. Limpar diretorio remoto
    Write-Step "2/4" "Limpando diretorio remoto..."
    plink -batch -pw $SERVER_PASS "$SERVER_USER@$SERVER_HOST" "rm -rf $FRONTEND_REMOTE/*"
    Write-OK "Diretorio limpo"
    Write-Host ""
    
    # 3. Enviar arquivos
    Write-Step "3/4" "Enviando arquivos..."
    pscp -r -batch -pw $SERVER_PASS "$FRONTEND_DIST\*" "${SERVER_USER}@${SERVER_HOST}:${FRONTEND_REMOTE}/"
    Write-OK "Arquivos enviados"
    Write-Host ""
    
    # 4. Verificar
    Write-Step "4/4" "Verificando deploy..."
    $result = plink -batch -pw $SERVER_PASS "$SERVER_USER@$SERVER_HOST" "ls $FRONTEND_REMOTE/index.html 2>/dev/null"
    
    if (-not $result) {
        Write-Fail "index.html nao encontrado"
        exit 1
    }
    Write-OK "Frontend deployado com sucesso"
    Write-Host ""
    
    Set-Location $PROJECT_ROOT
}

# =============================================================================
# DEPLOY BACKEND
# =============================================================================
function Deploy-Backend {
    Write-Header "DEPLOY BACKEND"
    
    # 1. Enviar pastas
    Write-Step "1/5" "Enviando pastas do backend..."
    $folders = @("app", "bootstrap", "config", "database", "public", "resources", "routes")
    
    foreach ($folder in $folders) {
        $folderPath = "$BACKEND_LOCAL\$folder"
        if (Test-Path $folderPath) {
            Write-Host "  -> $folder"
            pscp -r -batch -pw $SERVER_PASS "$folderPath" "${SERVER_USER}@${SERVER_HOST}:${BACKEND_REMOTE}/"
        }
    }
    Write-OK "Pastas enviadas"
    Write-Host ""
    
    # 2. Enviar arquivos
    Write-Step "2/5" "Enviando arquivos..."
    $files = @("artisan", "composer.json", "composer.lock")
    
    foreach ($file in $files) {
        $filePath = "$BACKEND_LOCAL\$file"
        if (Test-Path $filePath) {
            Write-Host "  -> $file"
            pscp -batch -pw $SERVER_PASS "$filePath" "${SERVER_USER}@${SERVER_HOST}:${BACKEND_REMOTE}/"
        }
    }
    Write-OK "Arquivos enviados"
    Write-Host ""
    
    # 3. Composer install
    Write-Step "3/5" "Instalando dependencias..."
    plink -batch -pw $SERVER_PASS "$SERVER_USER@$SERVER_HOST" "cd $BACKEND_REMOTE && composer install --no-dev --optimize-autoloader 2>&1 | tail -3"
    Write-OK "Dependencias instaladas"
    Write-Host ""
    
    # 4. Migracoes e cache
    Write-Step "4/5" "Executando migracoes e otimizacoes..."
    plink -batch -pw $SERVER_PASS "$SERVER_USER@$SERVER_HOST" "cd $BACKEND_REMOTE && php artisan migrate --force && php artisan optimize:clear && php artisan config:cache && php artisan route:cache && php artisan view:cache"
    Write-OK "Migracoes e caches OK"
    Write-Host ""
    
    # 5. Permissoes e PHP-FPM
    Write-Step "5/5" "Ajustando permissoes e reiniciando PHP-FPM..."
    plink -batch -pw $SERVER_PASS "$SERVER_USER@$SERVER_HOST" "chown -R www-data:www-data $BACKEND_REMOTE/storage $BACKEND_REMOTE/bootstrap/cache && chmod -R 775 $BACKEND_REMOTE/storage $BACKEND_REMOTE/bootstrap/cache && systemctl restart php8.4-fpm"
    Write-OK "Backend deployado com sucesso"
    Write-Host ""
}

# =============================================================================
# REINICIAR NGINX (sempre ao final)
# =============================================================================
function Restart-Nginx {
    Write-Step "FINAL" "Reiniciando Nginx para limpar cache..."
    plink -batch -pw $SERVER_PASS "$SERVER_USER@$SERVER_HOST" "systemctl restart nginx"
    Write-OK "Nginx reiniciado"
    Write-Host ""
}

# =============================================================================
# MAIN
# =============================================================================
Write-Host ""
Write-Color "========================================" "Magenta"
Write-Color "   WEBMoney - Deploy Unificado         " "Magenta"
Write-Color "   Target: $Target                     " "Magenta"
Write-Color "========================================" "Magenta"
Write-Host ""

$startTime = Get-Date

# Executar deploy conforme target
switch ($Target) {
    'frontend' {
        Deploy-Frontend
    }
    'backend' {
        Deploy-Backend
    }
    'both' {
        Deploy-Backend
        Deploy-Frontend
    }
}

# Sempre reiniciar Nginx ao final
Restart-Nginx

$endTime = Get-Date
$duration = $endTime - $startTime

Write-Color "========================================" "Green"
Write-Color "   DEPLOY CONCLUIDO COM SUCESSO!       " "Green"
Write-Color "========================================" "Green"
Write-Host ""
Write-Host "  Target:   $Target"
Write-Host "  Duracao:  $($duration.TotalSeconds.ToString('F1')) segundos"
Write-Host "  URL:      https://webmoney.cnxifly.com"
Write-Host ""
Write-Host "  Dica: Use Ctrl+Shift+R no navegador para limpar cache local"
Write-Host ""
