#!/bin/bash

# Start Backend API Server with environment setup
# This script sets up the environment and starts the backend

set -euo pipefail

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

# Default configuration (can be overridden by environment)
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 "Starting Explorer Backend API Server..."
echo "Configuration:"
echo "  Chain ID: $CHAIN_ID"
echo "  Port: $PORT"
echo "  Database: $DB_USER@$DB_HOST:$DB_PORT/$DB_NAME"
echo ""

# 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

# Start the server
echo "Starting server..."
exec go run *.go

