# Backend Application Expert Agent

> **Specialized agent for translate.press.zone backend application development**
> Complete knowledge of API, admin panel, translation service, token economy, and WordPress plugin integration

---

## Identity & Scope

**Name:** `backend-app-expert`
**Domain:** Standalone translation API backend (deployed separately)
**Primary Files:**
- `press-zone-backend/api/**` - Node.js API server
- `press-zone-backend/admin-panel/**` - React admin dashboard (planned)
- `press-zone-backend/backup/**` - Database backup scripts
- `press-zone-backend/nginx/**` - Nginx configs with SSL
- `press-zone-backend/systemd/**` - Systemd service files
- WordPress plugin integration (client-side)

**IMPORTANT:** The backend is a STANDALONE APPLICATION located at:
`/wordpress/wp-content/press-zone-backend/`

It is NOT part of the translate-press-zone plugin. The plugin acts as a CLIENT
that connects to the backend API via REST endpoints.

**Translation Service:** Uses Google Gemini API (`gemini-3-flash-preview`)
**Deployment:** Native Node.js with systemd (not Docker)
**Production:** https://api.press.zone (dev3.press.zone server)

---

## System Architecture Overview

### 3-Tier Architecture
```
WordPress Plugin ←→ Node.js API ←→ Google Gemini API
                        ↓
                   PostgreSQL + Redis
                        ↓
                   Bull Queue Worker
```

### Component Responsibilities

1. **WordPress Plugin** (Client)
   - Sends translation jobs via REST API
   - Receives webhooks with completed translations
   - Manages API keys and user settings

2. **Node.js API Server** (Core Backend)
   - Authentication & authorization
   - Credit management & billing
   - Job queue & processing (Bull + Redis)
   - Webhook delivery
   - Admin endpoints
   - Google Gemini API integration

3. **Google Gemini API** (Translation Engine)
   - Neural translation (gemini-3-flash-preview)
   - Token-based pricing
   - High-quality multilingual support

4. **React Admin Panel** (Management Interface - Planned)
   - User management
   - Analytics & reporting
   - System settings
   - Transaction monitoring

---

## Token Economy & Pricing

### Subscription Tiers
```typescript
enum SubscriptionPlan {
  STARTER = 'starter',        // $9/month  - 100K tokens
  PROFESSIONAL = 'professional', // $29/month - 500K tokens  
  ENTERPRISE = 'enterprise'   // $99/month - 2M tokens
}
```

### Model Pricing
- **Gemini 3 Flash:** Token-based pricing (see Google Cloud pricing)
- Backend tracks token usage for accurate billing
- Credit deduction based on actual tokens consumed

### Credit System
- Credits allocated monthly based on subscription
- Real-time deduction on translation
- Automatic refunds on failed jobs
- Overage billing for enterprise plans

---

## Database Schema (PostgreSQL)

### Core Tables
```sql
-- User accounts and authentication
users (id, email, status, created_at, updated_at)
api_keys (id, user_id, key_hash, name, last_used_at)

-- Subscription and billing
subscriptions (id, user_id, plan, status, billing_cycle)
payments (id, user_id, amount, paypal_transaction_id)

-- Credit management
credit_transactions (id, user_id, type, amount, balance_after)

-- Translation jobs
translation_jobs (id, user_id, status, source_lang, target_lang, 
                 content_hash, tokens_used, cost, model_tier)

-- System monitoring
webhook_deliveries (id, job_id, url, status, attempts)
audit_logs (id, user_id, action, details, ip_address)
```

### Key Relationships
- Users → API Keys (1:many)
- Users → Subscriptions (1:1 active)
- Users → Credit Transactions (1:many)
- Users → Translation Jobs (1:many)
- Jobs → Webhook Deliveries (1:many)

---

## API Endpoints

### Authentication
```typescript
POST /auth/register     // User registration
POST /auth/login        // JWT login
POST /auth/refresh      // Token refresh
POST /auth/logout       // Logout

POST /api-keys          // Generate API key
GET  /api-keys          // List keys
DELETE /api-keys/:id    // Revoke key
```

### Translation API
```typescript
POST /translate         // Sync translation (60s timeout)
POST /jobs              // Async job submission
GET  /jobs/:id          // Job status
POST /webhooks/callback // WordPress callback endpoint
```

### Account Management
```typescript
GET  /account           // Account info + credits
GET  /account/usage     // Usage statistics
POST /subscriptions     // Create subscription
PUT  /subscriptions/:id // Update subscription
GET  /transactions      // Transaction history
```

### Admin Endpoints
```typescript
GET  /admin/analytics   // System analytics
GET  /admin/users       // User management
GET  /admin/jobs        // Job monitoring
GET  /admin/settings    // System settings
POST /admin/credits     // Manual credit allocation
```

---

## WordPress Plugin Integration

### Plugin → API Flow
1. **Authentication:** Plugin uses API key in Authorization header
2. **Job Submission:** POST to `/jobs` with translation request
3. **Webhook Delivery:** API calls plugin's callback URL when complete
4. **Credit Deduction:** Automatic based on tokens used

### API Request Format
```typescript
// Plugin sends to API
POST /jobs
{
  "job_id": "wp_12345",
  "source_lang": "en",
  "target_lang": "es", 
  "content": "<p>Hello world</p>",
  "model": "4b",
  "callback_url": "https://site.com/wp-json/translate-press-zone/v1/callback"
}

// API responds
{
  "success": true,
  "job_id": "tpz_abc123",
  "status": "processing",
  "estimated_tokens": 150
}
```

### Webhook Callback Format
```typescript
// API sends to plugin
POST https://site.com/wp-json/translate-press-zone/v1/callback
{
  "job_id": "wp_12345",
  "status": "completed",
  "translation": "<p>Hola mundo</p>",
  "tokens_used": 145,
  "cost_usd": 0.0000725
}
```

---

## Security Implementation

### API Key Authentication
```typescript
// Format: sk_live_32_random_chars
// Stored as SHA-256 hash in database
// Rate limited: 1000 requests/hour per key
```

### JWT Authentication (Admin)
```typescript
// Access token: 15 minutes expiry
// Refresh token: 7 days expiry
// Secure httpOnly cookies
```

### Webhook Security
```typescript
// HMAC-SHA256 signature verification
// Timestamp validation (5 min window)
// Retry with exponential backoff
```

### Input Validation
```typescript
// Zod schemas for all endpoints
// SQL injection prevention (Prisma ORM)
// XSS protection (content sanitization)
```

---

## Translation Service (Google Gemini API)

### Model Configuration
```typescript
// Current: Gemini 3 Flash Preview
model: 'gemini-3-flash-preview'

// Pricing: Token-based billing
// Speed: ~1-2s per translation
// Quality: High-quality neural translation
```

### Translation Pipeline
1. **Content Preprocessing:** HTML tag preservation
2. **API Request:** Google Gemini API with translation prompts
3. **Post-processing:** HTML structure restoration
4. **Token Counting:** Accurate billing calculation
5. **Queue Processing:** Bull + Redis for async jobs

---

## Admin Panel Features

### Dashboard
- Real-time metrics (jobs, revenue, users)
- Usage charts (daily/monthly trends)
- System health monitoring
- Recent activity feed

### User Management
- User search and filtering
- Subscription management
- Credit allocation/adjustment
- Account suspension/activation

### Analytics
- Revenue tracking by plan
- Translation volume metrics
- Model usage distribution
- Geographic usage patterns

### System Settings
- Model pricing configuration
- Rate limit adjustments
- Webhook retry settings
- Email notification templates

---

## Development Workflow

### Local Development
```bash
# Navigate to backend directory
cd press-zone-backend/api

# Start all services
npm run dev        # API server (port 3000)
npm run worker     # Background jobs

# Admin panel (planned - not yet implemented)
# cd press-zone-backend/admin-panel
# npm run dev      # Admin panel (port 5173)
```

### Environment Variables
```bash
# Database
DATABASE_URL="postgresql://user:pass@localhost:5432/tpz"
REDIS_HOST="localhost"
REDIS_PORT="6379"

# Authentication
JWT_ACCESS_SECRET="32-char-random-string"
JWT_REFRESH_SECRET="32-char-random-string"

# External Services
GEMINI_API_KEY="your-google-gemini-api-key"
PAYPAL_CLIENT_ID="your-paypal-client-id"
PAYPAL_CLIENT_SECRET="your-paypal-secret"

# Model Configuration
GEMINI_MODEL="gemini-3-flash-preview"
```

### Testing
```bash
npm run test           # Unit tests
npm run test:integration # Integration tests
npm run test:e2e       # End-to-end tests
```

---

## Performance & Scalability

### Caching Strategy
- Redis for session storage
- API response caching (5 min TTL)
- Database query optimization
- CDN for admin panel assets

### Queue Management
- Bull queue for async jobs
- Redis-backed job persistence
- Automatic retry with backoff
- Dead letter queue for failures

### Monitoring
- Prometheus metrics export
- Winston structured logging
- Health check endpoints
- Error tracking integration

---

## Deployment Architecture

### Production Stack
```yaml
# Native systemd deployment (not Docker)
Server: DigitalOcean dev3.press.zone

Services:
  - API: systemd user service (port 3000)
  - Worker: systemd user service (queue processing)
  - Nginx: reverse proxy with SSL (Let's Encrypt)
  - PostgreSQL: 15
  - Redis: 7

URLs:
  - API: https://api.press.zone
  - Admin: (planned) https://admin.translate.press.zone
```

### Current Deployment
- **Process Manager:** systemd user services (not Docker containers)
- **SSL:** Let's Encrypt via Nginx
- **Reverse Proxy:** Nginx with custom configs in `press-zone-backend/nginx/`
- **Service Files:** Located in `press-zone-backend/systemd/`
- **Auto-restart:** systemd handles process monitoring

### Scaling Considerations
- Horizontal API scaling (stateless)
- Database read replicas
- Redis clustering
- CDN for static assets
- Load balancer with health checks

---

## Critical Business Logic

### Credit Deduction Flow
1. **Pre-validation:** Check sufficient credits
2. **Job Processing:** Send to ML service
3. **Token Calculation:** Count actual usage
4. **Credit Deduction:** Atomic transaction
5. **Webhook Delivery:** Notify plugin
6. **Audit Logging:** Record all actions

### Subscription Management
1. **PayPal Integration:** Webhook-based billing
2. **Credit Allocation:** Monthly refresh
3. **Overage Handling:** Enterprise auto-billing
4. **Cancellation:** Immediate effect, credits retained

### Error Recovery
1. **Failed Jobs:** Automatic retry (3 attempts)
2. **Webhook Failures:** Exponential backoff
3. **Credit Refunds:** Automatic on job failure
4. **System Alerts:** Admin notifications

---

## Integration Points

### WordPress Plugin Sync
- **API Key Management:** Plugin settings sync
- **Usage Reporting:** Real-time credit display
- **Error Handling:** User-friendly messages
- **Webhook Reliability:** Guaranteed delivery

### PayPal Integration
- **Subscription Creation:** Automated billing setup
- **Webhook Processing:** Payment confirmations
- **Dispute Handling:** Automatic suspension
- **Refund Processing:** Credit adjustments

### Google Gemini API Integration
- **API Client:** Official Google AI SDK
- **Model:** gemini-3-flash-preview
- **Error Handling:** Retry with exponential backoff
- **Cost Optimization:** Token-based billing tracking

---

## Troubleshooting Guide

### Common Issues
1. **High Latency:** Check Google Gemini API response times
2. **Credit Discrepancies:** Audit transaction logs
3. **Webhook Failures:** Verify endpoint accessibility
4. **Authentication Errors:** Check API key validity
5. **Service Downtime:** Check systemd service status

### Monitoring Dashboards
- **System Health:** API response times, error rates
- **Business Metrics:** Revenue, user growth, usage
- **Technical Metrics:** Database performance, queue depth
- **Security Alerts:** Failed auth attempts, rate limits

---

## Future Enhancements

### Planned Features
- **Multi-language Admin Panel:** i18n support
- **Advanced Analytics:** Custom reporting
- **API Rate Limiting:** Per-plan limits
- **Batch Translation:** Bulk job processing
- **Translation Memory:** Content caching
- **Custom Models:** User-specific fine-tuning

### Scalability Roadmap
- **Microservices:** Service decomposition
- **Event Sourcing:** Audit trail improvements
- **GraphQL API:** Flexible data fetching
- **Real-time Updates:** WebSocket integration
- **Global CDN:** Multi-region deployment
