#!/usr/bin/env bash
# ziggy-generate.sh — Regenerate resources/js/ziggy.js to match the route table.
#
# WHY THIS EXISTS (CLAUDE.md gotcha #13):
#   The ZiggyIsInSyncTest contract test regenerates ziggy.js *inside the phpunit
#   process*, so the committed file must match generation under phpunit.xml's
#   feature-flag superset (FEATURE_SOCIAL_AUTH / FEATURE_WEBHOOKS / FEATURE_ENTERPRISE
#   = true, etc.). A plain `php artisan ziggy:generate` uses the dev .env — and
#   `--env=testing` loads .env.testing where those flags are FALSE — so both drop
#   feature-gated routes and the committed file fails the contract test.
#
#   This script derives the exact flag set FROM phpunit.xml (single source of truth,
#   so it can never drift from the test) and exports it before regenerating.
#
# Usage:
#   bash scripts/ziggy-generate.sh                 # regenerate resources/js/ziggy.js
#   bash scripts/ziggy-generate.sh <relative/path> # regenerate to a custom path
#   composer ziggy                                 # convenience wrapper

set -euo pipefail

# Resolve repo root from this script's location (works from any cwd).
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
cd "$REPO_ROOT"

if [ ! -f phpunit.xml ]; then
  echo "ziggy-generate: phpunit.xml not found at $REPO_ROOT — cannot derive feature flags." >&2
  exit 1
fi

# Extract APP_ENV + every FEATURE_* env entry from phpunit.xml, one KEY=VALUE per line.
# Matches <env name="..." value="..."/> regardless of trailing attributes (e.g. force="true").
FLAGS="$(grep -oE '<env name="[^"]+" value="[^"]*"' phpunit.xml \
  | sed -E 's/<env name="([^"]+)" value="([^"]*)"/\1=\2/' \
  | grep -E '^(APP_ENV|FEATURE_)' || true)"

if [ -z "$FLAGS" ]; then
  echo "ziggy-generate: no APP_ENV/FEATURE_* flags found in phpunit.xml — refusing to" \
       "regenerate under unknown env (would risk a drifted ziggy.js)." >&2
  exit 1
fi

# Export the phpunit flag set. Real env vars take precedence over .env / .env.testing,
# so this faithfully reproduces the env the contract test generates under.
while IFS= read -r kv; do
  export "$kv"
done <<< "$FLAGS"

php artisan ziggy:generate "$@"

echo "ziggy-generate: regenerated under phpunit feature flags (APP_ENV=${APP_ENV:-?})." >&2
