#!/bin/bash
# Start Backend API Server as a background service

set -euo pipefail

cd "$(dirname "$0")/.."

# Default configuration
export CHAIN_ID="${CHAIN_ID:-138}"
export PORT="${PORT:-8080}"
export DB_HOST="${DB_HOST:-localhost}"
export DB_PORT="${DB_PORT:-5432}"
export DB_USER="${DB_USER:-explorer}"
export DB_PASSWORD="${DB_PASSWORD:-changeme}"
export DB_NAME="${DB_NAME:-explorer}"
export DB_SSLMODE="${DB_SSLMODE:-disable}"

LOG_FILE="/tmp/explorer_backend_$(date +%Y%m%d_%H%M%S).log"
PID_FILE="/tmp/explorer_backend.pid"

echo "=========================================="
echo "Starting Explorer Backend API Server"
echo "=========================================="
echo ""
echo "Configuration:"
echo "  Chain ID: $CHAIN_ID"
echo "  Port: $PORT"
echo "  Database: $DB_USER@$DB_HOST:$DB_PORT/$DB_NAME"
echo "  Log File: $LOG_FILE"
echo ""

# Check if Go is installed
if ! command -v go &> /dev/null; then
    echo "❌ Error: Go is not installed"
    exit 1
fi

# Check if port is available
if lsof -Pi :$PORT -sTCP:LISTEN -t >/dev/null 2>&1 ; then
    echo "⚠️  Port $PORT is already in use"
    OLD_PID=$(lsof -t -i:$PORT)
    echo "Existing process PID: $OLD_PID"
    read -p "Kill existing process and start new one? (y/N): " -n 1 -r
    echo
    if [[ $REPLY =~ ^[Yy]$ ]]; then
        kill $OLD_PID 2>/dev/null || true
        sleep 2
    else
        exit 1
    fi
fi

# Check database connectivity
echo "Checking database connection..."
PGPASSWORD="$DB_PASSWORD" pg_isready -h "$DB_HOST" -p "$DB_PORT" -U "$DB_USER" >/dev/null 2>&1
if [ $? -eq 0 ]; then
    echo "✅ Database is ready"
else
    echo "⚠️  Warning: Database may not be ready, but continuing..."
fi

# Change to backend directory
cd backend/api/rest/cmd

# Build the server
echo "Building backend server..."
if go build -o api-server main.go 2>&1 | tee -a "$LOG_FILE"; then
    echo "✅ Build successful"
else
    echo "❌ Build failed - check $LOG_FILE for details"
    exit 1
fi

# Start the server in background
echo ""
echo "Starting server on port $PORT in background..."
nohup ./api-server > "$LOG_FILE" 2>&1 &
SERVER_PID=$!

# Save PID
echo $SERVER_PID > "$PID_FILE"

# Wait a moment for server to start
sleep 3

# Check if server is running
if ps -p $SERVER_PID > /dev/null 2>&1; then
    echo "✅ Server started successfully"
    echo "  PID: $SERVER_PID"
    echo "  Log: $LOG_FILE"
    echo "  PID File: $PID_FILE"
    echo ""
    echo "To stop the server:"
    echo "  kill $SERVER_PID"
    echo "  or"
    echo "  kill \$(cat $PID_FILE)"
    echo ""
    echo "To view logs:"
    echo "  tail -f $LOG_FILE"
    echo ""
    
    # Test health endpoint
    sleep 2
    if curl -s "http://localhost:$PORT/health" >/dev/null 2>&1; then
        echo "✅ Health check passed"
    else
        echo "⚠️  Health check failed - server may still be starting"
    fi
else
    echo "❌ Server failed to start - check $LOG_FILE for errors"
    cat "$LOG_FILE"
    exit 1
fi

