#!/bin/bash

# Configuration
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
EXTENSIONS_ROOT="$REPO_ROOT/packages"
TARGET_DIR="$REPO_ROOT/packages/cms-infra/extensions"

# List of extensions to sync - including modules and endpoints
EXTENSIONS=(
  "acquisition"
  "acquisition-manager"
  "customer-manager"
  "feedback-commander"
  "people-manager"
)

echo "🚀 Starting extension sync..."

# Ensure target directory exists
mkdir -p "$TARGET_DIR"

for EXT in "${EXTENSIONS[@]}"; do
  EXT_PATH="$EXTENSIONS_ROOT/$EXT"
  
  if [ -d "$EXT_PATH" ]; then
    echo "📦 Building $EXT..."
    
    # Build the extension
    # We use --if-present to avoid errors if build script is missing
    (cd "$EXT_PATH" && pnpm build)
    
    # Create target directory for this extension
    # Directus expects extensions to be in subdirectories matching their name
    mkdir -p "$TARGET_DIR/$EXT"
    
    echo "🚚 Syncing $EXT to $TARGET_DIR/$EXT..."
    
    # Clean target first to avoid ghost files
    rm -rf "${TARGET_DIR:?}/$EXT"/*
    
    # Copy build artifacts and package metadata
    # Some extensions have index.js in root after build, some use dist/
    # We check for index.js and package.json
    if [ -f "$EXT_PATH/index.js" ]; then
        cp "$EXT_PATH/index.js" "$TARGET_DIR/$EXT/"
    fi
    
    if [ -f "$EXT_PATH/package.json" ]; then
        cp "$EXT_PATH/package.json" "$TARGET_DIR/$EXT/"
    fi

    if [ -d "$EXT_PATH/dist" ]; then
        cp -r "$EXT_PATH/dist" "$TARGET_DIR/$EXT/"
    fi
    
    # Sync node_modules if they exist (sometimes needed if not everything is bundled)
    if [ -d "$EXT_PATH/node_modules" ]; then
       echo "📚 Syncing node_modules for $EXT..."
       rsync -a --delete "$EXT_PATH/node_modules/" "$TARGET_DIR/$EXT/node_modules/"
    fi

    echo "✅ $EXT synced."
  else
    echo "❌ Extension source not found: $EXT_PATH"
  fi
done

echo "✨ Extension sync complete!"
