#!/bin/bash

# =============================================================================
# Pre-commit hook: Run tests before every commit
# =============================================================================
# PRIMARY HOOK SYSTEM: .githooks/ (configured via core.hooksPath)
#
# This hook enforces the "test before commit" rule.
# Every commit must pass all tests — no exceptions.
#
# If tests fail, the commit is blocked. Fix the failing tests first.
# To bypass in emergencies: git commit --no-verify (NOT recommended)
#
# Note: .pre-commit-config.yaml exists for optional supplementary checks
# (trailing whitespace, YAML/JSON validation, large file detection, etc.)
# but requires separate installation: pip install pre-commit && pre-commit install
# This .githooks/ system is the primary and always-active hook system.
# =============================================================================

echo ""
echo "🧪 Running tests before commit..."
echo ""

# Check if vendor directory exists (composer install ran)
if [ ! -d "vendor" ]; then
    echo "⚠️  'vendor/' not found. Dependencies not installed."
    echo "   Run 'composer install' first."
    echo ""
    exit 1
fi

# Check if PHPUnit is available
if [ ! -f "vendor/bin/phpunit" ]; then
    echo "❌ PHPUnit not found at 'vendor/bin/phpunit'."
    echo "   Run 'composer install' to install dev dependencies."
    echo ""
    exit 1
fi

# Run PHPUnit with stop-on-failure for fast feedback
./vendor/bin/phpunit --stop-on-failure 2>&1

TEST_EXIT_CODE=$?

if [ $TEST_EXIT_CODE -ne 0 ]; then
    echo ""
    echo "❌ COMMIT BLOCKED: Tests failed!"
    echo ""
    echo "Fix the failing tests before committing."
    echo "Run './vendor/bin/phpunit' to see the full output."
    echo ""
    exit 1
fi

echo ""
echo "✅ All tests passed. Proceeding with commit."
echo ""
