#!/bin/bash

echo "=========================================="
echo "Normogen Deployment & Testing Script"
echo "=========================================="
echo ""

# Step 1: Push to remote
echo "Step 1: Pushing to remote..."
git push origin main
if [ $? -ne 0 ]; then
    echo "✗ Git push failed"
    exit 1
fi
echo "✓ Git push successful"
echo ""

# Step 2: Connect to Solaria and update
echo "Step 2: Updating Solaria..."
ssh solaria 'cd /srv/normogen && git pull'
if [ $? -ne 0 ]; then
    echo "✗ Git pull on Solaria failed"
    exit 1
fi
echo "✓ Code updated on Solaria"
echo ""

# Step 3: Build new container
echo "Step 3: Building Docker container..."
ssh solaria 'cd /srv/normogen && docker compose -f docker/docker-compose.improved.yml build backend'
if [ $? -ne 0 ]; then
    echo "✗ Docker build failed"
    exit 1
fi
echo "✓ Docker build successful"
echo ""

# Step 4: Restart containers
echo "Step 4: Restarting containers..."
ssh solaria 'cd /srv/normogen && docker compose -f docker/docker-compose.improved.yml down && docker compose -f docker/docker-compose.improved.yml up -d'
if [ $? -ne 0 ]; then
    echo "✗ Container restart failed"
    exit 1
fi
echo "✓ Containers restarted"
echo ""

# Step 5: Wait for container to be healthy
echo "Step 5: Waiting for backend to be healthy..."
sleep 10
ssh solaria 'docker ps | grep normogen'
echo ""

# Step 6: Run API tests
echo "Step 6: Running API tests..."
chmod +x test-medication-endpoints.sh
./test-medication-endpoints.sh
echo ""

echo "=========================================="
echo "Deployment & Testing Complete"
echo "=========================================="
