#!/bin/bash
# =============================================================================
# Cannamanage — Manual Production Deploy Script
# =============================================================================
# Usage: ./deploy/deploy.sh
# Run from: /opt/cannamanage on the production server
# =============================================================================
set -euo pipefail

DEPLOY_DIR="/opt/cannamanage"
COMPOSE_FILE="docker-compose.prod.yml"

cd "$DEPLOY_DIR"

echo "=== Cannamanage Deploy — $(date) ==="
echo ""

# Pull latest code
echo "[1/5] Pulling latest code..."
git pull origin main

# Build images
echo "[2/5] Building Docker images..."
docker compose -f "$COMPOSE_FILE" build --no-cache

# Bring up services (rolling restart)
echo "[3/5] Starting services..."
docker compose -f "$COMPOSE_FILE" up -d

# Wait for backend health
echo "[4/5] Waiting for health check..."
sleep 15

RETRIES=5
for i in $(seq 1 $RETRIES); do
    if curl -sf http://127.0.0.1:8080/actuator/health > /dev/null 2>&1; then
        echo "  ✅ Backend healthy"
        break
    fi
    if [ "$i" -eq "$RETRIES" ]; then
        echo "  ❌ Backend health check failed after $RETRIES attempts!"
        echo ""
        echo "=== Recent logs ==="
        docker compose -f "$COMPOSE_FILE" logs --tail=30 backend
        exit 1
    fi
    echo "  Attempt $i/$RETRIES — waiting 5s..."
    sleep 5
done

# Verify frontend
if curl -sf http://127.0.0.1:3000 > /dev/null 2>&1; then
    echo "  ✅ Frontend healthy"
else
    echo "  ⚠️ Frontend not responding (may still be starting)"
fi

# Cleanup old images
echo "[5/5] Cleaning up old images..."
docker image prune -f --filter "until=168h" 2>/dev/null || true

echo ""
echo "=== Deploy successful — $(date) ==="
echo "    URL: https://cannamanage.plate-software.de"
