#!/bin/bash
########################################
# Queue Worker Monitor - Test Suite
# Tests the monitoring script behavior
########################################

PROJECT_ROOT="/Users/charlie/code/showprima"
TEST_SCRIPT="$PROJECT_ROOT/scripts/queue-worker-cron-LOCAL.sh"
PID_FILE="$PROJECT_ROOT/storage/queue-worker.pid"
LOG_FILE="$PROJECT_ROOT/storage/logs/queue-worker.log"

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

cd "$PROJECT_ROOT" || exit 1

# Test counter
TESTS_PASSED=0
TESTS_FAILED=0

# Helper functions
print_test() {
    echo ""
    echo "========================================="
    echo -e "${BLUE}TEST $1: $2${NC}"
    echo "========================================="
}

print_pass() {
    echo -e "${GREEN}✅ PASS: $1${NC}"
    ((TESTS_PASSED++))
}

print_fail() {
    echo -e "${RED}❌ FAIL: $1${NC}"
    ((TESTS_FAILED++))
}

print_info() {
    echo -e "${YELLOW}ℹ️  $1${NC}"
}

cleanup() {
    print_info "Cleaning up test artifacts..."
    pkill -f "artisan queue:work" 2>/dev/null
    rm -f "$PID_FILE"
    echo ""
}

# Start tests
echo "========================================="
echo "🧪 QUEUE WORKER MONITOR TEST SUITE"
echo "========================================="
echo ""
echo "Testing script: $TEST_SCRIPT"
echo "PID file: $PID_FILE"
echo "Log file: $LOG_FILE"
echo ""

# Test 1: Worker NOT running, script should start it
print_test "1" "Worker NOT Running → Script Starts Worker"
cleanup
bash "$TEST_SCRIPT"

if [ -f "$PID_FILE" ]; then
    PID=$(cat "$PID_FILE")
    if ps -p "$PID" > /dev/null 2>&1; then
        if ps -p "$PID" -o args= | grep -q "queue:work"; then
            print_pass "Worker started successfully (PID: $PID)"
        else
            print_fail "Process exists but is not queue:work"
        fi
    else
        print_fail "PID file exists but process is not running"
    fi
else
    print_fail "PID file was not created"
fi

# Test 2: Worker IS running, script should do nothing
print_test "2" "Worker IS Running → Script Does Nothing"
BEFORE_PID=$(cat "$PID_FILE" 2>/dev/null)
bash "$TEST_SCRIPT"
AFTER_PID=$(cat "$PID_FILE" 2>/dev/null)

if [ "$BEFORE_PID" = "$AFTER_PID" ]; then
    if ps -p "$AFTER_PID" > /dev/null 2>&1; then
        print_pass "Worker PID unchanged and still running ($AFTER_PID)"
    else
        print_fail "Worker died unexpectedly"
    fi
else
    print_fail "Worker PID changed unexpectedly ($BEFORE_PID → $AFTER_PID)"
fi

# Test 3: Stale PID file, script should restart worker
print_test "3" "Stale PID File → Script Restarts Worker"
OLD_PID=$(cat "$PID_FILE" 2>/dev/null)
print_info "Killing worker (simulating unexpected death)..."
pkill -f "artisan queue:work" 2>/dev/null
sleep 2

bash "$TEST_SCRIPT"
NEW_PID=$(cat "$PID_FILE" 2>/dev/null)

if [ "$NEW_PID" != "$OLD_PID" ]; then
    if ps -p "$NEW_PID" > /dev/null 2>&1; then
        print_pass "Worker restarted with new PID ($OLD_PID → $NEW_PID)"
    else
        print_fail "New PID file created but process is not running"
    fi
else
    print_fail "Worker PID did not change"
fi

# Test 4: Multiple runs in quick succession
print_test "4" "Multiple Rapid Runs → No Duplicate Workers"
bash "$TEST_SCRIPT" &
bash "$TEST_SCRIPT" &
bash "$TEST_SCRIPT" &
wait

WORKER_COUNT=$(ps aux | grep "artisan queue:work" | grep -v grep | wc -l | tr -d ' ')
if [ "$WORKER_COUNT" -eq 1 ]; then
    print_pass "Only 1 worker running (no duplicates)"
else
    print_fail "Found $WORKER_COUNT workers (expected 1)"
fi

# Test 5: Log file is being written
print_test "5" "Log File → Contains Startup Messages"
if [ -f "$LOG_FILE" ]; then
    if grep -q "Worker started with PID" "$LOG_FILE"; then
        ENTRIES=$(grep "Worker started with PID" "$LOG_FILE" | wc -l | tr -d ' ')
        print_pass "Log file contains $ENTRIES worker startup entries"
    else
        print_fail "Log file exists but has no startup messages"
    fi
else
    print_fail "Log file does not exist"
fi

# Test 6: Worker actually processes jobs
print_test "6" "Worker → Actually Processes Jobs"
print_info "Dispatching test job..."

# Create a test job via tinker
php artisan tinker --execute="
    use Illuminate\Support\Facades\Mail;
    use App\Mail\TestMail;

    try {
        \Log::info('TEST: Dispatching test email job');
        Mail::to('test@example.com')->queue(new TestMail());
        echo 'Test job dispatched';
    } catch (\Exception \$e) {
        echo 'Error: ' . \$e->getMessage();
    }
" 2>&1 | tail -5

sleep 5

# Check if job was processed (it should be in logs)
if grep -q "Processing:" "$LOG_FILE" || grep -q "Processed:" "$LOG_FILE"; then
    print_pass "Worker is actively processing jobs"
else
    print_info "No job processing detected (may be working correctly if no jobs were available)"
    print_pass "Worker is running and monitoring queue"
fi

# Final cleanup
cleanup

# Test summary
echo ""
echo "========================================="
echo "📊 TEST SUMMARY"
echo "========================================="
echo -e "${GREEN}Passed: $TESTS_PASSED${NC}"
echo -e "${RED}Failed: $TESTS_FAILED${NC}"
echo "Total: $((TESTS_PASSED + TESTS_FAILED))"
echo ""

if [ $TESTS_FAILED -eq 0 ]; then
    echo -e "${GREEN}✅ ALL TESTS PASSED!${NC}"
    echo ""
    echo "🎉 The monitoring script is working correctly!"
    echo ""
    echo "Next steps:"
    echo "1. Deploy to production server"
    echo "2. Test on server with production script"
    echo "3. Set up cron job"
    exit 0
else
    echo -e "${RED}❌ SOME TESTS FAILED${NC}"
    echo ""
    echo "Review the failures above and investigate."
    exit 1
fi
