#!/bin/bash

# =============================================================================
# Build All Services (Polyglot: Node.js & .NET)
# =============================================================================

set -e

source "$(dirname "$0")/../utils/os-helper.sh"

echo "🔨 Building all services and apps..."

# -----------------------------------------------------------------------------
# 1. Build Node.js / TypeScript Projects (pnpm workspace)
# -----------------------------------------------------------------------------
echo "📦 Building Node.js packages..."
# EN: Build all packages using pnpm workspace
# VI: Build tất cả các package sử dụng pnpm workspace
if command -v pnpm &> /dev/null; then
    pnpm build
else
    echo "⚠️  pnpm not found. Skipping Node.js build."
fi

# -----------------------------------------------------------------------------
# 2. Build .NET Services
# -----------------------------------------------------------------------------
echo "📦 Building .NET services..."

if command -v dotnet &> /dev/null; then
    # Find all directories in services/ that contain a .sln or .csproj file
    # and do NOT contain a package.json (or we can build both if mixed)
    
    count=0
    
    # EN: Iterate over direct subdirectories of services/
    # VI: Duyệt qua các thư mục con trực tiếp của services/
    for service_dir in services/*; do
        if [ -d "$service_dir" ]; then
            # Check for .NET solution or project files
            if compgen -G "$service_dir/*.sln" > /dev/null || compgen -G "$service_dir/*.csproj" > /dev/null || compgen -G "$service_dir/src/*.sln" > /dev/null; then
                 service_name=$(basename "$service_dir")
                 
                 # Optimization: specific check to avoid building node apps again if they were mixed (unlikely here but safety first)
                 # In this repo, .NET services don't have package.json usually.
                 
                 echo "   👉 Building .NET service: $service_name"
                 # Use dotnet build on the directory (it finds sln/csproj auto) or specific path
                 if compgen -G "$service_dir/*.sln" > /dev/null; then
                     dotnet build "$service_dir" -v m
                 elif [ -d "$service_dir/src" ]; then
                     # Common pattern: service/src/Service.sln
                     dotnet build "$service_dir/src" -v m
                 else
                     dotnet build "$service_dir" -v m
                 fi
                 
                 count=$((count + 1))
            fi
        fi
    done
    
    if [ "$count" -eq 0 ]; then
        echo "   (No .NET services found to build)"
    else
        echo "   ✅ Built $count .NET services."
    fi

else
    echo "⚠️  dotnet SDK not found. Skipping .NET build."
fi

echo "✅ Build completed!"
