#!/usr/bin/env bash
#
# Regenerates app/Domain/Access/ModuleRegistry.php from the frontend's
# permission catalogue, so backend authorization can never silently drift
# from what the UI enforces.
#
# Usage:
#   scripts/sync-access-catalogue.sh /path/to/stayflow
#
# The argument must point at a checkout of the frontend repository
# (https://github.com/dakamola-alt/stayflow.git). Requires Node.js.

set -euo pipefail

FRONTEND="${1:-}"
if [[ -z "$FRONTEND" ]]; then
  echo "usage: $0 /path/to/stayflow" >&2
  exit 64
fi

SOURCE="$FRONTEND/artifacts/hotel-pms/src/lib/admin-types.ts"
if [[ ! -f "$SOURCE" ]]; then
  echo "error: $SOURCE not found — is that a stayflow checkout?" >&2
  exit 66
fi

ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
WORK="$(mktemp -d)"
trap 'rm -rf "$WORK"' EXIT

# Stage 1 — pull the catalogue out of the TypeScript source as JSON.
node "$ROOT/scripts/extract-access-catalogue.cjs" "$SOURCE" "$WORK"

# Stage 2 — emit the PHP registry.
node "$ROOT/scripts/emit-module-registry.cjs" "$WORK" "$ROOT/app/Domain/Access"

php -l "$ROOT/app/Domain/Access/ModuleRegistry.php"
echo "ModuleRegistry.php regenerated."
