#!/bin/bash

# =============================================================================
# Build 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:"
    echo "  $0 auth-service        (Node.js)"
    echo "  $0 mission-service-net (.NET)"
    exit 1
fi

# 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

echo "🔨 Building $SERVICE..."

# -----------------------------------------------------------------------------
# Detect Project Type & Build
# -----------------------------------------------------------------------------

BUILT=false

# 1. Check for Node.js (package.json)
if [ -f "$SERVICE_PATH/package.json" ]; then
    echo "   📦 Detected Node.js project"
    # EN: Build specific service using pnpm filter
    # VI: Build service cụ thể sử dụng pnpm filter
    if pnpm --filter "@goodgo/$SERVICE" build; then
        BUILT=true
    fi
fi

# 2. Check for .NET (Solution or CSPROJ)
if [ -f "$SERVICE_PATH"/*.sln ] || compgen -G "$SERVICE_PATH/*.sln" > /dev/null || \
   [ -f "$SERVICE_PATH"/*.csproj ] || compgen -G "$SERVICE_PATH/src/*.sln" > /dev/null; then
    
    # If not already built (or if it's a mixed project, we might want to build both, 
    # but usually it's one or the other. Let's assume .NET if found).
    # If we already built Node, we still try .NET just in case? 
    # Let's say yes for completeness, though rare.
    
    echo "   📦 Detected .NET project"
    
    TARGET_BUILD="$SERVICE_PATH"
    if [ -d "$SERVICE_PATH/src" ] && compgen -G "$SERVICE_PATH/src/*.sln" > /dev/null; then
        TARGET_BUILD="$SERVICE_PATH/src"
    fi
    
    if dotnet build "$TARGET_BUILD"; then
        BUILT=true
    fi
fi

if [ "$BUILT" = true ]; then
    echo "✅ Build completed for $SERVICE!"
else
    echo "❌ Could not determine how to build $SERVICE (no package.json or .sln/.csproj found)"
    exit 1
fi
