services:
  # ============================================================================
  # READY SERVICE - Have everything READY
  # ============================================================================
  cms-webportal-playground-ready:
    image: alpine:latest
    container_name: rb-cms-webportal-playground-ready
    # Mounts the shared volume to access the filesystem
    volumes:
      - wp_html:/var/www/html
    env_file:
      - .env
    # This service depends on ALL other services to be healthy and complete first
    depends_on:
      theme-builder:
        condition: service_completed_successfully
      cms-webportal-playground-cli:
        condition: service_completed_successfully  
    command: >
      /bin/sh -c '
        echo "📌 Creating provisioning marker...";
        # Create the .provisioned file here, in the shared volume
        touch /var/www/html/.provisioned;
        
        echo "✅ All provisioning complete - WordPress is ready!";
      '
    restart: "no"

  cms-webportal-playground:
    build:
      context: .
      dockerfile: Dockerfile.cms-webportal
    container_name: rb-cms-webportal-playground
    depends_on:
      cms-webportal-playground-db:
        condition: service_healthy
    ports:
      - "${HOST_PORT:-8080}:80"
    volumes:
      # WordPress core
      - wp_html:/var/www/html

      # Plugin source code (use Docker-managed volume populated from image)
      - datapallas_plugin_build:/var/www/html/wp-content/plugins/datapallas-portal:ro

      # Theme source code (host) — commented out to prefer the builder volume
      # Use the builder-produced theme build so the web container sees the compiled assets
      - datapallas_theme_build:/var/www/html/wp-content/themes/datapallas-theme:ro

      # Writable dirs for WordPress
      - wp_uploads:/var/www/html/wp-content/uploads
      - wp_upgrade:/var/www/html/wp-content/upgrade
    env_file:
      - .env
    restart: unless-stopped
    healthcheck:
      test: ["CMD-SHELL", "test -f /var/www/html/.provisioned && curl -f http://localhost/ -o /dev/null -s || exit 1"]
      interval: 5s
      timeout: 5s
      retries: 300
      start_period: 10s

  cms-webportal-playground-db:
    image: mysql:8.0
    container_name: rb-cms-webportal-playground-db
    volumes:
      - wp_db_data:/var/lib/mysql
      - ./logs-db:/var/log/mysql
    environment:
      MYSQL_ROOT_PASSWORD: ${MYSQL_ROOT_PASSWORD}
      MYSQL_DATABASE:      ${MYSQL_DATABASE}
      MYSQL_USER:          ${MYSQL_USER}
      MYSQL_PASSWORD:      ${MYSQL_PASSWORD}
    restart: unless-stopped
    healthcheck:
      test: ["CMD", "mysqladmin", "ping", "-h", "localhost", "-u", "root", "-p${MYSQL_ROOT_PASSWORD}"]
      interval: 5s
      timeout: 5s
      retries: 30
      start_period: 5s

  cms-webportal-playground-cli:
    image: wordpress:cli-2.12.0-php8.4
    container_name: rb-cms-webportal-playground-cli
    user: "0:0"
    env_file:
      - .env
    environment:
      - WP_CLI_ALLOW_ROOT=1
    depends_on:
      cms-webportal-playground:
        condition: service_started
      theme-builder:
        condition: service_completed_successfully
    volumes:
      # WordPress core
      - wp_html:/var/www/html

      # Plugin source code (use Docker-managed volume populated from image)
      - datapallas_plugin_build:/var/www/html/wp-content/plugins/datapallas-portal

      # Use the builder-produced theme build so the CLI and web see the same compiled assets
      - datapallas_theme_build:/var/www/html/wp-content/themes/datapallas-theme

    restart: "no"
    command: >
      /bin/sh -c '
        # Early exit if already provisioned (saves doing effort on restarts)
        if [ -f /var/www/html/.provisioned ]; then
          echo "✅ Already provisioned (.provisioned exists). Skipping CLI provisioning.";
          exit 0;
        fi

        echo "⏳ Waiting for Wordpress core files…";
        while [ ! -f /var/www/html/wp-settings.php ]; do sleep 2; done

        echo "🔐 Waiting for wp-content to settle…";
        # Wait for directories to be properly created
        sleep 5

        echo "🕓 Waiting for the database to be responsive…";
        until mysqladmin ping \
          --host="${WORDPRESS_DB_HOST}" \
          --user="${WORDPRESS_DB_USER}" \
          --password="${WORDPRESS_DB_PASSWORD}" \
          --protocol=TCP --skip-ssl --silent > /dev/null 2>&1; do
          sleep 2;
        done

        sleep 5;

        echo "🚀 Checking WordPress install...";

        if ! wp core is-installed; then
          wp core install \
            --path="/var/www/html" \
            --url="${WP_SITE_URL}" \
            --title="${WP_SITE_TITLE}" \
            --admin_user="${WP_ADMIN_USER}" \
            --admin_password="${WP_ADMIN_PASSWORD}" \
            --admin_email="${WP_ADMIN_EMAIL}";

          echo "🧹 Removing default bundled plugins…";
          wp plugin is-installed akismet && wp plugin delete akismet || true
          wp plugin is-installed hello   && wp plugin delete hello   || true

          # ================================================================
          # PODS FRAMEWORK - Install FIRST (dependency for datapallas-portal)
          # ================================================================
          echo "📦 Installing Pods framework (required by datapallas-portal)…";
          if ! wp plugin is-installed pods; then
            wp plugin install pods --version=3.3.3 --activate
          else
            wp plugin is-active pods || wp plugin activate pods || true
          fi
          # Small delay to let Pods initialize its tables
          sleep 5

          
          # =========================================================================
          # IDEMPOTENT PROVISIONING (runs every time, safe to re-run)
          # =========================================================================
          echo "🔐 Ensuring custom roles…";
          wp role exists employee || wp role create employee 'Employee' --clone=subscriber
          wp role exists customer || wp role create customer 'Customer' --clone=subscriber
        
          sleep 2

          echo "🎨 Activating datapallas-theme…";
          # Check if theme exists before trying to activate
          if wp theme is-installed datapallas-theme; then
            wp theme activate datapallas-theme
          else
            echo "Theme not found yet, will be activated after build."
          fi
        
          sleep 2

          echo "🎨 Activating datapallas-portal…";

          if wp plugin is-installed datapallas-portal; then
            wp plugin activate datapallas-portal
          else
            echo "Plugin not found yet, will be activated later."
          fi
          
          # ================================================================
          # OTHER PLUGINS (uncomment as needed)
          # ================================================================

          # echo "== Installing Site and Admin Management Plugins ==";
          # ensure matomo 5.3.1
          # ensure burst-statistics 2.1.0
          # ensure jwt-authentication-for-wp-rest-api 1.3.8
          # ensure members 3.2.18
          # ensure adminimize 1.11.11
          # ensure wp-phpmyadmin-extension 5.2.2.01
          # ensure updraftplus 1.25.6
          # ensure loginpress 4.0.1
          # ensure oauth2-provider 4.4.0
          # ensure redux-framework 4.5.7

          # echo "== Installing Spam / Security Plugins ==";
          # ensure antispam-bee 2.11.7

          # echo "== Installing Contact Forms and Enhancements Plugins ==";
          # ensure forminator 1.44.3
          # ensure contact-form-7 6.1
          # ensure contact-form-7-paypal-add-on 2.4.3
          # ensure contact-form-cfdb7 1.3.1
          # ensure contact-form-7-simple-recaptcha 0.1.6
          # ensure cf7-grid-layout 4.15.8

          # echo "== Installing Email Management Plugins ==";
          # ensure fluent-smtp 2.2.90

          echo "== Installing Developer Tools and Utilities Plugins ==";
          # Query Monitor plugin
          if ! wp plugin is-installed query-monitor; then
            wp plugin install query-monitor --version=3.20.0
          fi
          # ensure font-awesome 5.0.2
          # ensure codepress-admin-columns 4.7.7

          # echo "== Installing Social / Community (Optional) Plugins ==";
          # ensure buddypress 14.3.4

          # echo "== Installing LMS / Donation (Optional) Plugins ==";
          # ensure give 4.4.0
          # ensure tutor 3.6.3
          # ensure learnpress 4.2.8.7.3

          # echo "== Installing Search & Indexing (Optional) Plugins ==";
          # ensure facetwp 4.3.2
          # ensure relevanssi 4.22.1
          # ensure add-search-to-menu 1.3.1
          # ensure search-filter 1.2.16
          # ensure elasticpress 5.0.3

          # echo "== Installing Permalinks / Structure (Optional) Plugins ==";
          # ensure custom-post-type-permalinks 3.5.1

          echo "🔗 Setting permalink structure to /%postname%/…";
          wp rewrite structure "/%postname%/" --hard;
          wp rewrite flush --hard;

          echo "🔧 Updating site URLs…";
          wp option update home    "${WP_SITE_URL}";
          wp option update siteurl "${WP_SITE_URL}";

          echo "📌 First-run provisioning complete.";
        fi

        # Demo users, Pods CPT, and sample data are now provisioned automatically
        # by the DataPallas Portal plugin when WordPress loads (via Provisioner class).
        # This eliminates dependency on fragile shell script execution.

        echo "✅ CLI provisioning complete.";
      '

  # ============================================================================
  # THEME BUILDER - Compiles theme assets (CSS, JS)
  # ============================================================================
  theme-builder:
    build:
      context: .
      dockerfile: Dockerfile.theme-builder
    container_name: rb-theme-builder
    user: "0:0"
    depends_on:
      cms-webportal-playground:
        condition: service_started
    working_dir: /theme-src
    volumes:
      - wp_html:/var/www/html
      - datapallas_theme_build:/theme-dist
    env_file:
      - .env
    environment:
      - FORCE_BUILD=${FORCE_BUILD:-false}
    command: >
      /bin/sh -c '
        set -e

        # Ensure we are in the theme folder (defensive)
        cd /theme-src

        # If we are forcing a build, remove the old marker to ensure the full cycle completes
        if [ "${FORCE_BUILD}" = "true" ]; then
          echo "🔄 FORCE_BUILD is true. Removing old .provisioned marker to build the theme.";
          rm -f /var/www/html/.provisioned
        fi
        
        # Early exit if already provisioned (saves doing effort on restarts)
        if [ -f /var/www/html/.provisioned ]; then
          echo "✅ Already provisioned (.provisioned exists). Skipping CLI provisioning.";
          exit 0;
        fi
        
        echo "⏳ Waiting for theme sources (package.json)...";
        
        COUNT=0;
        while [ ! -f /theme-src/package.json ] && [ $$COUNT -lt 3 ]; do
          COUNT=$$((COUNT+1));
          sleep 1;
        done

        if [ ! -f /theme-src/package.json ]; then
          echo "❌ ERROR: /theme-src/package.json not found after timeout; exiting.";
          exit 1;
        fi
        
        echo "🔨 Starting theme asset build...";

        if [ ! -d "node_modules" ]; then
          echo "📦 Installing Node.js dependencies...";
          # Try a clean ci install first (fast & reproducible). If the lockfile is out-of-sync
          # fall back to `npm install` which updates the lockfile and succeeds in this environment.
          if ! npm ci --no-audit --no-fund --legacy-peer-deps; then
            echo "🔁 npm ci failed; falling back to npm install (this will update package-lock.json)";
            npm install --no-audit --no-fund --legacy-peer-deps;
          fi
        fi

        npm install -g cross-env;
          
        echo "🔨 Running production build (Tailwind & esbuild)...";
        npm run production;
        
        echo "📦 Publishing built theme to shared volume (/theme-dist)...";
        # Copy built theme output into the build volume so web/cli can consume it
        cp -R /theme-src/theme/* /theme-dist/ || true
        chown -R 33:33 /theme-dist
                          
        chown -R 33:33 /theme-src
        
        echo "✅ Theme build complete!";
      '
    restart: "no"

volumes:
  wp_html:
  datapallas_theme_build:
  datapallas_plugin_build:
  wp_uploads:
  wp_upgrade:
  wp_db_data: