#!/usr/bin/env bash
# GSC-NEW-01: Orphaned connection-card ratchet.
#
# GscConnectCard and WpConnectCard were fully-built connection components with
# zero importers in resources/js/Pages — dead code carrying a "Last synced"
# label that printed the data cursor (GscConnectCard.tsx:99-100), not the sync
# time.  They were deleted in the GSC-NEW-01 cleanup.
#
# This ratchet prevents re-introduction: if either component name appears as an
# import or JSX usage inside resources/js/Pages, CI fails.
#
# The canonical surface for connection status is the onboarding wizard
# (OnboardingWizard.tsx) via GscSyncStatusCompact + DownloadPluginButton /
# ActivationPromptCard. If product ever needs a standalone per-site card, build
# it against ConnectionHealthPanel / ConnectionStatusBadge and label the data
# cursor honestly ("Data through" / "Last data date" — NOT "Last synced").
#
# Usage: bash scripts/checks/no-orphaned-connection-cards.sh
#
# Exit codes:
#   0  no matches (tree is clean)
#   1  match found (orphan re-introduced — CI blocks)

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(git -C "$SCRIPT_DIR" rev-parse --show-toplevel 2>/dev/null || echo "$SCRIPT_DIR/../..")"
PAGES_DIR="$REPO_ROOT/resources/js/Pages"
CONNECTIONS_DIR="$REPO_ROOT/resources/js/Components/Connections"

FAILED=0

# Guard 1: file-existence — the component definition must not be re-created.
for CARD in GscConnectCard WpConnectCard; do
    if [ -f "$CONNECTIONS_DIR/${CARD}.tsx" ]; then
        echo "::error::GSC-NEW-01: ${CARD}.tsx was re-created in resources/js/Components/Connections/."
        echo "::error::This component was deleted in GSC-NEW-01 — its \"Last synced\" label prints"
        echo "::error::the data cursor, not the sync time. Build against ConnectionHealthPanel /"
        echo "::error::ConnectionStatusBadge instead."
        FAILED=1
    fi
done

# Guard 2: import/JSX usage in Pages.
if [ ! -d "$PAGES_DIR" ]; then
    echo "ERROR: Pages directory not found: $PAGES_DIR" >&2
    exit 1
fi

MATCHES=$(grep -rE "GscConnectCard|WpConnectCard" "$PAGES_DIR" --include="*.tsx" --include="*.ts" -l 2>/dev/null || true)

if [ -n "$MATCHES" ]; then
    echo "::error::GSC-NEW-01: Orphaned connection card re-introduced in resources/js/Pages."
    echo "::error::GscConnectCard and WpConnectCard are banned — they carry a misleading"
    echo "::error::\"Last synced\" label that prints the data cursor, not the sync time."
    echo "::error::Use ConnectionHealthPanel / ConnectionStatusBadge instead."
    echo "::error::Files with matches:"
    echo "$MATCHES" | while IFS= read -r f; do echo "::error::  $f"; done
    FAILED=1
fi

if [ "$FAILED" -eq 1 ]; then
    exit 1
fi

echo "No orphaned connection cards (definition or usage) — OK"
