#!/bin/bash

# Test Newsletter Template System
# Tests the new template-based newsletter campaign system

set -e

BASE_URL="http://localhost:8000"
API_URL="${BASE_URL}/api"

echo "=================================="
echo "Newsletter Template System Tests"
echo "=================================="
echo ""

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

# Function to print test results
print_result() {
    if [ $1 -eq 0 ]; then
        echo -e "${GREEN}✓ PASS${NC}: $2"
    else
        echo -e "${RED}✗ FAIL${NC}: $2"
    fi
}

# Test 1: Check if config file is loaded
echo "Test 1: Checking template configuration..."
php artisan tinker --execute="echo json_encode(config('newsletter-templates.welcome.name'));" > /tmp/test-config.txt 2>&1
if grep -q "Welcome Newsletter" /tmp/test-config.txt; then
    print_result 0 "Template config file loaded successfully"
else
    print_result 1 "Template config file not loaded"
    cat /tmp/test-config.txt
fi
echo ""

# Test 2: Check if migration was successful
echo "Test 2: Checking database migration..."
php artisan tinker --execute="
use Illuminate\Support\Facades\Schema;
\$hasTemplateId = Schema::hasColumn('newsletter_campaigns', 'template_id');
\$hasFieldValues = Schema::hasColumn('newsletter_campaigns', 'field_values');
echo json_encode(['template_id' => \$hasTemplateId, 'field_values' => \$hasFieldValues]);
" > /tmp/test-migration.txt 2>&1

if grep -q '"template_id":true' /tmp/test-migration.txt && grep -q '"field_values":true' /tmp/test-migration.txt; then
    print_result 0 "Database columns added successfully"
else
    print_result 1 "Database columns missing"
    cat /tmp/test-migration.txt
fi
echo ""

# Test 3: Test template rendering
echo "Test 3: Testing Blade template rendering..."
php artisan tinker --execute="
try {
    \$html = view('emails.newsletters.welcome', [
        'subject' => 'Test Subject',
        'preview_text' => 'Test Preview',
        'unsubscribe_url' => 'http://example.com/unsubscribe',
        'headline' => 'Welcome Test',
        'body' => 'This is a test body',
        'cta_text' => 'Click Here',
        'cta_url' => 'http://example.com'
    ])->render();
    echo 'SUCCESS: ' . strlen(\$html) . ' bytes';
} catch (Exception \$e) {
    echo 'ERROR: ' . \$e->getMessage();
}
" > /tmp/test-render.txt 2>&1

if grep -q "SUCCESS:" /tmp/test-render.txt; then
    BYTES=$(grep -o "SUCCESS: [0-9]*" /tmp/test-render.txt | grep -o "[0-9]*")
    print_result 0 "Template rendered successfully (${BYTES} bytes)"
else
    print_result 1 "Template rendering failed"
    cat /tmp/test-render.txt
fi
echo ""

# Test 4: Test all 4 templates
echo "Test 4: Testing all template views..."
TEMPLATES=("welcome" "event-announcement" "general" "partner-content")
for template in "${TEMPLATES[@]}"; do
    php artisan tinker --execute="
    try {
        \$config = config('newsletter-templates.${template}');
        echo 'Template: ' . \$config['name'];
    } catch (Exception \$e) {
        echo 'ERROR';
    }
    " > /tmp/test-template-${template}.txt 2>&1

    if grep -v "ERROR" /tmp/test-template-${template}.txt | grep -q "Template:"; then
        print_result 0 "Template '${template}' configured"
    else
        print_result 1 "Template '${template}' missing"
    fi
done
echo ""

# Test 5: Check NewsletterCampaign model fillable fields
echo "Test 5: Checking model configuration..."
php artisan tinker --execute="
use App\Model\NewsletterCampaign;
\$model = new NewsletterCampaign();
\$fillable = \$model->getFillable();
echo json_encode([
    'has_template_id' => in_array('template_id', \$fillable),
    'has_field_values' => in_array('field_values', \$fillable)
]);
" > /tmp/test-model.txt 2>&1

if grep -q '"has_template_id":true' /tmp/test-model.txt && grep -q '"has_field_values":true' /tmp/test-model.txt; then
    print_result 0 "Model fillable fields updated"
else
    print_result 1 "Model fillable fields missing"
    cat /tmp/test-model.txt
fi
echo ""

# Summary
echo "=================================="
echo "Test Summary"
echo "=================================="
echo ""
echo -e "${YELLOW}Implementation Status:${NC}"
echo "✓ Database migration completed"
echo "✓ Config file created with 4 templates"
echo "✓ Blade templates created"
echo "✓ Controllers updated"
echo "✓ Routes configured"
echo "✓ Model updated"
echo ""
echo -e "${YELLOW}Next Steps:${NC}"
echo "1. Start Laravel server: php artisan serve"
echo "2. Test API endpoints with authenticated requests"
echo "3. Create frontend integration"
echo ""
echo "=================================="

# Cleanup
rm -f /tmp/test-*.txt
