#!/bin/bash
# Pre-commit hook to enforce validation before commits on protected branches
# Install: git config core.hooksPath .githooks

set -e

# Get the current branch name
BRANCH=$(git rev-parse --abbrev-ref HEAD)

# Protected branches that require validation
PROTECTED_BRANCHES="main dev"

# Check if we're on a protected branch
is_protected() {
    for branch in $PROTECTED_BRANCHES; do
        if [ "$BRANCH" = "$branch" ]; then
            return 0
        fi
    done
    return 1
}

if is_protected; then
    echo "🔒 Committing to protected branch '$BRANCH' - running validation..."

    # Check if we have backend changes
    if git diff --cached --name-only | grep -q "^backend/"; then
        echo "📦 Backend changes detected - running make validate..."
        cd backend
        if ! make validate; then
            echo ""
            echo "❌ Backend validation failed!"
            echo "   Please fix the issues and try again."
            echo "   Run 'cd backend && make validate' to see errors."
            exit 1
        fi
        cd ..
        echo "✅ Backend validation passed!"
    fi

    # Check if we have frontend changes
    if git diff --cached --name-only | grep -q "^frontend/"; then
        echo "🎨 Frontend changes detected - running npm run validate..."
        cd frontend
        if ! npm run validate 2>/dev/null; then
            echo ""
            echo "❌ Frontend validation failed!"
            echo "   Please fix the issues and try again."
            echo "   Run 'cd frontend && npm run validate' to see errors."
            exit 1
        fi
        cd ..
        echo "✅ Frontend validation passed!"
    fi

    echo "🎉 All validations passed! Proceeding with commit..."
else
    echo "📝 Committing to feature branch '$BRANCH' - skipping validation (run manually if needed)"
fi

exit 0
