#!/bin/bash

# Script para identificar qué test contamina TenantAwareMakeSearchableTest
# Ejecuta cada test de Unit/Jobs secuencialmente y verifica si TenantAware sigue funcionando

TARGET_TEST="tests/Unit/Jobs/TenantAwareMakeSearchableTest.php"
LOG_FILE="tenant-aware-debug-$(date +%Y%m%d-%H%M%S).log"

echo "🔍 Debugging TenantAwareMakeSearchableTest pollution" | tee "$LOG_FILE"
echo "══════════════════════════════════════════════════" | tee -a "$LOG_FILE"
echo "Target: $TARGET_TEST" | tee -a "$LOG_FILE"
echo "Log: $LOG_FILE" | tee -a "$LOG_FILE"
echo "" | tee -a "$LOG_FILE"

# Primero verificar que el test pasa solo
echo "📋 Step 1: Verificar que $TARGET_TEST pasa individualmente..." | tee -a "$LOG_FILE"
php artisan test "$TARGET_TEST" --compact > /tmp/test_output.txt 2>&1
if [ $? -eq 0 ]; then
    echo "✅ PASS - Test pasa individualmente" | tee -a "$LOG_FILE"
else
    echo "❌ FAIL - Test falla individualmente (problema base)" | tee -a "$LOG_FILE"
    cat /tmp/test_output.txt | tee -a "$LOG_FILE"
    exit 1
fi

echo "" | tee -a "$LOG_FILE"
echo "📋 Step 2: Ejecutar tests de Unit/Jobs uno por uno..." | tee -a "$LOG_FILE"
echo "══════════════════════════════════════════════════" | tee -a "$LOG_FILE"

# Obtener lista de tests en Unit/Jobs (excluyendo TenantAware)
TEST_FILES=$(find tests/Unit/Jobs -name "*Test.php" ! -name "TenantAwareMakeSearchableTest.php" | sort)

ACCUMULATED_TESTS=""
CONTAMINATION_FOUND=false
CULPRIT_TEST=""

for test_file in $TEST_FILES; do
    # Agregar test a la lista acumulada
    if [ -z "$ACCUMULATED_TESTS" ]; then
        ACCUMULATED_TESTS="$test_file"
    else
        ACCUMULATED_TESTS="$ACCUMULATED_TESTS $test_file"
    fi
    
    echo "" | tee -a "$LOG_FILE"
    echo "🧪 Testing: $test_file" | tee -a "$LOG_FILE"
    echo "   Accumulated tests: $(echo $ACCUMULATED_TESTS | wc -w) files" | tee -a "$LOG_FILE"
    
    # Ejecutar tests acumulados + TenantAware
    php artisan test $ACCUMULATED_TESTS "$TARGET_TEST" --compact > /tmp/test_output.txt 2>&1
    EXIT_CODE=$?
    
    if [ $EXIT_CODE -eq 0 ]; then
        echo "   ✅ PASS - TenantAware sigue funcionando" | tee -a "$LOG_FILE"
    else
        # Verificar si es TenantAware el que falla
        if grep -q "TenantAwareMakeSearchableTest.*FAILED" /tmp/test_output.txt; then
            echo "   ❌ CONTAMINATION DETECTED!" | tee -a "$LOG_FILE"
            echo "   🎯 Culprit: $test_file" | tee -a "$LOG_FILE"
            echo "" | tee -a "$LOG_FILE"
            echo "═══════════════════════════════════════════════════════" | tee -a "$LOG_FILE"
            echo "🎯 ROOT CAUSE FOUND!" | tee -a "$LOG_FILE"
            echo "═══════════════════════════════════════════════════════" | tee -a "$LOG_FILE"
            echo "Contaminating test: $test_file" | tee -a "$LOG_FILE"
            echo "" | tee -a "$LOG_FILE"
            echo "Test output:" | tee -a "$LOG_FILE"
            tail -50 /tmp/test_output.txt | tee -a "$LOG_FILE"
            
            CONTAMINATION_FOUND=true
            CULPRIT_TEST="$test_file"
            break
        else
            echo "   ⚠️  Other test failed (not TenantAware)" | tee -a "$LOG_FILE"
        fi
    fi
done

echo "" | tee -a "$LOG_FILE"
echo "═══════════════════════════════════════════════════════" | tee -a "$LOG_FILE"
echo "📊 FINAL REPORT" | tee -a "$LOG_FILE"
echo "═══════════════════════════════════════════════════════" | tee -a "$LOG_FILE"

if [ "$CONTAMINATION_FOUND" = true ]; then
    echo "Status: ❌ CONTAMINATION FOUND" | tee -a "$LOG_FILE"
    echo "Culprit: $CULPRIT_TEST" | tee -a "$LOG_FILE"
    echo "" | tee -a "$LOG_FILE"
    echo "🔧 Next steps:" | tee -a "$LOG_FILE"
    echo "1. Review $CULPRIT_TEST for cleanup issues" | tee -a "$LOG_FILE"
    echo "2. Check afterEach() blocks" | tee -a "$LOG_FILE"
    echo "3. Verify Mockery::close() is called" | tee -a "$LOG_FILE"
    echo "4. Check for container instance bindings" | tee -a "$LOG_FILE"
    echo "" | tee -a "$LOG_FILE"
    echo "🧪 Reproduce with:" | tee -a "$LOG_FILE"
    echo "php artisan test $CULPRIT_TEST $TARGET_TEST" | tee -a "$LOG_FILE"
else
    echo "Status: ✅ NO CONTAMINATION DETECTED" | tee -a "$LOG_FILE"
    echo "All tests passed in sequence with TenantAware" | tee -a "$LOG_FILE"
fi

echo "" | tee -a "$LOG_FILE"
echo "Log saved to: $LOG_FILE" | tee -a "$LOG_FILE"
