#!/bin/bash
# ============================================================
# Manutix — Script de Deploy Completo
# Domínio: app.minhaos.com
# Servidor: 82.25.66.174
# ============================================================
set -e

DOMAIN="app.minhaos.com"
APP_DIR="/opt/manutix"
DB_PASS="Mn@$(openssl rand -hex 12)"
JWT_SECRET="$(openssl rand -hex 32)"
JWT_REFRESH="$(openssl rand -hex 32)"

echo ""
echo "╔══════════════════════════════════════════╗"
echo "║     MANUTIX — INSTALAÇÃO AUTOMÁTICA      ║"
echo "╚══════════════════════════════════════════╝"
echo ""
echo "🌐 Domínio: $DOMAIN"
echo "📁 Diretório: $APP_DIR"
echo ""

# ─── 1. DEPENDÊNCIAS ─────────────────────────────────────────
echo "📦 [1/7] Instalando dependências..."
apt-get update -qq
apt-get install -y -qq curl git nginx certbot python3-certbot-nginx openssl

# Docker
if ! command -v docker &> /dev/null; then
    echo "🐳 Instalando Docker..."
    curl -fsSL https://get.docker.com | sh -s -- -q
fi

# Docker Compose Plugin
if ! docker compose version &> /dev/null; then
    apt-get install -y -qq docker-compose-plugin
fi

echo "✅ Dependências OK"

# ─── 2. DIRETÓRIO DO APP ─────────────────────────────────────
echo "📁 [2/7] Preparando diretório..."
mkdir -p $APP_DIR
cd $APP_DIR

# ─── 3. CRIAR ESTRUTURA DO PROJETO ───────────────────────────
echo "🏗️  [3/7] Criando estrutura do projeto..."

# .env
cat > $APP_DIR/.env << ENVEOF
DATABASE_URL=postgresql://manutix:${DB_PASS}@postgres:5432/manutix
POSTGRES_PASSWORD=${DB_PASS}
JWT_SECRET=${JWT_SECRET}
JWT_EXPIRES_IN=15m
JWT_REFRESH_SECRET=${JWT_REFRESH}
JWT_REFRESH_EXPIRES_IN=7d
PORT=3001
NODE_ENV=production
FRONTEND_URL=https://${DOMAIN}
NEXT_PUBLIC_API_URL=https://${DOMAIN}/api/v1
ENVEOF

echo "✅ .env criado (senhas geradas automaticamente)"

# ─── 4. DOCKER COMPOSE ───────────────────────────────────────
echo "🐳 [4/7] Criando docker-compose.yml..."

mkdir -p $APP_DIR/apps/api
mkdir -p $APP_DIR/apps/web

cat > $APP_DIR/docker-compose.yml << 'DCEOF'
version: '3.9'

services:
  postgres:
    image: postgres:16-alpine
    container_name: manutix_db
    restart: unless-stopped
    environment:
      POSTGRES_DB: manutix
      POSTGRES_USER: manutix
      POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
    volumes:
      - postgres_data:/var/lib/postgresql/data
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U manutix"]
      interval: 10s
      timeout: 5s
      retries: 5

  api:
    image: node:20-alpine
    container_name: manutix_api
    restart: unless-stopped
    working_dir: /app
    command: sh -c "npm install && npx prisma generate && npx prisma migrate deploy && node -e \"require('./dist/main')\" 2>/dev/null || (npm run build && node dist/main)"
    environment:
      DATABASE_URL: ${DATABASE_URL}
      JWT_SECRET: ${JWT_SECRET}
      JWT_EXPIRES_IN: ${JWT_EXPIRES_IN}
      JWT_REFRESH_SECRET: ${JWT_REFRESH_SECRET}
      JWT_REFRESH_EXPIRES_IN: ${JWT_REFRESH_EXPIRES_IN}
      PORT: 3001
      NODE_ENV: production
      FRONTEND_URL: ${FRONTEND_URL}
    volumes:
      - ./apps/api:/app
      - api_modules:/app/node_modules
    ports:
      - "3001:3001"
    depends_on:
      postgres:
        condition: service_healthy

  web:
    image: node:20-alpine
    container_name: manutix_web
    restart: unless-stopped
    working_dir: /app
    command: sh -c "npm install && npm run build && npm start"
    environment:
      NEXT_PUBLIC_API_URL: ${NEXT_PUBLIC_API_URL}
      NODE_ENV: production
      PORT: 3000
    volumes:
      - ./apps/web:/app
      - web_modules:/app/node_modules
    ports:
      - "3000:3000"
    depends_on:
      - api

volumes:
  postgres_data:
  api_modules:
  web_modules:
DCEOF

echo "✅ docker-compose.yml criado"

# ─── 5. NGINX ────────────────────────────────────────────────
echo "🌐 [5/7] Configurando Nginx..."

cat > /etc/nginx/sites-available/manutix << NGINXEOF
server {
    listen 80;
    server_name ${DOMAIN};

    # Frontend Next.js
    location / {
        proxy_pass http://localhost:3000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade \$http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host \$host;
        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;
        proxy_cache_bypass \$http_upgrade;
        client_max_body_size 50M;
    }

    # Backend API
    location /api/ {
        proxy_pass http://localhost:3001;
        proxy_http_version 1.1;
        proxy_set_header Host \$host;
        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;
        client_max_body_size 50M;
    }

    # WebSocket para notificações em tempo real
    location /notifications/ {
        proxy_pass http://localhost:3001;
        proxy_http_version 1.1;
        proxy_set_header Upgrade \$http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header Host \$host;
        proxy_read_timeout 86400;
    }

    # Swagger
    location /api/docs {
        proxy_pass http://localhost:3001;
        proxy_http_version 1.1;
        proxy_set_header Host \$host;
    }
}
NGINXEOF

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

nginx -t && systemctl reload nginx
echo "✅ Nginx configurado"

# ─── 6. SSL ──────────────────────────────────────────────────
echo "🔒 [6/7] Obtendo certificado SSL..."

certbot --nginx -d $DOMAIN \
    --non-interactive \
    --agree-tos \
    --email admin@minhaos.com \
    --redirect \
    --quiet && echo "✅ SSL ativado com sucesso" || echo "⚠️  SSL falhou — verifique se DNS aponta para esse servidor"

# Auto-renovação
systemctl enable certbot.timer 2>/dev/null || true

# ─── 7. INICIAR APLICAÇÃO ────────────────────────────────────
echo "🚀 [7/7] Iniciando aplicação..."

cd $APP_DIR
docker compose up -d

echo ""
echo "⏳ Aguardando containers iniciarem (60s)..."
sleep 60

echo ""
echo "📊 Status dos containers:"
docker compose ps

# Seed de dados de demonstração
echo ""
echo "🌱 Populando banco de dados..."
docker compose exec -T api sh -c "npx ts-node prisma/seed.ts" 2>/dev/null || echo "ℹ️  Seed será disponível após build completo"

# ─── RESUMO ──────────────────────────────────────────────────
echo ""
echo "╔══════════════════════════════════════════════════╗"
echo "║           INSTALAÇÃO CONCLUÍDA! 🎉               ║"
echo "╠══════════════════════════════════════════════════╣"
echo "║                                                  ║"
echo "║  🌐 App:     https://app.minhaos.com             ║"
echo "║  📚 API:     https://app.minhaos.com/api/v1      ║"
echo "║  📖 Swagger: https://app.minhaos.com/api/docs    ║"
echo "║                                                  ║"
echo "║  📧 Login:   admin@demo.com                      ║"
echo "║  🔑 Senha:   senha123                            ║"
echo "║                                                  ║"
echo "╚══════════════════════════════════════════════════╝"
echo ""
echo "⚠️  IMPORTANTE: Troque a senha padrão após o 1º login!"
echo ""
echo "📋 Senhas do servidor (guarde em local seguro):"
echo "   DB Password: ${DB_PASS}"
echo "   (salvas em /opt/manutix/.env)"
echo ""
