#!/bin/bash
#############################################
# GestorStream - Instalador Completo de Produção
# Versão: 2.0.0
# Data: 2025-01-15
# 
# Este script instala e configura o GestorStream
# em um novo servidor de produção
#############################################

set -e

# Cores para output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
MAGENTA='\033[0;35m'
CYAN='\033[0;36m'
NC='\033[0m' # No Color

# Banner
echo -e "${CYAN}"
echo "╔════════════════════════════════════════════════════════════╗"
echo "║                                                            ║"
echo "║         GestorStream - Instalador de Produção v2.0         ║"
echo "║       Sistema de Gestão IPTV Profissional                 ║"
echo "║                                                            ║"
echo "╚════════════════════════════════════════════════════════════╝"
echo -e "${NC}"
echo ""

# Verificar se está rodando como root
if [ "$EUID" -ne 0 ]; then 
    echo -e "${RED}❌ Este script precisa ser executado como root (use sudo)${NC}"
    exit 1
fi

# Variáveis de configuração
INSTALL_DIR="/var/www/gestorstream"
LOG_FILE="/tmp/gestorstream-install.log"
BACKEND_DIR="$INSTALL_DIR/backend"
FRONTEND_DIR="$INSTALL_DIR/frontend"

# Função de log
log() {
    echo -e "$1" | tee -a "$LOG_FILE"
}

# Função de erro
error_exit() {
    log "${RED}❌ ERRO: $1${NC}"
    log "${YELLOW}Verifique o log em: $LOG_FILE${NC}"
    exit 1
}

# Função de sucesso
success() {
    log "${GREEN}✅ $1${NC}"
}

# Função de aviso
warning() {
    log "${YELLOW}⚠️  $1${NC}"
}

# Função de info
info() {
    log "${BLUE}ℹ️  $1${NC}"
}

log "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
log "${BLUE}📋 COLETA DE CONFIGURAÇÕES${NC}"
log "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo ""

# URL do Repositório Git
read -p "🔗 URL do repositório Git (ex: https://gitea.com/usuario/GestorStream.git): " GIT_REPO
if [ -z "$GIT_REPO" ]; then
    error_exit "URL do repositório é obrigatória"
fi

# Branch
read -p "🌿 Branch para instalar [main]: " GIT_BRANCH
GIT_BRANCH=${GIT_BRANCH:-main}

# Domínio
read -p "🌐 Domínio do sistema (ex: gestor.exemplo.com): " DOMAIN
if [ -z "$DOMAIN" ]; then
    error_exit "Domínio é obrigatório"
fi

# Email do Admin
read -p "📧 Email do administrador: " ADMIN_EMAIL
if [ -z "$ADMIN_EMAIL" ]; then
    error_exit "Email do administrador é obrigatório"
fi

# Senha do Admin
read -sp "🔐 Senha do administrador: " ADMIN_PASS
echo ""
if [ -z "$ADMIN_PASS" ]; then
    error_exit "Senha do administrador é obrigatória"
fi

# Confirmação de senha
read -sp "🔐 Confirme a senha: " ADMIN_PASS_CONFIRM
echo ""
if [ "$ADMIN_PASS" != "$ADMIN_PASS_CONFIRM" ]; then
    error_exit "As senhas não coincidem"
fi

# Banco de Dados
echo ""
log "${CYAN}🗄️  Configuração do Banco de Dados${NC}"
read -p "Usar banco local ou remoto? [local/remoto] (local): " DB_TYPE
DB_TYPE=${DB_TYPE:-local}

if [[ "$DB_TYPE" == "remoto" ]] || [[ "$DB_TYPE" == "r" ]]; then
    USE_EXTERNAL_DB=true
    info "Configurando banco de dados remoto..."
    
    read -p "🌐 Host do banco (ex: mysql.exemplo.com ou IP): " DB_HOST
    if [ -z "$DB_HOST" ]; then
        error_exit "Host do banco é obrigatório"
    fi
    
    read -p "🔌 Porta do banco [3306]: " DB_PORT
    DB_PORT=${DB_PORT:-3306}
    
    read -p "🗄️  Nome do banco de dados [gestorstream]: " DB_NAME
    DB_NAME=${DB_NAME:-gestorstream}
    
    read -p "👤 Usuário do banco: " DB_USER
    if [ -z "$DB_USER" ]; then
        error_exit "Usuário do banco é obrigatório"
    fi
    
    read -sp "🔐 Senha do banco: " DB_PASS
    echo ""
    if [ -z "$DB_PASS" ]; then
        error_exit "Senha do banco é obrigatória"
    fi
else
    USE_EXTERNAL_DB=false
    info "Configurando banco de dados local..."
    
    DB_HOST="127.0.0.1"
    DB_PORT="3306"
    
    read -p "🗄️  Nome do banco de dados [gestorstream]: " DB_NAME
    DB_NAME=${DB_NAME:-gestorstream}
    
    read -p "👤 Usuário root do MySQL [root]: " DB_USER
    DB_USER=${DB_USER:-root}
    
    read -sp "🔐 Senha do MySQL (deixe vazio se não houver): " DB_PASS
    echo ""
fi

# Porta HTTP
read -p "🔌 Porta HTTP [80]: " HTTP_PORT
HTTP_PORT=${HTTP_PORT:-80}

# SSL
echo ""
read -p "🔒 Instalar certificado SSL (Let's Encrypt) após instalação? [S/n]: " INSTALL_SSL
INSTALL_SSL=${INSTALL_SSL:-S}

echo ""
success "Configurações coletadas!"
echo ""
read -p "Pressione ENTER para iniciar a instalação ou CTRL+C para cancelar..."
echo ""

log "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
log "${BLUE}📦 ETAPA 1/8: ATUALIZANDO SISTEMA${NC}"
log "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"

apt-get update -qq
apt-get install -y software-properties-common apt-transport-https ca-certificates \
    git curl wget unzip gnupg lsb-release -qq

success "Sistema atualizado"

log "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
log "${BLUE}📦 ETAPA 2/8: INSTALANDO NODE.JS${NC}"
log "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"

if ! command -v node &> /dev/null; then
    info "Instalando Node.js 20.x..."
    curl -fsSL https://deb.nodesource.com/setup_20.x | bash - > /dev/null 2>&1
    apt-get install -y nodejs -qq
    success "Node.js instalado: $(node -v)"
else
    success "Node.js já instalado: $(node -v)"
fi

log "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
log "${BLUE}📦 ETAPA 3/8: INSTALANDO PHP 8.2${NC}"
log "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"

if ! command -v php &> /dev/null || ! php -v | grep -q "8.2"; then
    info "Adicionando repositório do PHP..."
    add-apt-repository ppa:ondrej/php -y > /dev/null 2>&1
    apt-get update -qq
    
    info "Instalando PHP 8.2 e extensões..."
    apt-get install -y \
        php8.2-fpm \
        php8.2-cli \
        php8.2-common \
        php8.2-mysql \
        php8.2-zip \
        php8.2-gd \
        php8.2-mbstring \
        php8.2-curl \
        php8.2-xml \
        php8.2-bcmath \
        php8.2-redis \
        php8.2-intl \
        php8.2-soap \
        -qq
    
    # Configurar PHP
    PHP_INI="/etc/php/8.2/fpm/php.ini"
    sed -i 's/upload_max_filesize = .*/upload_max_filesize = 100M/' "$PHP_INI"
    sed -i 's/post_max_size = .*/post_max_size = 100M/' "$PHP_INI"
    sed -i 's/memory_limit = .*/memory_limit = 512M/' "$PHP_INI"
    sed -i 's/max_execution_time = .*/max_execution_time = 300/' "$PHP_INI"
    
    systemctl enable php8.2-fpm
    systemctl restart php8.2-fpm
    
    success "PHP 8.2 instalado e configurado: $(php -v | head -n 1)"
else
    success "PHP 8.2 já instalado: $(php -v | head -n 1)"
fi

log "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
log "${BLUE}📦 ETAPA 4/8: INSTALANDO COMPOSER${NC}"
log "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"

if ! command -v composer &> /dev/null; then
    info "Instalando Composer..."
    curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer --quiet
    success "Composer instalado: $(composer --version)"
else
    success "Composer já instalado: $(composer --version)"
fi

log "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
log "${BLUE}📦 ETAPA 5/8: INSTALANDO NGINX${NC}"
log "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"

if ! command -v nginx &> /dev/null; then
    apt-get install -y nginx -qq
    systemctl enable nginx
    success "Nginx instalado"
else
    success "Nginx já instalado"
fi

log "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
log "${BLUE}📦 ETAPA 6/8: CONFIGURANDO BANCO DE DADOS${NC}"
log "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"

if [ "$USE_EXTERNAL_DB" = false ]; then
    # Instalar MariaDB
    if ! command -v mysql &> /dev/null; then
        info "Instalando MariaDB..."
        apt-get install -y mariadb-server mariadb-client -qq
        systemctl enable mariadb
        systemctl start mariadb
        success "MariaDB instalado"
    else
        success "MariaDB já instalado"
        systemctl start mariadb 2>/dev/null || true
    fi
    
    # Criar banco e usuário
    info "Criando banco de dados local..."
    if [ -z "$DB_PASS" ]; then
        mysql -u "$DB_USER" -e "CREATE DATABASE IF NOT EXISTS $DB_NAME CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;" 2>/dev/null || \
        mysql -e "CREATE DATABASE IF NOT EXISTS $DB_NAME CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;"
    else
        mysql -u "$DB_USER" -p"$DB_PASS" -e "CREATE DATABASE IF NOT EXISTS $DB_NAME CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;" 2>/dev/null || \
        mysql -e "CREATE DATABASE IF NOT EXISTS $DB_NAME CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;"
    fi
    success "Banco de dados '$DB_NAME' criado"
else
    # Instalar cliente MySQL
    if ! command -v mysql &> /dev/null; then
        apt-get install -y mariadb-client -qq
        success "Cliente MySQL instalado"
    fi
    
    # Testar conexão
    info "Testando conexão com banco remoto..."
    if mysql -h "$DB_HOST" -P "$DB_PORT" -u "$DB_USER" -p"$DB_PASS" -e "SELECT 1;" &> /dev/null; then
        success "Conexão com banco remoto OK!"
        
        # Verificar/criar banco
        if ! mysql -h "$DB_HOST" -P "$DB_PORT" -u "$DB_USER" -p"$DB_PASS" -e "USE $DB_NAME;" &> /dev/null; then
            warning "Banco '$DB_NAME' não existe"
            read -p "Deseja criar o banco? [S/n]: " CREATE_DB
            CREATE_DB=${CREATE_DB:-S}
            if [[ "$CREATE_DB" =~ ^[Ss]$ ]]; then
                if mysql -h "$DB_HOST" -P "$DB_PORT" -u "$DB_USER" -p"$DB_PASS" -e "CREATE DATABASE IF NOT EXISTS $DB_NAME CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;" 2>/dev/null; then
                    success "Banco criado com sucesso"
                else
                    error_exit "Falha ao criar banco. Verifique permissões do usuário."
                fi
            else
                warning "Certifique-se de que o banco '$DB_NAME' existe antes de continuar"
            fi
        else
            success "Banco '$DB_NAME' encontrado"
        fi
    else
        warning "Falha ao conectar no banco remoto"
        read -p "Deseja continuar mesmo assim? [s/N]: " CONTINUE
        if [[ ! "$CONTINUE" =~ ^[Ss]$ ]]; then
            error_exit "Instalação cancelada"
        fi
    fi
fi

# Instalar Redis
log "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
log "${BLUE}📦 ETAPA 7/8: INSTALANDO REDIS${NC}"
log "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"

if ! command -v redis-server &> /dev/null; then
    apt-get install -y redis-server -qq
    systemctl enable redis-server
    systemctl start redis-server
    success "Redis instalado e iniciado"
else
    success "Redis já instalado"
    systemctl start redis-server 2>/dev/null || true
fi

log "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
log "${BLUE}📁 ETAPA 8/8: CLONANDO E CONFIGURANDO APLICAÇÃO${NC}"
log "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"

# Criar diretório
mkdir -p "$INSTALL_DIR"
cd "$INSTALL_DIR"

# Clonar repositório
if [ ! -d ".git" ]; then
    info "Clonando repositório..."
    info "⚠️  Se o repositório for privado, você precisará fornecer credenciais Git"
    if ! git clone -b "$GIT_BRANCH" "$GIT_REPO" . 2>&1 | tee -a "$LOG_FILE"; then
        error_exit "Falha ao clonar repositório. Verifique:"
        error_exit "  1. URL do repositório está correta"
        error_exit "  2. Credenciais Git estão configuradas (git config --global user.name e user.email)"
        error_exit "  3. Você tem acesso ao repositório"
        error_exit "  4. Para repositórios privados, configure autenticação:"
        error_exit "     git config --global credential.helper store"
        error_exit "     ou use SSH: git clone git@git.jf.eng.br:jfeng/GestorStream.git"
    fi
    success "Repositório clonado"
else
    info "Repositório já existe, atualizando..."
    git fetch origin
    git checkout "$GIT_BRANCH"
    if ! git pull origin "$GIT_BRANCH" 2>&1 | tee -a "$LOG_FILE"; then
        warning "Falha ao atualizar repositório, continuando com código existente..."
    else
        success "Repositório atualizado"
    fi
fi

# BACKEND
log "${CYAN}📦 Configurando Backend (Laravel)...${NC}"

# Verificar se backend existe
if [ ! -d "$BACKEND_DIR" ]; then
    error_exit "Diretório backend não encontrado em $INSTALL_DIR. Verifique se o repositório foi clonado corretamente."
fi

cd "$BACKEND_DIR"

# Verificar se composer.json existe
if [ ! -f "composer.json" ]; then
    error_exit "composer.json não encontrado em $BACKEND_DIR. Verifique se o repositório foi clonado corretamente."
fi

# Instalar dependências Composer
info "Instalando dependências do Laravel..."
info "⏳ Isso pode levar alguns minutos..."

# Permitir plugins e superuser para composer (evita avisos)
export COMPOSER_ALLOW_SUPERUSER=1

# Limpar cache do Composer antes
composer clear-cache --quiet 2>/dev/null || true

# Verificar se composer.lock está desatualizado
LOCK_OUTDATED=false
if [ -f "composer.lock" ]; then
    # Tentar instalar primeiro
    if ! composer install --no-dev --optimize-autoloader --no-interaction 2>&1 | tee -a "$LOG_FILE"; then
        # Verificar se o erro é relacionado a lock file desatualizado ou pacote faltando
        if grep -qE "lock file is not up to date|not present in the lock file|Required package.*is not present" "$LOG_FILE" 2>/dev/null; then
            warning "composer.lock está desatualizado ou incompleto, atualizando..."
            LOCK_OUTDATED=true
        else
            warning "composer install falhou por outro motivo, tentando update..."
            LOCK_OUTDATED=true
        fi
    fi
else
    warning "composer.lock não encontrado, executando composer update..."
    LOCK_OUTDATED=true
fi

# Se lock está desatualizado ou install falhou, fazer update
if [ "$LOCK_OUTDATED" = true ] || [ ! -f "vendor/autoload.php" ]; then
    info "Executando composer update (isso pode levar mais tempo)..."
    info "⏳ Isso atualizará o composer.lock e instalará todas as dependências..."
    
    if ! composer update --no-dev --optimize-autoloader --no-interaction 2>&1 | tee -a "$LOG_FILE"; then
        error_exit "Falha ao atualizar dependências do Composer. Verifique o log: $LOG_FILE"
    fi
fi

# Verificar se vendor/autoload.php foi criado
if [ ! -f "vendor/autoload.php" ]; then
    error_exit "vendor/autoload.php não foi criado. Composer falhou. Verifique o log: $LOG_FILE"
fi

success "Dependências do Laravel instaladas"

# Configurar .env
if [ ! -f ".env" ]; then
    info "Criando arquivo .env..."
    if [ -f ".env.example" ]; then
        cp .env.example .env
    else
        # Criar .env básico se .env.example não existir
        cat > .env <<EOF
APP_NAME=GestorStream
APP_ENV=production
APP_KEY=
APP_DEBUG=false
APP_URL=http://${DOMAIN}

DB_CONNECTION=mysql
DB_HOST=${DB_HOST}
DB_PORT=${DB_PORT}
DB_DATABASE=${DB_NAME}
DB_USERNAME=${DB_USER}
DB_PASSWORD=${DB_PASS}

REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379

QUEUE_CONNECTION=redis
SESSION_DRIVER=redis
CACHE_DRIVER=redis

BROADCAST_DRIVER=log
LOG_CHANNEL=stack
LOG_LEVEL=error
EOF
    fi
    
    # Configurar variáveis no .env
    sed -i "s|APP_URL=.*|APP_URL=http://${DOMAIN}|" .env
    sed -i "s|DB_HOST=.*|DB_HOST=${DB_HOST}|" .env
    sed -i "s|DB_PORT=.*|DB_PORT=${DB_PORT}|" .env
    sed -i "s|DB_DATABASE=.*|DB_DATABASE=${DB_NAME}|" .env
    sed -i "s|DB_USERNAME=.*|DB_USERNAME=${DB_USER}|" .env
    sed -i "s|DB_PASSWORD=.*|DB_PASSWORD=${DB_PASS}|" .env
    sed -i "s|REDIS_HOST=.*|REDIS_HOST=127.0.0.1|" .env
    sed -i "s|QUEUE_CONNECTION=.*|QUEUE_CONNECTION=redis|" .env
    
    # Verificar se artisan existe antes de gerar chave
    if [ ! -f "artisan" ]; then
        error_exit "Arquivo artisan não encontrado. Verifique se o repositório foi clonado corretamente."
    fi
    
    # Gerar chave da aplicação
    if ! php artisan key:generate --force 2>&1 | tee -a "$LOG_FILE"; then
        error_exit "Falha ao gerar chave da aplicação. Verifique se vendor/autoload.php existe."
    fi
    
    success "Arquivo .env configurado"
fi

# Rodar migrações
info "Executando migrações do banco de dados..."
php artisan migrate --force --no-interaction 2>&1 | tee -a "$LOG_FILE"

# Criar usuário admin
info "Criando usuário administrador..."
cat > /tmp/create_admin.php <<'EOFPHP'
<?php
$basePath = getenv('BASE_PATH');
require $basePath . '/vendor/autoload.php';
$app = require_once $basePath . '/bootstrap/app.php';
$app->make('Illuminate\Contracts\Console\Kernel')->bootstrap();

$email = getenv('ADMIN_EMAIL');
$password = getenv('ADMIN_PASS');

DB::table('users')->updateOrInsert(
    ['email' => $email],
    [
        'name' => 'Administrador',
        'email' => $email,
        'password' => Hash::make($password),
        'role' => 'admin',
        'email_verified_at' => now(),
        'created_at' => now(),
        'updated_at' => now()
    ]
);

echo "Usuário admin criado/atualizado: $email\n";
EOFPHP

ADMIN_EMAIL="$ADMIN_EMAIL" ADMIN_PASS="$ADMIN_PASS" BASE_PATH="$BACKEND_DIR" php /tmp/create_admin.php 2>&1 | tee -a "$LOG_FILE"
rm -f /tmp/create_admin.php

# Rodar seeders (se existirem)
if php artisan db:seed --class=PlanSeeder --force --no-interaction 2>/dev/null | tee -a "$LOG_FILE"; then
    info "Seeders executados"
fi

# Cache
php artisan config:cache
php artisan route:cache
php artisan view:cache

success "Backend configurado"

# FRONTEND
log "${CYAN}📦 Configurando Frontend (React)...${NC}"
cd "$FRONTEND_DIR"

info "Instalando dependências do frontend..."
export NPM_CONFIG_CACHE="$BACKEND_DIR/storage/npm-cache"
mkdir -p "$NPM_CONFIG_CACHE"
npm install --silent --no-audit --no-fund 2>&1 | tee -a "$LOG_FILE"

info "Compilando frontend (isso pode levar alguns minutos)..."
export NODE_OPTIONS="--max-old-space-size=4096"
npm run build 2>&1 | tee -a "$LOG_FILE"

if [ ! -f "dist/index.html" ]; then
    error_exit "Build do frontend falhou - index.html não encontrado"
fi

success "Frontend compilado"

# PERMISSÕES
log "${CYAN}🔐 Configurando permissões...${NC}"
chown -R www-data:www-data "$INSTALL_DIR"
chmod -R 775 "$INSTALL_DIR"
chmod +x "$BACKEND_DIR/artisan"
chmod -R 777 "$BACKEND_DIR/storage"
chmod -R 777 "$BACKEND_DIR/bootstrap/cache"
success "Permissões configuradas"

log "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
log "${BLUE}🌐 CONFIGURANDO NGINX${NC}"
log "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"

cat > /etc/nginx/sites-available/gestorstream <<EOF
server {
    listen ${HTTP_PORT};
    listen [::]:${HTTP_PORT};
    server_name ${DOMAIN};

    root ${FRONTEND_DIR}/dist;
    index index.html;

    # Logs
    access_log /var/log/nginx/gestorstream-access.log;
    error_log /var/log/nginx/gestorstream-error.log;

    # Frontend - SPA
    location / {
        try_files \$uri \$uri/ /index.html;
        add_header Cache-Control "no-cache, no-store, must-revalidate";
    }

    # Backend API
    location /api {
        proxy_pass http://127.0.0.1:8000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade \$http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host \$host;
        proxy_cache_bypass \$http_upgrade;
        proxy_set_header X-Real-IP \$remote_addr;
        proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto \$scheme;
    }

    # Storage (uploads)
    location /storage {
        alias ${BACKEND_DIR}/storage/app/public;
        try_files \$uri \$uri/ =404;
        expires 30d;
        add_header Cache-Control "public, immutable";
    }

    # Arquivos estáticos do frontend
    location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot)$ {
        expires 1y;
        add_header Cache-Control "public, immutable";
    }

    client_max_body_size 100M;
}
EOF

# Ativar site
ln -sf /etc/nginx/sites-available/gestorstream /etc/nginx/sites-enabled/
rm -f /etc/nginx/sites-enabled/default

# Testar configuração
nginx -t 2>&1 | tee -a "$LOG_FILE" || error_exit "Configuração do Nginx inválida"

# Reiniciar Nginx
systemctl restart nginx
success "Nginx configurado"

log "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
log "${BLUE}⚙️  CONFIGURANDO SERVIÇOS SYSTEMD${NC}"
log "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"

# Criar diretórios de log
touch /var/log/gestorstream-backend.log /var/log/gestorstream-backend-error.log
touch /var/log/gestorstream-worker.log /var/log/gestorstream-worker-error.log
chown www-data:www-data /var/log/gestorstream-*.log
chmod 664 /var/log/gestorstream-*.log

# Serviço Backend
cat > /etc/systemd/system/gestorstream-backend.service <<EOF
[Unit]
Description=GestorStream Backend API
After=network.target mysql.service redis.service

[Service]
Type=simple
User=www-data
Group=www-data
WorkingDirectory=${BACKEND_DIR}
Environment="PATH=/usr/bin:/usr/sbin"
ExecStart=/usr/bin/php8.2 ${BACKEND_DIR}/artisan serve --host=127.0.0.1 --port=8000
Restart=always
RestartSec=5s
StandardOutput=append:/var/log/gestorstream-backend.log
StandardError=append:/var/log/gestorstream-backend-error.log

[Install]
WantedBy=multi-user.target
EOF

# Serviço Queue Worker
cat > /etc/systemd/system/gestorstream-worker.service <<EOF
[Unit]
Description=GestorStream Queue Worker
After=network.target mysql.service redis.service

[Service]
Type=simple
User=www-data
Group=www-data
WorkingDirectory=${BACKEND_DIR}
Environment="PATH=/usr/bin:/usr/sbin"
ExecStart=/usr/bin/php8.2 ${BACKEND_DIR}/artisan queue:work redis --sleep=3 --tries=3 --timeout=90 --max-jobs=1000
Restart=always
RestartSec=5s
StandardOutput=append:/var/log/gestorstream-worker.log
StandardError=append:/var/log/gestorstream-worker-error.log

[Install]
WantedBy=multi-user.target
EOF

# Recarregar systemd
systemctl daemon-reload

# Habilitar e iniciar serviços
systemctl enable gestorstream-backend gestorstream-worker
systemctl start gestorstream-backend gestorstream-worker

sleep 3

# Verificar serviços
if systemctl is-active --quiet gestorstream-backend; then
    success "Backend iniciado"
else
    error_exit "Backend não iniciou. Verifique: journalctl -u gestorstream-backend -n 50"
fi

if systemctl is-active --quiet gestorstream-worker; then
    success "Queue Worker iniciado"
else
    error_exit "Queue Worker não iniciou. Verifique: journalctl -u gestorstream-worker -n 50"
fi

log "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
log "${BLUE}⏰ CONFIGURANDO CRON JOBS${NC}"
log "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"

# Remover crontab antigo se existir
(crontab -l 2>/dev/null | grep -v "gestorstream\|schedule:run" || true) | crontab -

# Adicionar scheduler do Laravel
(crontab -l 2>/dev/null; echo "* * * * * cd ${BACKEND_DIR} && /usr/bin/php artisan schedule:run >> ${BACKEND_DIR}/storage/logs/scheduler.log 2>&1") | crontab -

success "Cron jobs configurados"

log "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
log "${BLUE}🔐 CONFIGURANDO SUDOERS (Auto-Update)${NC}"
log "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"

if [ -f "$INSTALL_DIR/build_frontend.sh" ]; then
    chmod +x "$INSTALL_DIR/build_frontend.sh"
    cat > /etc/sudoers.d/gestorstream << EOF
# Permitir www-data executar script de build do frontend durante auto-update
www-data ALL=(root) NOPASSWD: ${INSTALL_DIR}/build_frontend.sh
EOF
    chmod 0440 /etc/sudoers.d/gestorstream
    success "Sudoers configurado para auto-update"
fi

log "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
log "${BLUE}🔒 CONFIGURANDO SSL (OPCIONAL)${NC}"
log "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"

if [[ "$INSTALL_SSL" =~ ^[Ss]$ ]]; then
    # Instalar Certbot
    if ! command -v certbot &> /dev/null; then
        info "Instalando Certbot..."
        apt-get install -y certbot python3-certbot-nginx -qq
        success "Certbot instalado"
    fi
    
    info "IMPORTANTE: Certifique-se que:"
    info "  1. O DNS de $DOMAIN está apontando para este servidor"
    info "  2. A porta 80 está acessível da internet"
    echo ""
    read -p "DNS configurado e porta 80 acessível? [S/n]: " DNS_OK
    DNS_OK=${DNS_OK:-S}
    
    if [[ "$DNS_OK" =~ ^[Ss]$ ]]; then
        info "Obtendo certificado SSL..."
        certbot --nginx -d "$DOMAIN" --non-interactive --agree-tos --email "$ADMIN_EMAIL" --redirect 2>&1 | tee -a "$LOG_FILE"
        
        if [ $? -eq 0 ]; then
            # Atualizar APP_URL no .env
            sed -i "s|APP_URL=http://|APP_URL=https://|" "$BACKEND_DIR/.env"
            php artisan config:cache
            
            # Reiniciar backend
            systemctl restart gestorstream-backend
            
            success "Certificado SSL instalado com sucesso!"
            USE_HTTPS=true
        else
            warning "Falha ao obter certificado SSL. Você pode tentar depois com:"
            info "  sudo certbot --nginx -d $DOMAIN"
            USE_HTTPS=false
        fi
    else
        warning "Pulando instalação de SSL. Configure depois com:"
        info "  sudo certbot --nginx -d $DOMAIN"
        USE_HTTPS=false
    fi
else
    warning "SSL não será instalado agora"
    info "Para instalar depois: sudo certbot --nginx -d $DOMAIN"
    USE_HTTPS=false
fi

# RESUMO FINAL
echo ""
echo -e "${GREEN}"
echo "╔════════════════════════════════════════════════════════════╗"
echo "║     ✅  INSTALAÇÃO CONCLUÍDA COM SUCESSO!                 ║"
echo "╚════════════════════════════════════════════════════════════╝"
echo -e "${NC}"
echo ""

log "${CYAN}📊 INFORMAÇÕES DO SISTEMA:${NC}"
log "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
if [ "$USE_HTTPS" = true ]; then
    log "${GREEN}🌐 URL: https://${DOMAIN}${NC}"
else
    log "${GREEN}🌐 URL: http://${DOMAIN}${NC}"
fi
log "${GREEN}📧 Admin: ${ADMIN_EMAIL}${NC}"
log "${GREEN}🗄️  Banco: ${DB_NAME} (${DB_HOST}:${DB_PORT})${NC}"
log "${GREEN}📁 Instalação: ${INSTALL_DIR}${NC}"
echo ""

log "${CYAN}✅ STATUS DOS SERVIÇOS:${NC}"
log "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
systemctl is-active nginx &> /dev/null && success "Nginx" || log "${RED}❌ Nginx${NC}"
systemctl is-active php8.2-fpm &> /dev/null && success "PHP-FPM" || log "${RED}❌ PHP-FPM${NC}"
systemctl is-active redis-server &> /dev/null && success "Redis" || log "${RED}❌ Redis${NC}"
if [ "$USE_EXTERNAL_DB" = false ]; then
    systemctl is-active mariadb &> /dev/null && success "MariaDB" || log "${RED}❌ MariaDB${NC}"
else
    log "${GREEN}✅ Banco externo: ${DB_HOST}:${DB_PORT}${NC}"
fi
systemctl is-active gestorstream-backend &> /dev/null && success "Backend API" || log "${RED}❌ Backend API${NC}"
systemctl is-active gestorstream-worker &> /dev/null && success "Queue Worker" || log "${RED}❌ Queue Worker${NC}"
if [ "$USE_HTTPS" = true ]; then
    log "${GREEN}🔒 SSL/HTTPS: Ativo${NC}"
else
    log "${YELLOW}⚠️  SSL/HTTPS: Não configurado${NC}"
fi
echo ""

log "${CYAN}💡 PRÓXIMOS PASSOS:${NC}"
log "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
if [ "$USE_HTTPS" = true ]; then
    log "  1. Acesse: ${GREEN}https://${DOMAIN}${NC}"
else
    log "  1. Acesse: ${GREEN}http://${DOMAIN}${NC}"
fi
log "  2. Faça login com:"
log "     ${GREEN}Email: ${ADMIN_EMAIL}${NC}"
log "     ${GREEN}Senha: [a senha que você definiu]${NC}"
log "  3. Configure as integrações:"
log "     • WhatsApp (Uazapi / Evolution API)"
log "     • Pagamentos (Mercado Pago / OpenPIX)"
log "     • Gitea (para auto-updates)"
if [ "$USE_HTTPS" = false ]; then
    log "  4. ${YELLOW}[Recomendado]${NC} Configure HTTPS:"
    log "     ${CYAN}sudo certbot --nginx -d ${DOMAIN}${NC}"
fi
echo ""

log "${CYAN}📝 COMANDOS ÚTEIS:${NC}"
log "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
log "  Ver logs backend:  ${CYAN}journalctl -u gestorstream-backend -f${NC}"
log "  Ver logs worker:   ${CYAN}journalctl -u gestorstream-worker -f${NC}"
log "  Ver logs scheduler:${CYAN}tail -f ${BACKEND_DIR}/storage/logs/scheduler.log${NC}"
log "  Ver logs nginx:    ${CYAN}tail -f /var/log/nginx/gestorstream-error.log${NC}"
log "  Reiniciar tudo:    ${CYAN}systemctl restart nginx php8.2-fpm gestorstream-backend gestorstream-worker${NC}"
log "  Status serviços:   ${CYAN}systemctl status gestorstream-backend gestorstream-worker${NC}"
log "  Ver crontab:       ${CYAN}crontab -l${NC}"
echo ""

log "${GREEN}✨ Sistema pronto para produção!${NC}"
log "${BLUE}📄 Log completo da instalação: ${LOG_FILE}${NC}"
echo ""
