#!/bin/bash
set -e

echo "🚀 Deploying Normogen Backend to Solaria (Improved)"
echo "===================================================="

# Configuration
REMOTE_HOST="solaria"
REMOTE_DIR="/srv/normogen"
DOCKER_COMPOSE_FILE="docker/docker-compose.improved.yml"

# Colors for output
RED='\\033[0;31m'
GREEN='\\033[0;32m'
YELLOW='\\033[1;33m'
NC='\\033[0m' # No Color

log_info() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

log_warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# Check if JWT_SECRET is set
if [ -z "${JWT_SECRET}" ]; then
    log_error "JWT_SECRET environment variable not set!"
    echo "Usage: JWT_SECRET=your-secret ./backend/deploy-to-solaria-improved.sh"
    echo ""
    echo "Generate a secure secret with:"
    echo "  openssl rand -base64 32"
    exit 1
fi

# Step 1: Build locally
log_info "Step 1: Building backend binary locally..."
cargo build --release
log_info "✅ Build complete"

# Step 2: Create remote directory structure
log_info "Step 2: Setting up remote directory..."
ssh ${REMOTE_HOST} "mkdir -p ${REMOTE_DIR}/docker"
log_info "✅ Directory ready"

# Step 3: Create .env file on remote
log_info "Step 3: Setting up environment variables..."
ssh ${REMOTE_HOST} "cat > ${REMOTE_DIR}/.env << EOF
MONGODB_DATABASE=normogen
JWT_SECRET=${JWT_SECRET}
RUST_LOG=info
SERVER_PORT=8000
SERVER_HOST=0.0.0.0
EOF"
log_info "✅ Environment configured"

# Step 4: Copy improved Docker files to remote
log_info "Step 4: Copying Docker files to remote..."
scp docker/Dockerfile.improved ${REMOTE_HOST}:${REMOTE_DIR}/docker/Dockerfile.improved
scp docker/docker-compose.improved.yml ${REMOTE_HOST}:${REMOTE_DIR}/docker/docker-compose.improved.yml
log_info "✅ Docker files copied"

# Step 5: Stop old containers
log_info "Step 5: Stopping old containers..."
ssh ${REMOTE_HOST} "cd ${REMOTE_DIR} && docker compose down 2>/dev/null || true"
log_info "✅ Old containers stopped"

# Step 6: Start new containers with improved configuration
log_info "Step 6: Starting new containers..."
ssh ${REMOTE_HOST} "cd ${REMOTE_DIR} && docker compose -f ${DOCKER_COMPOSE_FILE} up -d"
log_info "✅ Containers started"

# Step 7: Wait for containers to be healthy
log_info "Step 7: Waiting for containers to stabilize..."
sleep 10
ssh ${REMOTE_HOST} "docker compose -f ${REMOTE_DIR}/${DOCKER_COMPOSE_FILE} ps"
log_info "✅ Container status retrieved"

# Step 8: Test API health endpoint
log_info "Step 8: Testing API health endpoint..."
sleep 5
if curl -f http://solaria.solivarez.com.ar:8001/health > /dev/null 2>&1; then
    log_info "✅ API is responding correctly"
else
    log_warn "⚠️  API health check failed - check logs with:"
    echo "    ssh ${REMOTE_HOST} 'docker logs -f normogen-backend'"
fi

log_info "🎉 Deployment complete!"
echo ""
echo "View logs:"
echo "  ssh ${REMOTE_HOST} 'docker compose -f ${REMOTE_DIR}/${DOCKER_COMPOSE_FILE} logs -f backend'"
echo ""
echo "View status:"
echo "  ssh ${REMOTE_HOST} 'docker compose -f ${REMOTE_DIR}/${DOCKER_COMPOSE_FILE} ps'"
echo ""
echo "Restart services:"
echo "  ssh ${REMOTE_HOST} 'docker compose -f ${REMOTE_DIR}/${DOCKER_COMPOSE_FILE} restart'"
