# Newsletter Testing Guide

## 🧪 Complete Test Suite for All Newsletter Types

This guide shows how to test every newsletter function from the admin panel.

## 📬 Available Test Types

### **API Endpoint**
```
POST /api/v1/admin/newsletter/test
Authorization: Bearer {admin_token}
Content-Type: application/json
```

### **Request Body**
```json
{
  "email": "your-test@email.com",  // or use "emails": ["email1@test.com", "email2@test.com"]
  "type": "test_type_here"
}
```

---

## ✅ Test Cases (All Newsletter Functions)

### 1. **Subscription Flow Tests**

#### A. Setup Email (Initial Token Email)
```bash
curl -X POST http://localhost:8080/api/v1/admin/newsletter/test \
  -H "Authorization: Bearer YOUR_ADMIN_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "email": "test@example.com",
    "type": "setup"
  }'
```
**Tests**: 
- ✅ Initial subscription email with token
- ✅ Link to preference setup page
- ✅ Token generation and URL formatting

#### B. Welcome Email
```bash
curl -X POST http://localhost:8080/api/v1/admin/newsletter/test \
  -H "Authorization: Bearer YOUR_ADMIN_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "email": "test@example.com",
    "type": "welcome"
  }'
```
**Tests**: 
- ✅ Welcome introduction email
- ✅ Unsubscribe/manage links
- ✅ Club branding

#### C. Welcome Back Email (Resubscribe)
```bash
curl -X POST http://localhost:8080/api/v1/admin/newsletter/test \
  -H "Authorization: Bearer YOUR_ADMIN_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "email": "test@example.com",
    "type": "welcome_back"
  }'
```
**Tests**: 
- ✅ Resubscription email
- ✅ Preference restoration

---

### 2. **Týdenní Přehled (Weekly Overview)**

```bash
curl -X POST http://localhost:8080/api/v1/admin/newsletter/test \
  -H "Authorization: Bearer YOUR_ADMIN_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "email": "test@example.com",
    "type": "weekly"
  }'
```
**Tests**: 
- ✅ Weekly digest with all content
- ✅ Blogs section
- ✅ Events section
- ✅ Upcoming matches section
- ✅ Recent scores section
- ✅ Preference-based filtering
- ✅ Category filtering

**Individual Sections**:
```bash
# Test only blogs
"type": "blogs"

# Test only events  
"type": "events"

# Test only matches
"type": "matches"

# Test only scores
"type": "scores"
```

---

### 3. **Nadcházející Zápasy (Match Reminders)**

#### A. 48-Hour Reminder
```bash
curl -X POST http://localhost:8080/api/v1/admin/newsletter/test \
  -H "Authorization: Bearer YOUR_ADMIN_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "email": "test@example.com",
    "type": "match_reminder_48h"
  }'
```
**Tests**: 
- ✅ 48h before match alert
- ✅ Match category display
- ✅ Teams display
- ✅ Date and time
- ✅ Place/venue
- ✅ Proper formatting

#### B. Day-of Reminder
```bash
curl -X POST http://localhost:8080/api/v1/admin/newsletter/test \
  -H "Authorization: Bearer YOUR_ADMIN_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "email": "test@example.com",
    "type": "match_reminder_today"
  }'
```
**Tests**: 
- ✅ Same-day match alert
- ✅ All match details
- ✅ Urgency messaging

---

### 4. **Blog Notifications**

```bash
curl -X POST http://localhost:8080/api/v1/admin/newsletter/test \
  -H "Authorization: Bearer YOUR_ADMIN_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "email": "test@example.com",
    "type": "blog_notification"
  }'
```
**Tests**: 
- ✅ New blog release notification
- ✅ Article title and excerpt
- ✅ Link to full article
- ✅ Call-to-action button
- ✅ Proper styling

---

### 5. **Výsledky Zápasu (Match Results)**

```bash
curl -X POST http://localhost:8080/api/v1/admin/newsletter/test \
  -H "Authorization: Bearer YOUR_ADMIN_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "email": "test@example.com",
    "type": "match_result"
  }'
```
**Tests**: 
- ✅ Match result notification
- ✅ Final score display
- ✅ Date and competition
- ✅ Result formatting
- ✅ Victory/defeat messaging

---

### 6. **Basic SMTP Test**

```bash
curl -X POST http://localhost:8080/api/v1/admin/newsletter/test \
  -H "Authorization: Bearer YOUR_ADMIN_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "email": "test@example.com",
    "type": "newsletter"
  }'
```
**Tests**: 
- ✅ SMTP configuration
- ✅ Email delivery
- ✅ Basic template rendering

---

## 🎯 Complete Test Checklist

Use this checklist to verify all newsletter functions:

### Subscription & Onboarding
- [ ] **setup** - Initial setup email with token ✉️
- [ ] **welcome** - Welcome email with manage/unsubscribe ✉️
- [ ] **welcome_back** - Resubscribe email ✉️

### Content Newsletters
- [ ] **weekly** - Full weekly digest (all sections) 📅
- [ ] **blogs** - Blog-only digest 📰
- [ ] **events** - Events-only digest 🎉
- [ ] **matches** - Matches-only digest ⚽
- [ ] **scores** - Scores-only digest 🏆

### Match Notifications
- [ ] **match_reminder_48h** - 48h before match ⏰
- [ ] **match_reminder_today** - Day-of match ⏰

### Special Notifications
- [ ] **blog_notification** - New blog release 📝
- [ ] **match_result** - Post-match result 🎯

### System Test
- [ ] **newsletter** - Basic SMTP test 🔧

---

## 🖥️ Admin UI Test Buttons (Implementation Guide)

To add test buttons to your admin panel, create a test page with these buttons:

```typescript
// Example React/TypeScript implementation
const newsletterTests = [
  { type: 'setup', label: 'Setup Email', icon: '⚙️', category: 'Subscription' },
  { type: 'welcome', label: 'Welcome Email', icon: '👋', category: 'Subscription' },
  { type: 'welcome_back', label: 'Welcome Back', icon: '🔄', category: 'Subscription' },
  
  { type: 'weekly', label: 'Weekly Digest', icon: '📅', category: 'Digests' },
  { type: 'blogs', label: 'Blogs Only', icon: '📰', category: 'Digests' },
  { type: 'events', label: 'Events Only', icon: '🎉', category: 'Digests' },
  { type: 'matches', label: 'Matches Only', icon: '⚽', category: 'Digests' },
  { type: 'scores', label: 'Scores Only', icon: '🏆', category: 'Digests' },
  
  { type: 'match_reminder_48h', label: '48h Match Alert', icon: '⏰', category: 'Alerts' },
  { type: 'match_reminder_today', label: 'Today Match Alert', icon: '🔔', category: 'Alerts' },
  { type: 'blog_notification', label: 'Blog Release', icon: '📝', category: 'Alerts' },
  { type: 'match_result', label: 'Match Result', icon: '🎯', category: 'Alerts' },
  
  { type: 'newsletter', label: 'SMTP Test', icon: '🔧', category: 'System' },
];

async function sendTest(type: string, email: string) {
  const response = await fetch('/api/v1/admin/newsletter/test', {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${adminToken}`,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({ type, email }),
  });
  
  if (response.ok) {
    alert(`Test email "${type}" sent to ${email}`);
  } else {
    alert('Failed to send test email');
  }
}
```

### UI Layout Suggestion

```
┌─────────────────────────────────────────┐
│   Newsletter Testing Panel              │
├─────────────────────────────────────────┤
│                                         │
│  Test Email: [________________] 📧      │
│                                         │
│  ┌─── Subscription Flow ───────────┐   │
│  │  [⚙️ Setup Email]                │   │
│  │  [👋 Welcome Email]              │   │
│  │  [🔄 Welcome Back]               │   │
│  └──────────────────────────────────┘   │
│                                         │
│  ┌─── Content Digests ─────────────┐   │
│  │  [📅 Weekly Digest]              │   │
│  │  [📰 Blogs] [🎉 Events]          │   │
│  │  [⚽ Matches] [🏆 Scores]         │   │
│  └──────────────────────────────────┘   │
│                                         │
│  ┌─── Match Alerts ────────────────┐   │
│  │  [⏰ 48h Reminder]               │   │
│  │  [🔔 Today Reminder]             │   │
│  │  [🎯 Match Result]               │   │
│  └──────────────────────────────────┘   │
│                                         │
│  ┌─── Special Notifications ───────┐   │
│  │  [📝 Blog Release]               │   │
│  └──────────────────────────────────┘   │
│                                         │
│  ┌─── System ──────────────────────┐   │
│  │  [🔧 SMTP Test]                  │   │
│  └──────────────────────────────────┘   │
└─────────────────────────────────────────┘
```

---

## 🔍 Verification Steps

### After Sending Each Test:

1. **Check Email Inbox**
   - Verify email received
   - Check sender name and address
   - Verify subject line

2. **Verify Content**
   - Check all text renders correctly
   - Verify images load (if any)
   - Test all links work
   - Check responsive design (mobile/desktop)

3. **Test Interactive Elements**
   - Click article links (should track)
   - Click unsubscribe (should work with token)
   - Click manage preferences (should load page)

4. **Verify Analytics**
   - Check `email_log` table for entry
   - Open email and verify `email_event` logs "open"
   - Click link and verify `email_event` logs "click"

```sql
-- Check email logs
SELECT * FROM email_log ORDER BY created_at DESC LIMIT 10;

-- Check events
SELECT * FROM email_event ORDER BY created_at DESC LIMIT 10;
```

---

## 🐛 Troubleshooting

### Email Not Received?

1. **Check SMTP Configuration**
   ```sql
   SELECT smtp_host, smtp_port, smtp_from 
   FROM settings LIMIT 1;
   ```

2. **Check Spam Folder**
   - Test emails might be flagged as spam
   - Add sender to whitelist

3. **Check Server Logs**
   ```bash
   # Look for SMTP errors
   grep -i "smtp" logs/app.log
   grep -i "newsletter" logs/app.log
   ```

4. **Verify Email Address**
   - Ensure email format is valid
   - Try different email provider

### Wrong Content?

1. **Check Cache Files**
   ```bash
   ls -la cache/prefetch/
   # Should have: articles.json, events_upcoming.json, facr_club_info.json
   ```

2. **Refresh Cache**
   - Wait for prefetcher cycle (30 minutes)
   - Or manually trigger: `POST /api/v1/admin/prefetch/trigger`

### Links Not Working?

1. **Check Frontend URL**
   ```bash
   echo $FRONTEND_BASE_URL
   # Should be: http://localhost:3000 (dev) or https://your-domain.com (prod)
   ```

2. **Verify Token Generation**
   ```bash
   echo $JWT_SECRET
   # Should NOT be: "default-secret-key-change-in-production"
   ```

---

## 📊 Test Results Log Template

Use this to track your testing:

```markdown
## Newsletter Test Results - [Date]

### Subscription Flow
- [ ] Setup Email - ✅/❌ - Notes: _______
- [ ] Welcome Email - ✅/❌ - Notes: _______
- [ ] Welcome Back - ✅/❌ - Notes: _______

### Content Digests
- [ ] Weekly Digest - ✅/❌ - Notes: _______
- [ ] Blogs Only - ✅/❌ - Notes: _______
- [ ] Events Only - ✅/❌ - Notes: _______
- [ ] Matches Only - ✅/❌ - Notes: _______
- [ ] Scores Only - ✅/❌ - Notes: _______

### Match Alerts
- [ ] 48h Reminder - ✅/❌ - Notes: _______
- [ ] Today Reminder - ✅/❌ - Notes: _______
- [ ] Match Result - ✅/❌ - Notes: _______

### Special Notifications
- [ ] Blog Release - ✅/❌ - Notes: _______

### System
- [ ] SMTP Test - ✅/❌ - Notes: _______

### Analytics Verification
- [ ] Open tracking works - ✅/❌
- [ ] Click tracking works - ✅/❌
- [ ] Blog link tracking works - ✅/❌
- [ ] Unsubscribe works - ✅/❌

### Issues Found:
1. _______________________
2. _______________________
3. _______________________
```

---

## 🚀 Quick Test All (Bash Script)

Save this as `test-newsletters.sh`:

```bash
#!/bin/bash

TOKEN="YOUR_ADMIN_TOKEN"
EMAIL="your-test@email.com"
API="http://localhost:8080/api/v1/admin/newsletter/test"

test_types=(
  "setup"
  "welcome"
  "welcome_back"
  "weekly"
  "blogs"
  "events"
  "matches"
  "scores"
  "match_reminder_48h"
  "match_reminder_today"
  "blog_notification"
  "match_result"
  "newsletter"
)

for type in "${test_types[@]}"; do
  echo "Testing: $type"
  curl -X POST "$API" \
    -H "Authorization: Bearer $TOKEN" \
    -H "Content-Type: application/json" \
    -d "{\"email\":\"$EMAIL\",\"type\":\"$type\"}"
  echo ""
  sleep 2  # Delay between requests
done

echo "All tests sent to $EMAIL"
```

**Usage**:
```bash
chmod +x test-newsletters.sh
./test-newsletters.sh
```

---

## ✅ Summary

**Total Test Types Available**: 13

| Category | Test Types | Count |
|----------|-----------|-------|
| Subscription | setup, welcome, welcome_back | 3 |
| Digests | weekly, blogs, events, matches, scores | 5 |
| Alerts | match_reminder_48h, match_reminder_today, blog_notification, match_result | 4 |
| System | newsletter | 1 |

**All newsletter functions can be tested individually from the admin panel!** 🎉
