#!/usr/bin/env bash
# Audit: find Vue pages with no matching entry in VueRouteMap.php
# Usage: ./scripts/check-route-map.sh [--quiet]
#
# Exits 0 if all pages are registered, 1 if any are missing.
# Use --quiet to suppress the header (useful in CI or pre-commit hooks).

REPO_ROOT="$(cd "$(dirname "$0")/.." && pwd)"
PAGES_DIR="$REPO_ROOT/resources/js/Pages"
ROUTE_MAP="$REPO_ROOT/app/Http/Controllers/Support/VueRouteMap.php"
QUIET="${1:-}"

# Extract all component names registered in VueRouteMap (quoted string values for 'component' key)
registered=$(grep "'component'" "$ROUTE_MAP" \
    | sed "s/.*'component'[^']*'\([^']*\)'.*/\1/" \
    | sort -u)

# Collect Vue page basenames (strip path and .vue extension).
# Excludes: Core/* fragments (layout shell), Fragments/* (sub-views mounted inside pages),
# Auth/* (login is registered separately), and index.js shims.
unregistered=()
while IFS= read -r -d '' file; do
    relative="${file#$PAGES_DIR/}"
    # Skip layout fragments and sub-views that are not standalone routes
    case "$relative" in
        Core/*|Fragments/*|Auth/*)   continue ;;
    esac
    basename="${relative%.vue}"
    # Component name is the last path segment (e.g. Market/FooBar.vue → FooBar)
    component="${basename##*/}"
    if ! echo "$registered" | grep -qx "$component"; then
        unregistered+=("$component  ($relative)")
    fi
done < <(find "$PAGES_DIR" -name "*.vue" -print0)

if [[ ${#unregistered[@]} -eq 0 ]]; then
    [[ "$QUIET" != "--quiet" ]] && echo "✓ All Vue pages are registered in VueRouteMap.php"
    exit 0
fi

[[ "$QUIET" != "--quiet" ]] && echo "Vue pages missing from VueRouteMap.php:"
for entry in "${unregistered[@]}"; do
    echo "  MISSING: $entry"
done
exit 1
