#!/bin/bash
# PHP Optimizer Phase 3 - Comprehensive Test Suite
# Tests all refactored modules for functionality and compatibility

set -e

PHP_TOOLKIT_DIR="/root/server-toolkit"
TEST_RESULTS_FILE="/tmp/php-optimizer-phase3-test-results.txt"
TEST_PASSED=0
TEST_FAILED=0

# Color codes
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
CYAN='\033[0;36m'
NC='\033[0m'

# Test result functions
test_pass() {
    local test_name="$1"
    echo -e "${GREEN}✓ PASS${NC}: $test_name" | tee -a "$TEST_RESULTS_FILE"
    TEST_PASSED=$((TEST_PASSED + 1))
}

test_fail() {
    local test_name="$1"
    local reason="$2"
    echo -e "${RED}✗ FAIL${NC}: $test_name" | tee -a "$TEST_RESULTS_FILE"
    [ -n "$reason" ] && echo "  Reason: $reason" | tee -a "$TEST_RESULTS_FILE"
    TEST_FAILED=$((TEST_FAILED + 1))
}

test_skip() {
    local test_name="$1"
    echo -e "${YELLOW}⊘ SKIP${NC}: $test_name" | tee -a "$TEST_RESULTS_FILE"
}

# ============================================================================
# PHASE 3c STEP 1: MODULE LOADING TEST
# ============================================================================

echo ""
echo "╔════════════════════════════════════════════════════════════════╗"
echo "║ PHASE 3c STEP 1: MODULE LOADING TEST                          ║"
echo "╚════════════════════════════════════════════════════════════════╝"
echo ""

> "$TEST_RESULTS_FILE"

# Test 1.1: Source php-ui.sh
bash << 'EOF'
source /root/server-toolkit/lib/common-functions.sh 2>/dev/null
source /root/server-toolkit/lib/php-ui.sh 2>/dev/null
[ $(type -t show_banner | wc -l) -gt 0 ] && exit 0 || exit 1
EOF

if [ $? -eq 0 ]; then
    test_pass "php-ui.sh loads without errors"
else
    test_fail "php-ui.sh loads without errors" "Module failed to load"
fi

# Test 1.2: Source php-scanner.sh
bash << 'EOF'
source /root/server-toolkit/lib/common-functions.sh 2>/dev/null
source /root/server-toolkit/lib/user-manager.sh 2>/dev/null
source /root/server-toolkit/lib/php-scanner.sh 2>/dev/null
[ $(type -t enumerate_all_accounts | wc -l) -gt 0 ] && exit 0 || exit 1
EOF

if [ $? -eq 0 ]; then
    test_pass "php-scanner.sh loads without errors"
else
    test_fail "php-scanner.sh loads without errors" "Module failed to load"
fi

# Test 1.3: Source php-action-executor.sh
bash << 'EOF'
source /root/server-toolkit/lib/common-functions.sh 2>/dev/null
source /root/server-toolkit/lib/php-action-executor.sh 2>/dev/null
[ $(type -t init_change_tracking | wc -l) -gt 0 ] && exit 0 || exit 1
EOF

if [ $? -eq 0 ]; then
    test_pass "php-action-executor.sh loads without errors"
else
    test_fail "php-action-executor.sh loads without errors" "Module failed to load"
fi

# Test 1.4: Source php-server-manager.sh
bash << 'EOF'
source /root/server-toolkit/lib/common-functions.sh 2>/dev/null
source /root/server-toolkit/lib/user-manager.sh 2>/dev/null
source /root/server-toolkit/lib/php-analyzer.sh 2>/dev/null
source /root/server-toolkit/lib/php-scanner.sh 2>/dev/null
source /root/server-toolkit/lib/php-action-executor.sh 2>/dev/null
source /root/server-toolkit/lib/php-server-manager.sh 2>/dev/null
[ $(type -t scan_entire_server | wc -l) -gt 0 ] && exit 0 || exit 1
EOF

if [ $? -eq 0 ]; then
    test_pass "php-server-manager.sh loads without errors"
else
    test_fail "php-server-manager.sh loads without errors" "Module failed to load"
fi

# Test 1.5: All modules together
bash << 'EOF'
source /root/server-toolkit/lib/common-functions.sh 2>/dev/null
source /root/server-toolkit/lib/system-detect.sh 2>/dev/null
source /root/server-toolkit/lib/user-manager.sh 2>/dev/null
source /root/server-toolkit/lib/php-detector.sh 2>/dev/null
source /root/server-toolkit/lib/php-analyzer.sh 2>/dev/null
source /root/server-toolkit/lib/php-config-manager.sh 2>/dev/null
source /root/server-toolkit/lib/php-calculator-improved.sh 2>/dev/null
source /root/server-toolkit/lib/php-ui.sh 2>/dev/null
source /root/server-toolkit/lib/php-scanner.sh 2>/dev/null
source /root/server-toolkit/lib/php-action-executor.sh 2>/dev/null
source /root/server-toolkit/lib/php-server-manager.sh 2>/dev/null

# Verify key functions from each module
type show_banner >/dev/null 2>&1 || exit 1
type enumerate_all_domains >/dev/null 2>&1 || exit 1
type apply_optimization >/dev/null 2>&1 || exit 1
type execute_server_optimization_plan >/dev/null 2>&1 || exit 1
exit 0
EOF

if [ $? -eq 0 ]; then
    test_pass "All modules load together without conflicts"
else
    test_fail "All modules load together without conflicts" "Conflicts or missing functions"
fi

# ============================================================================
# PHASE 3c STEP 2: CONTROL PANEL ENUMERATION TEST
# ============================================================================

echo ""
echo "╔════════════════════════════════════════════════════════════════╗"
echo "║ PHASE 3c STEP 2: CONTROL PANEL ENUMERATION TEST               ║"
echo "╚════════════════════════════════════════════════════════════════╝"
echo ""

# Test 2.1: List all accounts
bash << 'EOF'
source /root/server-toolkit/lib/common-functions.sh 2>/dev/null
source /root/server-toolkit/lib/system-detect.sh 2>/dev/null
source /root/server-toolkit/lib/user-manager.sh 2>/dev/null
source /root/server-toolkit/lib/php-scanner.sh 2>/dev/null

initialize_system_detection
accounts=$(enumerate_all_accounts)
[ -n "$accounts" ] && [ $(echo "$accounts" | wc -l) -gt 0 ] && exit 0 || exit 1
EOF

if [ $? -eq 0 ]; then
    account_count=$(bash << 'EOF'
source /root/server-toolkit/lib/common-functions.sh 2>/dev/null
source /root/server-toolkit/lib/system-detect.sh 2>/dev/null
source /root/server-toolkit/lib/user-manager.sh 2>/dev/null
source /root/server-toolkit/lib/php-scanner.sh 2>/dev/null
initialize_system_detection
enumerate_all_accounts | wc -l
EOF
)
    test_pass "enumerate_all_accounts() returns accounts ($account_count found)"
else
    test_fail "enumerate_all_accounts() returns accounts" "No accounts enumerated"
fi

# Test 2.2: List domains for first account
bash << 'EOF'
source /root/server-toolkit/lib/common-functions.sh 2>/dev/null
source /root/server-toolkit/lib/system-detect.sh 2>/dev/null
source /root/server-toolkit/lib/user-manager.sh 2>/dev/null
source /root/server-toolkit/lib/php-scanner.sh 2>/dev/null

initialize_system_detection
first_account=$(enumerate_all_accounts | head -1)
[ -z "$first_account" ] && exit 1

domains=$(enumerate_user_domains "$first_account" 2>/dev/null)
# Domains may or may not exist, but function should work
exit 0
EOF

if [ $? -eq 0 ]; then
    test_pass "enumerate_user_domains() works for first account"
else
    test_fail "enumerate_user_domains() works for first account" "Function failed"
fi

# Test 2.3: enumerate_all_domains (server-wide)
bash << 'EOF'
source /root/server-toolkit/lib/common-functions.sh 2>/dev/null
source /root/server-toolkit/lib/system-detect.sh 2>/dev/null
source /root/server-toolkit/lib/user-manager.sh 2>/dev/null
source /root/server-toolkit/lib/php-scanner.sh 2>/dev/null

initialize_system_detection
all_domains=$(enumerate_all_domains)
# Function should return something (or empty if no domains)
exit 0
EOF

if [ $? -eq 0 ]; then
    test_pass "enumerate_all_domains() completes without error"
else
    test_fail "enumerate_all_domains() completes without error" "Function failed"
fi

# ============================================================================
# PHASE 3c STEP 3: FILTERING AND SELECTION TEST
# ============================================================================

echo ""
echo "╔════════════════════════════════════════════════════════════════╗"
echo "║ PHASE 3c STEP 3: FILTERING AND SELECTION TEST                 ║"
echo "╚════════════════════════════════════════════════════════════════╝"
echo ""

# Test 3.1: Account name filtering
bash << 'EOF'
source /root/server-toolkit/lib/common-functions.sh 2>/dev/null
source /root/server-toolkit/lib/system-detect.sh 2>/dev/null
source /root/server-toolkit/lib/user-manager.sh 2>/dev/null
source /root/server-toolkit/lib/php-scanner.sh 2>/dev/null

initialize_system_detection
# Try filtering with a pattern (may return nothing, but function should work)
filtered=$(filter_accounts_by_name "a" 2>/dev/null)
exit 0
EOF

if [ $? -eq 0 ]; then
    test_pass "filter_accounts_by_name() executes without error"
else
    test_fail "filter_accounts_by_name() executes without error" "Function failed"
fi

# Test 3.2: Domain name filtering
bash << 'EOF'
source /root/server-toolkit/lib/common-functions.sh 2>/dev/null
source /root/server-toolkit/lib/system-detect.sh 2>/dev/null
source /root/server-toolkit/lib/user-manager.sh 2>/dev/null
source /root/server-toolkit/lib/php-scanner.sh 2>/dev/null

initialize_system_detection
filtered=$(filter_domains_by_name "." 2>/dev/null)
exit 0
EOF

if [ $? -eq 0 ]; then
    test_pass "filter_domains_by_name() executes without error"
else
    test_fail "filter_domains_by_name() executes without error" "Function failed"
fi

# Test 3.3: Menu functions
bash << 'EOF'
source /root/server-toolkit/lib/common-functions.sh 2>/dev/null
source /root/server-toolkit/lib/php-ui.sh 2>/dev/null

# Test that menu functions exist
type show_main_menu >/dev/null 2>&1 || exit 1
type show_optimization_menu >/dev/null 2>&1 || exit 1
type show_apply_menu >/dev/null 2>&1 || exit 1
exit 0
EOF

if [ $? -eq 0 ]; then
    test_pass "Menu functions available and callable"
else
    test_fail "Menu functions available and callable" "Functions missing"
fi

# ============================================================================
# PHASE 3c STEP 4: BATCH OPERATIONS AND ROLLBACK TEST
# ============================================================================

echo ""
echo "╔════════════════════════════════════════════════════════════════╗"
echo "║ PHASE 3c STEP 4: BATCH OPERATIONS AND ROLLBACK TEST           ║"
echo "╚════════════════════════════════════════════════════════════════╝"
echo ""

# Test 4.1: Change tracking
bash << 'EOF'
source /root/server-toolkit/lib/common-functions.sh 2>/dev/null
source /root/server-toolkit/lib/php-action-executor.sh 2>/dev/null

init_change_tracking "test-session-$$"
[ -n "$EXECUTOR_SESSION_ID" ] && [ -n "$EXECUTOR_CHANGE_LOG" ] && exit 0 || exit 1
EOF

if [ $? -eq 0 ]; then
    test_pass "init_change_tracking() initializes session"
else
    test_fail "init_change_tracking() initializes session" "Initialization failed"
fi

# Test 4.2: Backup functionality
bash << 'EOF'
source /root/server-toolkit/lib/common-functions.sh 2>/dev/null
source /root/server-toolkit/lib/php-action-executor.sh 2>/dev/null

# This should fail gracefully if config not found (expected)
backup_domain_config "test.example.com" "testuser" 2>/dev/null
# Function should exist and be callable
exit 0
EOF

if [ $? -eq 0 ]; then
    test_pass "backup_domain_config() is callable"
else
    test_fail "backup_domain_config() is callable" "Function error"
fi

# Test 4.3: Verification functions
bash << 'EOF'
source /root/server-toolkit/lib/common-functions.sh 2>/dev/null
source /root/server-toolkit/lib/php-action-executor.sh 2>/dev/null

type verify_applied_changes >/dev/null 2>&1 || exit 1
type validate_pool_config >/dev/null 2>&1 || exit 1
exit 0
EOF

if [ $? -eq 0 ]; then
    test_pass "Verification functions available"
else
    test_fail "Verification functions available" "Functions missing"
fi

# Test 4.4: PHP-FPM service functions
bash << 'EOF'
source /root/server-toolkit/lib/php-action-executor.sh 2>/dev/null

type reload_php_fpm >/dev/null 2>&1 || exit 1
type restart_php_fpm >/dev/null 2>&1 || exit 1
type get_php_fpm_status >/dev/null 2>&1 || exit 1
exit 0
EOF

if [ $? -eq 0 ]; then
    test_pass "PHP-FPM service functions available"
else
    test_fail "PHP-FPM service functions available" "Functions missing"
fi

# ============================================================================
# PHASE 3c STEP 5: BACKWARD COMPATIBILITY TEST
# ============================================================================

echo ""
echo "╔════════════════════════════════════════════════════════════════╗"
echo "║ PHASE 3c STEP 5: BACKWARD COMPATIBILITY TEST                  ║"
echo "╚════════════════════════════════════════════════════════════════╝"
echo ""

# Test 5.1: Original php-optimizer.sh still works
bash -n /root/server-toolkit/modules/performance/php-optimizer.sh

if [ $? -eq 0 ]; then
    test_pass "php-optimizer.sh passes syntax check"
else
    test_fail "php-optimizer.sh passes syntax check" "Syntax error"
fi

# Test 5.2: Original functions still referenced
grep -q "analyze_single_domain" /root/server-toolkit/modules/performance/php-optimizer.sh

if [ $? -eq 0 ]; then
    test_pass "Original function names still in php-optimizer.sh"
else
    test_fail "Original function names still in php-optimizer.sh" "Functions removed"
fi

# Test 5.3: Color codes preserved
grep -q "RED=" /root/server-toolkit/modules/performance/php-optimizer.sh

if [ $? -eq 0 ]; then
    test_pass "Color code definitions preserved"
else
    test_fail "Color code definitions preserved" "Color codes missing"
fi

# Test 5.4: Menu structure intact
grep -q "show_main_menu" /root/server-toolkit/modules/performance/php-optimizer.sh

if [ $? -eq 0 ]; then
    test_pass "Menu display functions referenced"
else
    test_fail "Menu display functions referenced" "Menu functions missing"
fi

# ============================================================================
# PHASE 3c STEP 6: PERFORMANCE AND STRESS TEST
# ============================================================================

echo ""
echo "╔════════════════════════════════════════════════════════════════╗"
echo "║ PHASE 3c STEP 6: PERFORMANCE AND STRESS TEST                  ║"
echo "╚════════════════════════════════════════════════════════════════╝"
echo ""

# Test 6.1: Module size reasonable
UI_SIZE=$(wc -l < /root/server-toolkit/lib/php-ui.sh)
if [ "$UI_SIZE" -gt 500 ] && [ "$UI_SIZE" -lt 800 ]; then
    test_pass "php-ui.sh size is reasonable ($UI_SIZE lines)"
else
    test_fail "php-ui.sh size is reasonable" "Size: $UI_SIZE (expected 500-800)"
fi

# Test 6.2: php-scanner.sh size reasonable
SCANNER_SIZE=$(wc -l < /root/server-toolkit/lib/php-scanner.sh)
if [ "$SCANNER_SIZE" -gt 500 ] && [ "$SCANNER_SIZE" -lt 600 ]; then
    test_pass "php-scanner.sh size is reasonable ($SCANNER_SIZE lines)"
else
    test_fail "php-scanner.sh size is reasonable" "Size: $SCANNER_SIZE (expected 500-600)"
fi

# Test 6.3: php-action-executor.sh size reasonable
EXECUTOR_SIZE=$(wc -l < /root/server-toolkit/lib/php-action-executor.sh)
if [ "$EXECUTOR_SIZE" -gt 550 ] && [ "$EXECUTOR_SIZE" -lt 650 ]; then
    test_pass "php-action-executor.sh size is reasonable ($EXECUTOR_SIZE lines)"
else
    test_fail "php-action-executor.sh size is reasonable" "Size: $EXECUTOR_SIZE (expected 550-650)"
fi

# Test 6.4: php-server-manager.sh size reasonable
MANAGER_SIZE=$(wc -l < /root/server-toolkit/lib/php-server-manager.sh)
if [ "$MANAGER_SIZE" -gt 500 ] && [ "$MANAGER_SIZE" -lt 600 ]; then
    test_pass "php-server-manager.sh size is reasonable ($MANAGER_SIZE lines)"
else
    test_fail "php-server-manager.sh size is reasonable" "Size: $MANAGER_SIZE (expected 500-600)"
fi

# Test 6.5: All modules available
if [ -f /root/server-toolkit/lib/php-ui.sh ] && \
   [ -f /root/server-toolkit/lib/php-scanner.sh ] && \
   [ -f /root/server-toolkit/lib/php-action-executor.sh ] && \
   [ -f /root/server-toolkit/lib/php-server-manager.sh ]; then
    test_pass "All module files exist and are readable"
else
    test_fail "All module files exist and are readable" "One or more files missing"
fi

# ============================================================================
# TEST SUMMARY
# ============================================================================

echo ""
echo "╔════════════════════════════════════════════════════════════════╗"
echo "║ PHASE 3c TEST SUMMARY                                         ║"
echo "╚════════════════════════════════════════════════════════════════╝"
echo ""

TOTAL=$((TEST_PASSED + TEST_FAILED))

echo "Results: $TOTAL tests executed"
echo ""
echo -e "${GREEN}Passed: $TEST_PASSED${NC}"
echo -e "${RED}Failed: $TEST_FAILED${NC}"
echo ""

if [ $TEST_FAILED -eq 0 ]; then
    echo -e "${GREEN}✓ ALL TESTS PASSED${NC}"
    exit 0
else
    echo -e "${RED}✗ SOME TESTS FAILED${NC}"
    exit 1
fi
