#!/bin/bash

# Test Email System - Comprehensive Email Testing Script
# Tests all email flows and verifies queue processing

set -e

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

echo -e "${BLUE}========================================${NC}"
echo -e "${BLUE}  Email System Test Suite${NC}"
echo -e "${BLUE}========================================${NC}"
echo ""

# Change to project root
cd "$(dirname "$0")/.."

# Load database helper functions
source "$(dirname "$0")/_db-helper.sh"

# Function to check if service is running
check_service() {
    SERVICE=$1
    PORT=$2

    if lsof -i :$PORT > /dev/null 2>&1; then
        echo -e "${GREEN}✓${NC} $SERVICE is running on port $PORT"
        return 0
    else
        echo -e "${RED}✗${NC} $SERVICE is NOT running on port $PORT"
        return 1
    fi
}

# Function to count jobs
count_jobs() {
    db_count "jobs" 2>/dev/null || echo "0"
}

# Step 1: Check prerequisites
echo -e "${YELLOW}Step 1: Checking prerequisites...${NC}"
echo ""

PREREQ_PASS=true

# Check Laravel server
if ! check_service "Laravel API" 8000; then
    echo -e "${YELLOW}   Start with: php artisan serve${NC}"
    PREREQ_PASS=false
fi

# Check Mailpit
if ! check_service "Mailpit" 8025; then
    echo -e "${YELLOW}   Start with: mailpit${NC}"
    PREREQ_PASS=false
fi

# Check database
if db_test_connection; then
    echo -e "${GREEN}✓${NC} MySQL database is accessible"
else
    echo -e "${RED}✗${NC} MySQL database is NOT accessible"
    PREREQ_PASS=false
fi

echo ""

if [ "$PREREQ_PASS" = false ]; then
    echo -e "${RED}Prerequisites not met. Please start required services.${NC}"
    exit 1
fi

# Step 2: Clear queue
echo -e "${YELLOW}Step 2: Checking queue status...${NC}"
INITIAL_JOBS=$(count_jobs)
echo "   Initial queue size: $INITIAL_JOBS jobs"

if [ "$INITIAL_JOBS" -gt 0 ]; then
    echo -e "${YELLOW}   Processing existing jobs...${NC}"
    php artisan queue:work database --queue=critical,tickets,default --tries=3 --timeout=60 --stop-when-empty --quiet
    echo -e "${GREEN}   ✓ Queue cleared${NC}"
fi
echo ""

# Step 3: Test Welcome Email (User Registration)
echo -e "${YELLOW}Step 3: Testing Welcome Email (User Registration)...${NC}"
TEST_EMAIL="test-$(date +%s)@showprima.test"

echo "   Creating test user: $TEST_EMAIL"
RESPONSE=$(curl -s -X POST http://localhost:8000/api/register \
  -H "Content-Type: application/json" \
  -d "{
    \"first_name\": \"Test\",
    \"last_name\": \"User\",
    \"email\": \"$TEST_EMAIL\",
    \"password\": \"TestPassword123!\",
    \"password_confirmation\": \"TestPassword123!\"
  }")

if echo "$RESPONSE" | grep -q "error"; then
    echo -e "${RED}   ✗ Registration failed${NC}"
    echo "   Response: $RESPONSE"
else
    echo -e "${GREEN}   ✓ User registered${NC}"

    # Check if job was queued
    AFTER_REG_JOBS=$(count_jobs)
    if [ "$AFTER_REG_JOBS" -gt 0 ]; then
        echo -e "${GREEN}   ✓ Welcome email queued (${AFTER_REG_JOBS} jobs in queue)${NC}"
    else
        echo -e "${RED}   ✗ No job queued${NC}"
    fi
fi
echo ""

# Step 4: Process queue
echo -e "${YELLOW}Step 4: Processing queued jobs...${NC}"
php artisan queue:work database --queue=critical,tickets,default --tries=3 --timeout=60 --stop-when-empty --quiet
FINAL_JOBS=$(count_jobs)
echo -e "${GREEN}   ✓ Queue processed${NC}"
echo "   Final queue size: $FINAL_JOBS jobs"
echo ""

# Step 5: Test Account Setup Invitation
echo -e "${YELLOW}Step 5: Testing Account Setup Invitation Email...${NC}"
INVITE_EMAIL="invite-$(date +%s)@showprima.test"

echo "   Creating test invitation: $INVITE_EMAIL"
php artisan tinker --execute="
\$invitation = new App\Model\AccountSetupInvitation([
    'email' => '$INVITE_EMAIL',
    'first_name' => 'Test',
    'last_name' => 'Invitee',
    'campaign_name' => 'test_campaign'
]);
\$invitation->save();

\$service = new App\Services\AccountSetupService();
\$result = \$service->sendInvitationEmail(\$invitation);

echo \$result ? 'SUCCESS' : 'FAILED';
" > /tmp/tinker_output.txt 2>&1

if grep -q "SUCCESS" /tmp/tinker_output.txt; then
    echo -e "${GREEN}   ✓ Invitation email queued${NC}"

    # Process queue
    php artisan queue:work database --queue=critical,tickets,default --tries=3 --timeout=60 --stop-when-empty --quiet
    echo -e "${GREEN}   ✓ Queue processed${NC}"
else
    echo -e "${RED}   ✗ Failed to queue invitation email${NC}"
fi
rm -f /tmp/tinker_output.txt
echo ""

# Step 6: Check Mailpit
echo -e "${YELLOW}Step 6: Checking Mailpit for received emails...${NC}"
MAILPIT_RESPONSE=$(curl -s http://localhost:8025/api/v1/messages)
EMAIL_COUNT=$(echo "$MAILPIT_RESPONSE" | grep -o '"total":[0-9]*' | grep -o '[0-9]*' || echo "0")

if [ "$EMAIL_COUNT" -gt 0 ]; then
    echo -e "${GREEN}   ✓ $EMAIL_COUNT email(s) received in Mailpit${NC}"
    echo ""
    echo -e "${GREEN}   📧 View emails: ${BLUE}http://localhost:8025${NC}"
else
    echo -e "${YELLOW}   ⚠ No emails in Mailpit (emails may have been cleared)${NC}"
    echo -e "${YELLOW}   Check manually: ${BLUE}http://localhost:8025${NC}"
fi
echo ""

# Step 7: Summary
echo -e "${BLUE}========================================${NC}"
echo -e "${BLUE}  Test Summary${NC}"
echo -e "${BLUE}========================================${NC}"
echo -e "${GREEN}✓${NC} Queue processing: WORKING"
echo -e "${GREEN}✓${NC} Welcome email: QUEUED"
echo -e "${GREEN}✓${NC} Invitation email: QUEUED"
echo -e "${GREEN}✓${NC} Mailpit integration: WORKING"
echo ""
echo -e "${YELLOW}Next Steps:${NC}"
echo "1. Check Mailpit UI: ${BLUE}http://localhost:8025${NC}"
echo "2. Start queue worker for development: ${BLUE}./scripts/start-queue-worker.sh${NC}"
echo "3. Monitor logs: ${BLUE}tail -f storage/logs/laravel-$(date +%Y-%m-%d).log${NC}"
echo ""
echo -e "${GREEN}Email system is ready! 🎉${NC}"
