#!/usr/bin/env bash
#
# Provision the sg-test-automation Docker stack for the Playwright suite:
#   - boots WordPress + MariaDB (docker compose)
#   - installs WP core + WooCommerce, activates StoreGrowth
#   - enables pretty permalinks (required by /wp-json/ routes)
#   - creates an Application Password for the api project
#   - seeds published products so storefront tests have something to assert
#   - writes tests/e2e/.env with the resulting BASE_URL + credentials
#
# Idempotent: safe to re-run. Wipe everything with `docker compose down -v`.
set -euo pipefail

cd "$(dirname "$0")/.."   # -> tests/e2e

BASE_URL="http://localhost:8888"
ADMIN_USER="admin"
ADMIN_PASS="password"
ADMIN_EMAIL="admin@example.com"

# Pro license key, preserved across .env regeneration. Read from the environment
# or the existing .env so re-running setup keeps it. Used to activate Pro.
LICENSE_KEY="${LICENSE_KEY:-$(grep -E '^LICENSE_KEY=' .env 2>/dev/null | cut -d= -f2- | tr -d '\r' || true)}"

# Run a WP-CLI command inside the one-off cli container.
wp() { docker compose run --rm -T cli wp "$@"; }
# Same, but with the license key exposed to the container (for provisioning).
wp_licensed() { docker compose run --rm -T -e LICENSE_KEY="$LICENSE_KEY" cli wp "$@"; }

echo "==> Booting containers (db + wordpress)…"
docker compose up -d db wordpress

echo "==> Waiting for WordPress (apache) to serve…"
for i in $(seq 1 60); do
  code="$(curl -s -o /dev/null -w '%{http_code}' "$BASE_URL/wp-login.php" || true)"
  # Pre-install WP 302-redirects to install.php; any 2xx/3xx means apache is up.
  case "$code" in 2??|3??) echo "    up (HTTP $code)"; break ;; esac
  sleep 2
  [ "$i" = "60" ] && { echo "WordPress did not come up in time" >&2; exit 1; }
done

echo "==> Waiting for wp-config + DB to be reachable from CLI…"
for i in $(seq 1 30); do
  if wp db check >/dev/null 2>&1; then echo "    db reachable"; break; fi
  sleep 2
  [ "$i" = "30" ] && { echo "DB not reachable from CLI" >&2; exit 1; }
done

if wp core is-installed >/dev/null 2>&1; then
  echo "==> WordPress already installed — skipping core install."
else
  echo "==> Installing WordPress core…"
  wp core install \
    --url="$BASE_URL" \
    --title="StoreGrowth E2E" \
    --admin_user="$ADMIN_USER" \
    --admin_password="$ADMIN_PASS" \
    --admin_email="$ADMIN_EMAIL" \
    --skip-email
fi

# Application Passwords are refused over plain HTTP unless the env type is local.
echo "==> Ensuring WP_ENVIRONMENT_TYPE=local (enables App Passwords over HTTP)…"
wp config set WP_ENVIRONMENT_TYPE local >/dev/null 2>&1 || true

echo "==> Installing + activating WooCommerce…"
wp plugin is-installed woocommerce >/dev/null 2>&1 || wp plugin install woocommerce --force >/dev/null
wp plugin activate woocommerce >/dev/null

echo "==> Installing + activating the Storefront theme (official WooCommerce theme)…"
wp theme is-installed storefront >/dev/null 2>&1 || wp theme install storefront >/dev/null
wp theme activate storefront >/dev/null

echo "==> Activating StoreGrowth (Sales Booster)…"
wp plugin activate storegrowth-sales-booster >/dev/null

echo "==> Installing + activating WP-API Basic-Auth (plain Basic auth for REST)…"
# Lets the api project authenticate with the admin user/password directly.
wp plugin is-active basic-auth >/dev/null 2>&1 || \
  wp plugin install "https://github.com/WP-API/Basic-Auth/archive/refs/heads/master.zip" --activate >/dev/null

# Activate the Pro plugin if it is mounted (docker-compose mounts the sibling
# plugin). Done in its own step so it is loaded by the time provisioning runs
# the Appsero license activation.
if wp plugin is-installed storegrowth-sales-booster-pro >/dev/null 2>&1; then
  echo "==> Activating StoreGrowth Pro…"
  wp plugin activate storegrowth-sales-booster-pro >/dev/null
  [ -n "$LICENSE_KEY" ] && echo "    (will activate Pro license from \$LICENSE_KEY during provisioning)" || \
    echo "    (no LICENSE_KEY set — Pro features stay locked; add it to .env)"
fi

# Shared, environment-agnostic site config (same script CI runs via wp-env):
# pretty permalinks, publish storefront, classic checkout, activate ALL modules,
# seed products, mark initial setup complete. See bin/provision-site.php.
echo "==> Provisioning the site (all modules, products, classic checkout, Pro license)…"
wp_licensed eval-file /var/www/html/wp-content/plugins/storegrowth-sales-booster/tests/e2e/bin/provision-site.php

echo "==> Writing tests/e2e/.env…"
# With Basic-Auth active, the REST API accepts the admin user/password directly,
# so no Application Password is needed (env.ts falls back to WP_ADMIN_PASSWORD).
cat > .env <<EOF
# Generated by bin/setup-docker.sh for the sg-test-automation Docker stack.
BASE_URL=$BASE_URL

WP_ADMIN_USER=$ADMIN_USER
WP_ADMIN_PASSWORD=$ADMIN_PASS

# REST auth: WP-API Basic-Auth accepts the admin credentials directly.
WP_API_USER=$ADMIN_USER

# StoreGrowth Pro license key (Appsero). Activated during provisioning to unlock
# Pro features. Leave empty to run lite-only.
LICENSE_KEY=$LICENSE_KEY
EOF

echo ""
echo "============================================================"
echo " sg-test-automation is ready."
echo "   Site:   $BASE_URL"
echo "   Admin:  $ADMIN_USER / $ADMIN_PASS  ($BASE_URL/wp-admin)"
echo "   REST:   HTTP Basic via WP-API Basic-Auth (admin login)."
echo "   .env written with BASE_URL + credentials."
echo ""
echo " Next:"
echo "   npm test            # full suite (setup -> ui -> api)"
echo "   npm run test:api    # API only"
echo "   npm run test:ui     # UI only"
echo "============================================================"
