# ⚡ Content Machine SaaS

AI-powered content pipeline platform. Multi-tenant SaaS with Stripe billing, multi-provider AI (Claude/OpenAI/Gemini), and SuperAdmin dashboard.

---

## 🏗️ Architecture

```
contentmachine-saas/
├── backend/          Node.js + Express + PostgreSQL + Redis (BullMQ)
├── frontend/         React + Tailwind CSS (Vite)
├── nginx/            Production Nginx config
└── scripts/          Deployment scripts
```

**Stack:**
- **Backend:** Node.js 20, Express, PostgreSQL 15, Redis 7, BullMQ
- **Frontend:** React 18, Tailwind CSS, Vite, React Router
- **Auth:** JWT + bcrypt
- **Payments:** Stripe (Checkout, Webhooks, Billing Portal)
- **Email:** Resend
- **AI:** Claude, OpenAI GPT, Google Gemini
- **Server:** Hetzner VPS, Nginx, PM2, Let's Encrypt SSL
- **i18n:** English + Romanian

---

## 🚀 Hetzner Deployment (Step by Step)

### 1. Create Hetzner server
- Type: **CX21** (2 vCPU, 4GB RAM) — minimum
- OS: **Ubuntu 22.04**
- Location: your choice (Nuremberg/Helsinki)
- Add your SSH key

### 2. Point your domain
```
A record:  yourdomain.com    → SERVER_IP
A record:  www.yourdomain.com → SERVER_IP
```
Wait for DNS propagation (5–30 min) before running SSL setup.

### 3. Run deployment script
```bash
ssh root@SERVER_IP
git clone https://github.com/yourusername/contentmachine-saas.git /tmp/cm
cd /tmp/cm
chmod +x scripts/deploy-hetzner.sh
bash scripts/deploy-hetzner.sh yourdomain.com admin@yourdomain.com
```

### 4. Upload code + configure
```bash
# From your local machine:
rsync -avz --exclude node_modules --exclude .git . root@SERVER_IP:/var/www/contentmachine/

# On server:
ssh root@SERVER_IP
cd /var/www/contentmachine/backend
cp .env.example .env
nano .env   # Fill in ALL values
```

### 5. Install & migrate
```bash
# Backend
cd /var/www/contentmachine/backend
npm install
npm run migrate

# Frontend
cd /var/www/contentmachine/frontend
npm install
npm run build
```

### 6. Start with PM2
```bash
cd /var/www/contentmachine/backend
pm2 start ecosystem.config.cjs --env production
pm2 save
pm2 startup   # Follow the printed command
```

### 7. Create SuperAdmin
```bash
cd /var/www/contentmachine/backend
node scripts/create-superadmin.js
```

### 8. Configure Stripe
1. Stripe Dashboard → **Developers → Webhooks → Add endpoint**
2. URL: `https://yourdomain.com/api/stripe/webhook`
3. Events to listen:
   - `checkout.session.completed`
   - `invoice.payment_succeeded`
   - `invoice.payment_failed`
   - `customer.subscription.updated`
   - `customer.subscription.deleted`
4. Copy **Webhook signing secret** → add to `.env` as `STRIPE_WEBHOOK_SECRET`

5. Create products in Stripe:
   - Starter: $29/month recurring
   - Pro: $79/month recurring
   - Agency: $199/month recurring
6. Copy Price IDs → add to `.env`

7. Update Price IDs in database:
```bash
psql $DATABASE_URL
UPDATE plans SET stripe_price_id = 'price_...' WHERE id = 'starter';
UPDATE plans SET stripe_price_id = 'price_...' WHERE id = 'pro';
UPDATE plans SET stripe_price_id = 'price_...' WHERE id = 'agency';
```

---

## ⚙️ Environment Variables

See `backend/.env.example` for all required variables.

**Critical ones:**
```env
DATABASE_URL=postgresql://contentmachine:PASSWORD@localhost:5432/contentmachine
REDIS_URL=redis://localhost:6379
JWT_SECRET=<64 random chars>
ENCRYPTION_KEY=<32 random bytes hex>   # openssl rand -hex 32
STRIPE_SECRET_KEY=sk_live_...
STRIPE_WEBHOOK_SECRET=whsec_...
STRIPE_STARTER_PRICE_ID=price_...
STRIPE_PRO_PRICE_ID=price_...
STRIPE_AGENCY_PRICE_ID=price_...
RESEND_API_KEY=re_...
EMAIL_FROM=noreply@yourdomain.com
APP_URL=https://yourdomain.com
ANTHROPIC_API_KEY=sk-ant-...    # For Starter plan users
```

---

## 👤 User Flows

### Client registration → access
1. Client visits `/register`
2. Chooses plan (Starter/Pro/Agency) + fills form
3. Account created → **14-day trial starts** (card required on upgrade)
4. Client configures brand profile in Settings
5. Pro/Agency: adds their own API keys (encrypted AES-256)
6. Runs pipeline manually OR waits for auto-run at 6 AM
7. Views generated content in Content Library

### Payment flow
1. Client clicks "Activate" / "Upgrade" in Billing
2. Redirect to **Stripe Checkout** (with 14-day trial)
3. Stripe webhook fires → account activated automatically
4. Monthly renewal → webhook keeps status active
5. Failed payment → status → `past_due`, email sent
6. Cancellation → status → `canceled`

### Pipeline execution
1. Manual: click "Run Pipeline" in dashboard
2. Auto: cron at 6 AM in user's timezone
3. Job added to **BullMQ queue** (Redis)
4. Worker picks it up → runs 9 agents in sequence
5. All output saved to `generated_content` table
6. Client sees content in Content Library

---

## 🔐 Security

- **Passwords:** bcrypt (12 rounds)
- **JWT:** 7-day expiry, signed with 64-char secret
- **API Keys:** AES-256-GCM encryption at rest
- **Rate limiting:** 20 req/15min on auth, 5 pipeline runs/hour
- **Multi-tenant:** All DB queries scoped by `user_id`
- **Stripe webhooks:** Signature verification
- **Headers:** Helmet.js (X-Frame-Options, CSP, etc.)
- **HTTPS:** Let's Encrypt via Certbot

---

## 📊 Plans & Limits

| Feature | Starter ($29) | Pro ($79) | Agency ($199) |
|---------|--------------|-----------|----------------|
| Scripts/day | 3 | 5 | 10 |
| Posts/day | 3 | 5 | 10 |
| API Keys | Platform's | Your own | Your own |
| White label | ✗ | ✗ | ✓ |
| Sub-clients | 0 | 0 | Up to 10 |
| Trial | 14 days | 14 days | 14 days |

---

## 🛠️ Development

```bash
# Terminal 1: Backend
cd backend
cp .env.example .env   # Fill in local values
npm install
npm run dev

# Terminal 2: Frontend
cd frontend
npm install
npm run dev

# Access: http://localhost:3000
# API: http://localhost:4000
```

**Local requirements:**
- Node.js 20+
- PostgreSQL running locally
- Redis running locally
- At least one AI API key

---

## 📁 Database Schema

Key tables:
- `users` — accounts, subscription status, Stripe IDs
- `plans` — Starter/Pro/Agency config
- `user_profiles` — niche, brand, voice settings
- `user_api_keys` — encrypted AI keys (AES-256)
- `pipeline_runs` — execution history per user
- `generated_content` — all AI-generated output
- `usage_logs` — token/API usage tracking
- `audit_logs` — SuperAdmin action log

---

## 🔧 Maintenance

```bash
# View logs
pm2 logs contentmachine-api

# Restart
pm2 restart contentmachine-api

# Update code
cd /var/www/contentmachine
git pull
cd backend && npm install
cd ../frontend && npm install && npm run build
pm2 restart contentmachine-api

# DB backup
pg_dump $DATABASE_URL > backup_$(date +%Y%m%d).sql

# Monitor
pm2 monit
```

---

## 📞 Support

SuperAdmin panel: `https://yourdomain.com/admin`
- Manage all users
- Change plans / ban / activate
- View MRR and pipeline stats
- Audit log of all admin actions
