# Performance Optimization & Testing Plan

## 📊 Current Performance Status

### Metrics to Track
- **Page Load Time:** < 3 seconds (target)
- **API Response Time:** < 500ms (target)
- **Bundle Size:** < 500KB (target)
- **Core Web Vitals:**
  - LCP (Largest Contentful Paint): < 2.5s
  - FID (First Input Delay): < 100ms
  - CLS (Cumulative Layout Shift): < 0.1

---

## 🚀 Phase 6: Performance Optimizations

### Frontend Optimizations

#### 1. Image Optimization
```javascript
// Use Next.js Image component
import Image from 'next/image';

<Image
  src="/poster.png"
  alt="Poster"
  width={1080}
  height={1080}
  loading="lazy"
  quality={75}
/>
```

#### 2. Code Splitting
```javascript
// Dynamic imports for heavy components
const PosterGenerator = dynamic(
  () => import('../components/PosterGenerator'),
  { loading: () => <div>Loading...</div> }
);
```

#### 3. Caching Strategy
```javascript
// Cache API responses
const cache = new Map();

const getCachedData = async (url) => {
  if (cache.has(url) && cache.get(url).expires > Date.now()) {
    return cache.get(url).data;
  }
  const data = await fetch(url);
  cache.set(url, { data, expires: Date.now() + 3600000 });
  return data;
};
```

#### 4. Bundle Analysis
```bash
npm install --save-dev @next/bundle-analyzer

# Analyze bundle size
npm run analyze
```

### Backend Optimizations

#### 1. Database Connection Pooling
```javascript
const { Pool } = require('pg');

const pool = new Pool({
  max: 20, // max connections
  idleTimeoutMillis: 30000,
  connectionTimeoutMillis: 2000,
});
```

#### 2. Caching Layer (Redis)
```bash
npm install redis

# Cache frequently accessed data
// Cache user settings, templates, etc.
const redis = require('redis');
const client = redis.createClient();

// Set cache
await client.setEx('user:123:settings', 3600, JSON.stringify(settings));

// Get cache
const cached = await client.get('user:123:settings');
```

#### 3. Compression
```javascript
const compression = require('compression');
app.use(compression());

// Reduces response size by 70-80%
```

#### 4. Query Optimization
```sql
-- Add indexes for frequently queried columns
CREATE INDEX idx_posts_user_id ON posts(user_id);
CREATE INDEX idx_posts_created_at ON posts(created_at DESC);
CREATE INDEX idx_campaigns_status ON campaigns(status);

-- Use EXPLAIN to analyze queries
EXPLAIN ANALYZE SELECT * FROM posts WHERE user_id = $1;
```

---

## 🧪 Phase 7: Playwright Testing Setup

### Installation & Setup

```bash
npm install -D @playwright/test

# Initialize Playwright
npx playwright install

# Create tests directory
mkdir tests/e2e
```

### Test Configuration (playwright.config.ts)

```typescript
import { defineConfig, devices } from '@playwright/test';

export default defineConfig({
  testDir: './tests/e2e',
  webServer: {
    command: 'npm run dev',
    port: 3000,
    reuseExistingServer: !process.env.CI,
  },
  use: {
    baseURL: 'http://localhost:3000',
    screenshot: 'only-on-failure',
    video: 'retain-on-failure',
  },
  projects: [
    {
      name: 'chromium',
      use: { ...devices['Desktop Chrome'] },
    },
    {
      name: 'firefox',
      use: { ...devices['Desktop Firefox'] },
    },
    {
      name: 'webkit',
      use: { ...devices['Desktop Safari'] },
    },
  ],
});
```

### Test Examples

#### Auth Flow Test
```typescript
import { test, expect } from '@playwright/test';

test.describe('Authentication', () => {
  test('should register new user', async ({ page }) => {
    await page.goto('/register');
    
    await page.fill('input[name="name"]', 'John Doe');
    await page.fill('input[name="email"]', 'john@example.com');
    await page.fill('input[name="password"]', 'SecurePass123');
    await page.fill('input[name="confirmPassword"]', 'SecurePass123');
    
    await page.click('button[type="submit"]');
    
    // Wait for redirect to dashboard
    await expect(page).toHaveURL('/dashboard');
  });

  test('should show error for invalid email', async ({ page }) => {
    await page.goto('/register');
    await page.fill('input[name="email"]', 'invalid-email');
    await page.click('button[type="submit"]');
    
    const error = page.locator('text=Enter a valid email address');
    await expect(error).toBeVisible();
  });

  test('should login with valid credentials', async ({ page }) => {
    await page.goto('/login');
    await page.fill('input[name="email"]', 'john@example.com');
    await page.fill('input[name="password"]', 'SecurePass123');
    await page.click('button[type="submit"]');
    
    await expect(page).toHaveURL('/dashboard');
  });
});
```

#### Dashboard Test
```typescript
test.describe('Dashboard', () => {
  test.beforeEach(async ({ page }) => {
    // Login first
    await page.goto('/login');
    await page.fill('input[name="email"]', 'test@example.com');
    await page.fill('input[name="password"]', 'TestPass123');
    await page.click('button[type="submit"]');
    await page.waitForURL('/dashboard');
  });

  test('should display dashboard', async ({ page }) => {
    const heading = page.locator('h1');
    await expect(heading).toContainText('Dashboard');
  });

  test('should navigate to create post', async ({ page }) => {
    await page.click('text=Create Post');
    await expect(page).toHaveURL('/posts/create');
  });
});
```

#### Poster Generation Test
```typescript
test.describe('Poster Generation', () => {
  test('should generate poster with upload', async ({ page }) => {
    await page.goto('/posts/create');
    
    // Fill form
    await page.fill('textarea[name="caption"]', 'Test post content');
    
    // Upload image
    const fileInput = page.locator('input[type="file"]');
    await fileInput.setInputFiles('tests/fixtures/test-image.png');
    
    // Save draft
    await page.click('text=Save Draft');
    
    // Verify success
    const toast = page.locator('[role="status"]');
    await expect(toast).toContainText('Draft saved');
  });

  test('should generate AI poster', async ({ page }) => {
    await page.goto('/posts/create');
    
    // Select template
    await page.click('text=Gradient Burst');
    
    // Fill caption
    await page.fill('textarea[name="caption"]', 'AI generated poster test');
    
    // Generate
    await page.click('text=Generate Poster');
    
    // Wait for image
    await page.waitForSelector('img[alt="Preview"]');
  });
});
```

### Running Tests

```bash
# Run all tests
npm run test:e2e

# Run specific test file
npm run test:e2e -- auth.spec.ts

# Run in UI mode (easier debugging)
npm run test:e2e -- --ui

# Run with headed browser
npm run test:e2e -- --headed

# Generate HTML report
npm run test:e2e -- --reporter=html
npx playwright show-report
```

### CI/CD Integration

Add to `.github/workflows/test.yml`:

```yaml
name: Playwright Tests

on:
  push:
    branches: [ main, develop ]
  pull_request:
    branches: [ main ]

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - uses: actions/setup-node@v3
        with:
          node-version: '18'
      
      - run: npm ci
      - run: npx playwright install --with-deps
      - run: npm run test:e2e
      
      - uses: actions/upload-artifact@v3
        if: always()
        with:
          name: playwright-report
          path: playwright-report/
```

---

## 📋 Test Coverage Goals

### Critical Paths (Must Test)
- [x] User registration
- [x] User login
- [x] Create post with image upload
- [x] Generate AI poster
- [x] Schedule post
- [x] Create campaign
- [x] Settings updates

### Integration Tests
- API calls work correctly
- Database transactions succeed
- File uploads process
- Email sending (if implemented)

### Edge Cases
- Invalid form submission
- Network failures
- Large file uploads
- Concurrent requests
- Session expiration

---

## 🐛 Bug Tracking

### Known Issues to Fix (From Testing)
- [ ] Register form validation error display
- [ ] Poster generation timeout on slow network
- [ ] Campaign list pagination
- [ ] Settings save confirmation
- [ ] Error messages not clearing

### Performance Issues
- [ ] Dashboard loads slowly with many posts
- [ ] Poster generation memory usage spikes
- [ ] Campaign list doesn't paginate

---

## 🎯 Implementation Checklist

### To Complete:
- [ ] Run `npm install` to add security packages
- [ ] Setup Playwright test framework
- [ ] Write 10-15 critical path tests
- [ ] Run tests and fix failures
- [ ] Setup CI/CD test pipeline
- [ ] Add performance monitoring
- [ ] Implement caching layer
- [ ] Add database indexes
- [ ] Optimize images
- [ ] Enable compression

### Performance Targets:
- [ ] Reduce bundle size to < 500KB
- [ ] Page load time < 3 seconds
- [ ] API response time < 500ms
- [ ] Lighthouse score > 90

