#!/bin/bash
set -e

echo "========================================="
echo "Deploying & Testing on Solaria"
echo "========================================="

ssh alvaro@solaria bash << 'ENDSSH'
set -e

cd /home/alvaro/normogen/backend

# Start MongoDB if not running
if ! pgrep -x "mongod" > /dev/null; then
    echo "Starting MongoDB..."
    mkdir -p ~/mongodb_data
    mongod --dbpath ~/mongodb_data --fork --logpath ~/mongodb.log
    sleep 3
fi

# Stop existing backend
if pgrep -f "normogen-backend" > /dev/null; then
    echo "Stopping existing backend..."
    pkill -f "normogen-backend" || true
    sleep 2
fi

# Set environment
export DATABASE_URI="mongodb://localhost:27017"
export DATABASE_NAME="normogen"
export JWT_SECRET="test-secret-key"
export SERVER_HOST="0.0.0.0"
export SERVER_PORT="8080"
export RUST_LOG="debug"

# Build
echo "Building backend..."
cargo build --release 2>&1 | tail -10

# Start backend
echo "Starting backend..."
nohup ./target/release/normogen-backend > ~/normogen-backend.log 2>&1 &
sleep 5

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

# Health check
echo ""
echo "Health check..."
curl -s http://localhost:8080/health

ENDSSH

echo ""
echo "========================================="
echo "Running comprehensive tests..."
echo "========================================="
echo ""

# Copy and run test script
scp backend/comprehensive-test.sh alvaro@solaria:/tmp/
ssh alvaro@solaria "chmod +x /tmp/comprehensive-test.sh && /tmp/comprehensive-test.sh"

