#!/bin/bash
set -e

HOST="http://cms.localhost"
EXTENSIONS=("customer-manager" "people-manager" "company-manager" "feedback-commander" "unified-dashboard")

echo "🔍 Verifying extensions at $HOST..."

# 1. Check Main Manifest
MANIFEST=$(curl -s "$HOST/extensions/sources/index.js")

if [ -z "$MANIFEST" ]; then
  echo "❌ Error: Manifest returned empty response."
  exit 1
fi

echo "✅ Manifest loaded (${#MANIFEST} bytes)."

# 2. Check for unexpected 404/500
if echo "$MANIFEST" | grep -q "<!DOCTYPE html>"; then
  echo "❌ Error: Manifest returned HTML (likely 404 or error page) instead of JS."
  exit 1
fi

# 3. Verify each extension is in the bundle
FAILURE=0
for EXT in "${EXTENSIONS[@]}"; do
  # Directus bundles strings usually, or imports them. 
  # We look for the ID or the unique module name from src (e.g. "Customer Manager")
  # Or simply the path matching. 
  
  if echo "$MANIFEST" | grep -q "$EXT"; then
    echo "✅ Found '$EXT' in manifest."
  else
    echo "❌ MISSING '$EXT' in manifest!"
    FAILURE=1
  fi
done

if [ $FAILURE -eq 1 ]; then
  echo "🚨 VERIFICATION FAILED: One or more extensions are missing from the public bundle."
  exit 1
else
  echo "🎉 ALL EXTENSIONS VERIFIED."
  exit 0
fi
