#!/bin/bash
# scripts/validate-ddd-imports.sh
# Validates that all cross-domain references have explicit imports
#
# Exit codes:
#   0 = All imports valid
#   1 = Missing imports found (MUST FIX)
#
# Usage: ./scripts/validate-ddd-imports.sh

set -e

echo "🔍 DDD Import Validator"
echo "========================"
echo ""

ERRORS=0
WARNINGS=0
CHECKED=0

# Find all PHP files in Domains
MODELS=$(find app/Domains -name "*.php" -type f 2>/dev/null)

if [ -z "$MODELS" ]; then
    echo "❌ No models found in app/Domains/"
    exit 1
fi

for MODEL in $MODELS; do
    CHECKED=$((CHECKED + 1))

    # Extract namespace
    NAMESPACE=$(grep "^namespace" "$MODEL" 2>/dev/null | sed 's/namespace //;s/;//' | head -1)
    if [ -z "$NAMESPACE" ]; then
        continue
    fi

    MODEL_DIR=$(dirname "$MODEL")
    MODEL_NAME=$(basename "$MODEL" .php)

    # Extract referenced classes in relationships (Foo::class)
    REFS=$(grep -oE "\b[A-Z][a-zA-Z0-9]*::class" "$MODEL" 2>/dev/null | sed 's/::class//' | sort -u)

    if [ -z "$REFS" ]; then
        continue
    fi

    for REF in $REFS; do
        # Skip PHP/Laravel built-ins
        if [[ "$REF" =~ ^(Model|Collection|Builder|Request|Response|Illuminate|Carbon)$ ]]; then
            continue
        fi

        # Check if imported (direct or aliased)
        # Matches: use ...\ClassName; OR use ... as ClassName;
        if ! grep -qE "(use.*\\\\${REF};|use.*\s+as\s+${REF};)" "$MODEL" 2>/dev/null; then
            # Check if same namespace (class exists in same directory)
            if [ -f "${MODEL_DIR}/${REF}.php" ]; then
                # Same namespace - warning only
                echo "⚠️  $MODEL_NAME references $REF (same namespace, consider explicit import)"
                WARNINGS=$((WARNINGS + 1))
            else
                # Different namespace - error!
                echo "❌ $MODEL_NAME references $REF but doesn't import it"
                echo "   File: $MODEL"
                echo "   Fix: Add appropriate use statement"
                echo ""
                ERRORS=$((ERRORS + 1))
            fi
        fi
    done
done

echo "================================"
echo "Summary:"
echo "  Files checked: $CHECKED"
echo "  Errors: $ERRORS (MUST FIX)"
echo "  Warnings: $WARNINGS (SHOULD FIX)"
echo ""

if [ $ERRORS -gt 0 ]; then
    echo "❌ Import validation failed"
    echo ""
    echo "To fix: Add missing use statements to the files above"
    exit 1
elif [ $WARNINGS -gt 5 ]; then
    echo "⚠️  Many warnings found (${WARNINGS} > 5)"
    echo "Consider adding explicit imports for same-namespace references"
    echo ""
    echo "✅ Import validation passed (with warnings)"
    exit 0
else
    echo "✅ Import validation passed"
    exit 0
fi
