#!/usr/bin/env bash
set -euo pipefail

# ─── Config ──────────────────────────────────────────────────────────────────
SERVER="opc@163.176.236.167"
REMOTE_DIR="/home/opc/licitatche"
PROJECT_DIR="$(cd "$(dirname "$0")/.." && pwd)"

echo "🚀 Deploy Licitatche → $SERVER"
echo ""

# ─── 1. Build Go binary para linux/arm64 ────────────────────────────────────
echo "🔨 [1/6] Compilando API Go para linux/arm64..."
cd "$PROJECT_DIR/back-end"
CGO_ENABLED=0 GOOS=linux GOARCH=arm64 go build -ldflags="-s -w" -o api-linux-arm64 ./cmd/api/...
echo "  ✅ Binário Go compilado ($(du -h api-linux-arm64 | cut -f1))"

# ─── 2. Build Frontend Nuxt ─────────────────────────────────────────────────
echo ""
echo "🔨 [2/6] Compilando Frontend Nuxt..."
cd "$PROJECT_DIR/front-end"
NUXT_PUBLIC_API_BASE="http://163.176.236.167/api/v1" npx nuxi build 2>&1 | tail -5
echo "  ✅ Frontend compilado"

# ─── 3. Verificar Docker no servidor ────────────────────────────────────────
echo ""
echo "📦 [3/6] Verificando Docker no servidor..."
ssh "$SERVER" 'bash -s' <<'INSTALL_DOCKER'
if command -v docker &>/dev/null && docker compose version &>/dev/null; then
    echo "  ✅ Docker e Docker Compose já instalados"
else
    echo "  📥 Instalando Docker..."
    sudo dnf install -y dnf-utils 2>/dev/null || true
    sudo dnf config-manager --add-repo https://download.docker.com/linux/rhel/docker-ce.repo 2>/dev/null || true
    sudo dnf install -y docker-ce docker-ce-cli containerd.io docker-compose-plugin 2>/dev/null
    sudo systemctl enable docker
    sudo systemctl start docker
    sudo usermod -aG docker "$USER"
    echo "  ✅ Docker instalado"
fi
INSTALL_DOCKER

# ─── 4. Enviar arquivos ─────────────────────────────────────────────────────
echo ""
echo "📤 [4/6] Enviando projeto para o servidor..."
ssh "$SERVER" "mkdir -p $REMOTE_DIR"

rsync -avz --progress --delete \
    --exclude 'node_modules' \
    --exclude '.nuxt' \
    --exclude '.data' \
    --exclude '.git' \
    --exclude '*.pdf' \
    --exclude 'back-end/.env' \
    --exclude 'front-end/app' \
    --exclude 'front-end/public' \
    --exclude 'vendor' \
    "$PROJECT_DIR/" "$SERVER:$REMOTE_DIR/"

# ─── 5. Enviar .env de produção ─────────────────────────────────────────────
echo ""
echo "🔐 [5/6] Configurando variáveis de ambiente..."
scp "$PROJECT_DIR/.env.prod" "$SERVER:$REMOTE_DIR/.env"

# ─── 6. Build containers e start ────────────────────────────────────────────
echo ""
echo "🐳 [6/6] Construindo e iniciando containers..."
ssh "$SERVER" "bash -s" <<REMOTE_START
cd $REMOTE_DIR

# Abrir portas no firewall (Oracle Linux)
sudo firewall-cmd --permanent --add-service=http 2>/dev/null || true
sudo firewall-cmd --permanent --add-port=3000/tcp 2>/dev/null || true
sudo firewall-cmd --permanent --add-port=8080/tcp 2>/dev/null || true
sudo firewall-cmd --reload 2>/dev/null || true
sudo iptables -I INPUT -p tcp --dport 80 -j ACCEPT 2>/dev/null || true

# Build & deploy
docker compose -f docker-compose.prod.yml down 2>/dev/null || true
docker compose -f docker-compose.prod.yml build
docker compose -f docker-compose.prod.yml up -d

echo ""
echo "⏳ Aguardando serviços ficarem prontos..."
sleep 15

echo ""
echo "=== Status dos containers ==="
docker compose -f docker-compose.prod.yml ps
echo ""
echo "=== Logs API (últimas 10 linhas) ==="
docker compose -f docker-compose.prod.yml logs --tail=10 api 2>&1 || true
echo ""
echo "=== Logs Frontend (últimas 10 linhas) ==="
docker compose -f docker-compose.prod.yml logs --tail=10 front 2>&1 || true
echo ""
echo "=== Logs Migrate ==="
docker compose -f docker-compose.prod.yml logs migrate 2>&1 || true

echo ""
echo "✅ Deploy concluído!"
echo "🌐 Acesse: http://163.176.236.167"
REMOTE_START

# Limpar binário local
rm -f "$PROJECT_DIR/back-end/api-linux-arm64"

echo ""
echo "═══════════════════════════════════════════"
echo "  ✅ Deploy finalizado!"
echo "  🌐 http://163.176.236.167"
echo "═══════════════════════════════════════════"
