#!/usr/bin/env sh

# Skip tests for branch deletions (no code is being pushed)
if read local_ref local_oid remote_ref remote_oid; then
  if [ "$local_oid" = "0000000000000000000000000000000000000000" ]; then
    exit 0
  fi
fi

echo "🚀 Running pre-push checks..."

# Type-check FIRST — pre-commit's incremental check can miss errors under
# concurrent builds (stale .tsbuildinfo); this non-incremental run is the
# reliable gate, so type errors are caught before push, not at deploy/build.
echo "🔎 Type-checking..."
pnpm run type-check || { echo "❌ Type check failed"; exit 1; }
echo "✅ Type check passed"

# Run tests before pushing (target: ≤30s)

# Sub-second, and CI's verify fails on it: a component over its line limit
# passed this hook and failed two CI jobs (#1141).
pnpm run check:sizes || { echo "❌ File size limit exceeded — split the file"; exit 1; }

echo "🧭 Checking route integrity..."
pnpm run audit:routes || { echo "❌ Route audit failed — a declared or emitted link resolves to no route"; exit 1; }
echo "✅ Route audit passed"

echo "🧪 Running unit tests..."
pnpm run test:unit || { echo "❌ Unit tests failed"; exit 1; }
echo "✅ Unit tests passed"

echo "🎭 Running fast E2E tests..."
# Port 3000 is shared across the fleet — another project's dev server answers
# /api/health with the same template shape, so identify the app before testing
# it (2026-08-24: the gate failed a push here because :3000 was serving evig).
# The check must read the <title>: fleet sites are HOSTED at *.orangecat.ch, so
# "orangecat" appears in a foreign site's body links but not in its title.
if curl -sf "${BASE_URL:-http://localhost:3000}/api/health" >/dev/null 2>&1; then
  if curl -sf "${BASE_URL:-http://localhost:3000}/" | grep -io "<title>[^<]*" | grep -qi "orangecat"; then
    BASE_URL="${BASE_URL:-http://localhost:3000}" pnpm run test:e2e:node || { echo "❌ E2E tests failed"; exit 1; }
    echo "✅ E2E tests passed"
  else
    echo "⏭️  Skipped fast E2E (server at ${BASE_URL:-http://localhost:3000} is not OrangeCat; CI runs full P0 matrix)"
  fi
else
  echo "⏭️  Skipped fast E2E (no server at ${BASE_URL:-http://localhost:3000}; CI runs full P0 matrix)"
fi

echo "🎉 All pre-push checks passed! Safe to push."
