#!/bin/bash

# =============================================================================
# Start Single Service (Polyglot)
# =============================================================================

set -e

SERVICE=$1

# EN: Validate arguments
# VI: Xác thực tham số
if [ -z "$SERVICE" ]; then
    echo "Usage: $0 <service-name>"
    echo "Example: $0 iam-service"
    exit 1
fi

echo "🚀 Starting $SERVICE..."

# EN: Check if service exists
# VI: Kiểm tra xem service có tồn tại không
SERVICE_PATH="services/$SERVICE"
if [ ! -d "$SERVICE_PATH" ]; then
    echo "❌ Service $SERVICE not found in services/"
    exit 1
fi

cd "$SERVICE_PATH"

STARTED=false

# 1. Check for Node.js (package.json)
if [ -f "package.json" ]; then
    echo "   📦 Starting Node.js service..."
    pnpm dev
    STARTED=true
fi

# 2. Check for .NET
# If it's a .NET service, we prefer `dotnet watch run` for hot reload
if [ -f *.sln ] || compgen -G "*.sln" > /dev/null || \
   [ -f *.csproj ] || compgen -G "src/*.sln" > /dev/null; then
    
    echo "   📦 Starting .NET service with Hot Reload..."
    
    # Needs env vars? Often yes.
    # Load env vars from deployments/local/.env.local if not already set?
    # Usually .NET appsettings.Development.json handles this, or we export from .env.local
    
    # Attempt to load .env.local from root
    if [ -f "../../deployments/local/.env.local" ]; then
        echo "   ℹ️  Loading environment variables from deployments/local/.env.local"
        export $(grep -v '^#' ../../deployments/local/.env.local | xargs)
    fi
    
    TARGET_RUN="."
    if [ -d "src" ] && compgen -G "src/*.sln" > /dev/null; then
       # Usually we want to run the API project specifically, not the solution (dotnet run works on project, or solution if single run project)
       # Finding the API project is tricky without hardcoding. 
       # Assume pattern: ServiceName.API or just src/
       
       # Try to find a csproj in src that ends with API.csproj or Service.csproj
       API_PROJECT=$(find src -name "*.API.csproj" | head -n 1)
       if [ -z "$API_PROJECT" ]; then
           API_PROJECT=$(find src -name "*.csproj" | grep -v "Domain" | grep -v "Infrastructure" | head -n 1)
       fi
       
       if [ -n "$API_PROJECT" ]; then
           # We need to run from the project directory or pass --project
           TARGET_RUN="$API_PROJECT"
       else
           TARGET_RUN="src"
       fi
    elif [ -d "src" ]; then
       TARGET_RUN="src"
    fi

    echo "   👉 Running project: $TARGET_RUN"
    dotnet watch run --project "$TARGET_RUN"
    STARTED=true
fi

if [ "$STARTED" = false ]; then
    echo "❌ Could not determine how to start $SERVICE (no package.json or .sln found)"
    exit 1
fi
