#!/bin/bash

# Start Backend API Server
# This script starts the Explorer backend API server with proper configuration

set -euo pipefail

# Colors
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
NC='\033[0m'

echo -e "${GREEN}Starting Explorer Backend API Server...${NC}"
echo ""

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

# Check if Go is installed
if ! command -v go &> /dev/null; then
    echo -e "${RED}Error: Go is not installed${NC}"
    echo "Please install Go: https://golang.org/dl/"
    exit 1
fi

# Check if database is accessible
echo -e "${YELLOW}Checking database connection...${NC}"
if command -v psql &> /dev/null; then
    if PGPASSWORD="$DB_PASSWORD" psql -h "$DB_HOST" -p "$DB_PORT" -U "$DB_USER" -d "$DB_NAME" -c "SELECT 1;" &> /dev/null; then
        echo -e "${GREEN}✅ Database connection successful${NC}"
    else
        echo -e "${RED}❌ Database connection failed${NC}"
        echo "Please check your database configuration:"
        echo "  DB_HOST=$DB_HOST"
        echo "  DB_PORT=$DB_PORT"
        echo "  DB_USER=$DB_USER"
        echo "  DB_NAME=$DB_NAME"
        echo ""
        echo "You can set these via environment variables:"
        echo "  export DB_HOST=localhost"
        echo "  export DB_PORT=5432"
        echo "  export DB_USER=explorer"
        echo "  export DB_PASSWORD=your_password"
        echo "  export DB_NAME=explorer"
        exit 1
    fi
else
    echo -e "${YELLOW}⚠️  psql not found, skipping database check${NC}"
fi

# Set environment variables
export CHAIN_ID
export PORT
export DB_HOST
export DB_PORT
export DB_USER
export DB_PASSWORD
export DB_NAME
export DB_SSLMODE

# Change to backend directory
cd "$(dirname "$0")/../backend/api/rest" || exit 1

echo ""
echo -e "${GREEN}Configuration:${NC}"
echo "  Chain ID: $CHAIN_ID"
echo "  Port: $PORT"
echo "  Database: $DB_USER@$DB_HOST:$DB_PORT/$DB_NAME"
echo ""

# Check if server is already running
if lsof -Pi :$PORT -sTCP:LISTEN -t >/dev/null 2>&1 ; then
    echo -e "${YELLOW}⚠️  Port $PORT is already in use${NC}"
    echo "Another process may be running the API server."
    echo "To stop it, run: kill \$(lsof -t -i:$PORT)"
    read -p "Continue anyway? (y/N) " -n 1 -r
    echo
    if [[ ! $REPLY =~ ^[Yy]$ ]]; then
        exit 1
    fi
fi

# Start the server
echo -e "${GREEN}Starting server on port $PORT...${NC}"
echo ""

# Run the server
exec go run main.go

