#!/bin/bash
#
# clean_run.sh
# 
# Clean environment and run all tests
#

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "$SCRIPT_DIR/../.."

echo "Stopping existing server on port 4000..."
PID=$(lsof -t -i:4000 || true)
if [ -n "$PID" ]; then
    kill $PID || true
    wait $PID 2>/dev/null || true
    echo "Server stopped."
else
    echo "No server running on port 4000."
fi

echo "Cleaning database..."
rm -f /tmp/vb.sqlite

echo "Starting server..."
# Run in background
go run cli/main.go -db.type=sqlite -db.dsn /tmp/vb.sqlite -p 4000 > /tmp/vb_server.log 2>&1 &
SERVER_PID=$!

echo "Server PID: $SERVER_PID"
echo "Waiting for server to start..."

# Wait for port 4000 to be open
max_retries=30
count=0
while ! nc -z localhost 4000; do
    sleep 1
    ((count++))
    if [ $count -ge $max_retries ]; then
        echo "Server failed to start in $max_retries seconds."
        cat /tmp/vb_server.log
        kill $SERVER_PID || true
        exit 1
    fi
done

echo "Server started successfully."

# Run tests
echo "Running tests..."
BASE_URL=http://localhost:4000 bash scripts/tests/run_all.sh
EXIT_CODE=$?

echo "Stopping server..."
kill $SERVER_PID || true

exit $EXIT_CODE
