#!/bin/bash

# Start Backend API Server - Final Version
# This script properly builds and starts the backend server

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}"

echo "=========================================="
echo "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 ""

# 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"
    echo "To stop existing process: kill \$(lsof -t -i:$PORT)"
    exit 1
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; then
    echo "✅ Build successful"
else
    echo "❌ Build failed"
    exit 1
fi

# Start the server
echo ""
echo "Starting server on port $PORT..."
echo "Press Ctrl+C to stop"
echo ""
exec ./api-server

