#!/usr/bin/env bash
set -euo pipefail

# ── Only gate pushes to master ──────────────────────────────
REMOTE="$1"
while read local_ref local_oid remote_ref remote_oid; do
  if [[ "$remote_ref" == "refs/heads/master" ]]; then
    PUSHING_TO_MASTER=1
    break
  fi
done

if [[ -z "${PUSHING_TO_MASTER:-}" ]]; then
  exit 0
fi

echo "pre-push: pushing to master — running checks..."

BUN=$(command -v bun 2>/dev/null || echo "")
if [[ -z "$BUN" ]]; then
  echo "pre-push: bun not found, skipping"
  exit 0
fi

# ── 1. TypeScript typecheck ─────────────────────────────────
echo "  typecheck..."
$BUN x tsc --noEmit

# ── 2. Isolated tests (mock.module — must run one process each) ─
echo "  isolated tests..."
for f in $(find src -name '*.isolated.test.ts'); do
  $BUN test "$f" --timeout 30000
done

# ── 3. Unit tests ───────────────────────────────────────────
echo "  unit tests..."
# Unit lane = every *.test.ts EXCEPT *.integration.test.ts and *.isolated.test.ts.
TEST_FILES=$(find src -name '*.test.ts' \
  -not -name '*.integration.test.ts' \
  -not -name '*.isolated.test.ts' || true)
if [[ -n "$TEST_FILES" ]]; then
  echo $TEST_FILES | xargs $BUN test --timeout 30000
fi

# ── 4. Integration tests (only if Postgres is reachable) ────
DB_URL="${DATABASE_URL:-postgres://opencrow:opencrow@127.0.0.1:5432/opencrow}"
if pg_isready -d "$DB_URL" -t 2 >/dev/null 2>&1; then
  echo "  integration tests..."
  INTEGRATION_FILES=$(find src -name '*.integration.test.ts' || true)
  if [[ -n "$INTEGRATION_FILES" ]]; then
    echo $INTEGRATION_FILES | DATABASE_URL="$DB_URL" xargs $BUN test --timeout 30000
  fi
else
  echo "  skipping integration tests (Postgres not reachable)"
  echo "  start with: docker compose up -d postgres"
fi

echo "pre-push: all checks passed"
