#!/bin/bash
# Build all BFF proto dependencies and copy DLLs to libs folder
# This script is automatically run before build via Directory.Build.targets

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
LIBS_DIR="$SCRIPT_DIR/libs"
BFF_PROTOS_DIR="$SCRIPT_DIR/../BackOffice.BFF/src/Protobufs"

echo "🔧 Building all proto dependencies..."

# Create libs directory
mkdir -p "$LIBS_DIR"

# All proto projects
PROTO_PROJECTS=(
    "BackOffice.BFF.Common.Protobuf"
    "BackOffice.BFF.Category.Protobuf"
    "BackOffice.BFF.ClubMembership.Protobuf"
    "BackOffice.BFF.Commission.Protobuf"
    "BackOffice.BFF.Configuration.Protobuf"
    "BackOffice.BFF.DiscountCategory.Protobuf"
    "BackOffice.BFF.DiscountOrder.Protobuf"
    "BackOffice.BFF.DiscountProduct.Protobuf"
    "BackOffice.BFF.DiscountShoppingCart.Protobuf"
    "BackOffice.BFF.Health.Protobuf"
    "BackOffice.BFF.Inventory.Protobuf"
    "BackOffice.BFF.ManualPayment.Protobuf"
    "BackOffice.BFF.NetworkMembership.Protobuf"
    "BackOffice.BFF.Otp.Protobuf"
    "BackOffice.BFF.Package.Protobuf"
    "BackOffice.BFF.Products.Protobuf"
    "BackOffice.BFF.ProductTag.Protobuf"
    "BackOffice.BFF.PublicMessage.Protobuf"
    "BackOffice.BFF.Role.Protobuf"
    "BackOffice.BFF.Tag.Protobuf"
    "BackOffice.BFF.User.Protobuf"
    "BackOffice.BFF.UserAddress.Protobuf"
    "BackOffice.BFF.UserOrder.Protobuf"
    "BackOffice.BFF.UserRole.Protobuf"
)

BUILT_COUNT=0
FAILED_COUNT=0

for PROJECT in "${PROTO_PROJECTS[@]}"; do
    PROJECT_DIR="$BFF_PROTOS_DIR/$PROJECT"
    if [ -d "$PROJECT_DIR" ]; then
        echo "📦 Building $PROJECT..."
        if dotnet build "$PROJECT_DIR" -c Release --verbosity quiet 2>/dev/null; then
            # Copy DLL and PDB - check both net9.0 and net8.0
            if [ -f "$PROJECT_DIR/bin/Release/net9.0/$PROJECT.dll" ]; then
                cp "$PROJECT_DIR/bin/Release/net9.0/$PROJECT.dll" "$LIBS_DIR/" && ((BUILT_COUNT++))
                cp "$PROJECT_DIR/bin/Release/net9.0/$PROJECT.pdb" "$LIBS_DIR/" 2>/dev/null || true
            elif [ -f "$PROJECT_DIR/bin/Release/net8.0/$PROJECT.dll" ]; then
                cp "$PROJECT_DIR/bin/Release/net8.0/$PROJECT.dll" "$LIBS_DIR/" && ((BUILT_COUNT++))
                cp "$PROJECT_DIR/bin/Release/net8.0/$PROJECT.pdb" "$LIBS_DIR/" 2>/dev/null || true
            else
                echo "⚠️  DLL not found for: $PROJECT"
                ((FAILED_COUNT++))
            fi
        else
            echo "⚠️  Failed to build: $PROJECT"
            ((FAILED_COUNT++))
        fi
    else
        echo "⚠️  Project not found: $PROJECT"
        ((FAILED_COUNT++))
    fi
done

echo ""
echo "✅ Build complete!"
echo "   Built: $BUILT_COUNT projects"
echo "   Failed: $FAILED_COUNT projects"
echo "   Output: $LIBS_DIR"
echo ""
ls -la "$LIBS_DIR"/*.dll 2>/dev/null | wc -l | xargs -I {} echo "   Total DLLs: {}"
