#!/bin/bash
set -e

echo "========================================="
echo "Building & Deploying to Solaria"
echo "========================================="

# Build locally first
echo ""
echo "Step 1: Building backend locally..."
cd backend
cargo build --release 2>&1 | tail -20

if [ ! -f target/release/normogen-backend ]; then
    echo "❌ Build failed!"
    exit 1
fi

echo "✅ Build successful"

# Stop existing backend on Solaria
echo ""
echo "Step 2: Stopping existing backend on Solaria..."
ssh alvaro@solaria "pkill -f normogen-backend || true"

# Copy the binary to Solaria
echo ""
echo "Step 3: Copying binary to Solaria..."
scp target/release/normogen-backend alvaro@solaria:~/normogen-backend

# Start MongoDB if needed
echo ""
echo "Step 4: Setting up MongoDB..."
ssh alvaro@solaria bash << 'ENDSSH'
if ! pgrep -x "mongod" > /dev/null; then
    echo "Starting MongoDB..."
    mkdir -p ~/mongodb_data
    mongod --dbpath ~/mongodb_data --fork --logpath ~/mongodb.log
    sleep 3
else
    echo "✅ MongoDB already running"
fi
ENDSSH

# Start the backend
echo ""
echo "Step 5: Starting backend on Solaria..."
ssh alvaro@solaria bash << 'ENDSSH'
export DATABASE_URI="mongodb://localhost:27017"
export DATABASE_NAME="normogen"
export JWT_SECRET="production-secret-key"
export SERVER_HOST="0.0.0.0"
export SERVER_PORT="8080"
export RUST_LOG="normogen_backend=debug,tower_http=debug,axum=debug"

nohup ~/normogen-backend > ~/normogen-backend.log 2>&1 &
sleep 5

if pgrep -f "normogen-backend" > /dev/null; then
    echo "✅ Backend started (PID: $(pgrep -f 'normogen-backend'))"
else
    echo "❌ Backend failed to start"
    tail -50 ~/normogen-backend.log
    exit 1
fi

# Health check
echo ""
echo "Testing health endpoint..."
sleep 2
curl -s http://localhost:8080/health
echo ""

ENDSSH

echo ""
echo "========================================="
echo "✅ Deployment complete!"
echo "========================================="
