#!/bin/bash

set -e

echo "=========================================="
echo "Building and Deploying to Solaria"
echo "=========================================="

# Build the backend
echo "Step 1: Building backend..."
cd backend
cargo build --release

# Copy to Solaria
echo "Step 2: Copying binary to Solaria..."
scp target/release/normogen-backend alvaro@solaria:/tmp/normogen-backend-new

# Deploy on Solaria
echo "Step 3: Deploying on Solaria..."
ssh alvaro@solaria bash << 'EOSSH'
# Stop the container
docker stop normogen-backend

# Copy the new binary into the container
docker cp /tmp/normogen-backend-new normogen-backend:/app/normogen-backend

# Make it executable
docker exec normogen-backend chmod +x /app/normogen-backend

# Start the container
docker start normogen-backend

# Wait for startup
sleep 5

# Health check
echo "Health check:"
curl -s http://localhost:8001/health
echo ""
EOSSH

echo ""
echo "=========================================="
echo "✅ Deployment Complete!"
echo "=========================================="
echo ""

# Run tests
echo "Running comprehensive tests..."
ssh alvaro@solaria 'bash -s' < backend/phase27-test.sh
