# Deployment Guide

Deploy CiteFlow to production.

## Prerequisites

- Node.js 20+
- PostgreSQL database
- Redis (optional, for queue)
- Domain with SSL

## Environment Variables

```env
# Database
DATABASE_URL="postgresql://user:password@host:5432/citeflow"

# Authentication (Clerk)
NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY="pk_xxx"
CLERK_SECRET_KEY="sk_xxx"

# Payments (Stripe)
STRIPE_SECRET_KEY="sk_xxx"
STRIPE_WEBHOOK_SECRET="whsec_xxx"
NEXT_PUBLIC_STRIPE_PRICE_ID="price_xxx"

# App URL
NEXT_PUBLIC_APP_URL="https://your-domain.com"
```

## Deployment Options

### Vercel (Recommended)

1. **Connect Repository**
   ```bash
   vercel link
   ```

2. **Set Environment Variables**
   Go to Vercel Dashboard → Settings → Environment Variables

3. **Deploy**
   ```bash
   vercel --prod
   ```

4. **Run Migrations**
   ```bash
   vercel env pull .env
   npx prisma migrate deploy
   ```

### Docker

1. **Build Image**
   ```bash
   docker build -t citeflow .
   ```

2. **Run Container**
   ```bash
   docker run -p 3000:3000 \
     -e DATABASE_URL="postgresql://..." \
     -e CLERK_SECRET_KEY="..." \
     citeflow
   ```

### Self-Hosted

1. **Build Application**
   ```bash
   npm run build
   ```

2. **Run Migrations**
   ```bash
   npx prisma migrate deploy
   ```

3. **Start Server**
   ```bash
   npm start
   ```

## Database Setup

### Production Database

1. **Create Database**
   ```sql
   CREATE DATABASE citeflow;
   ```

2. **Run Migrations**
   ```bash
   npx prisma migrate deploy
   ```

3. **Seed Initial Data** (optional)
   ```bash
   npm run seed
   ```

### Connection Pooling

For production, use connection pooling:

```env
DATABASE_URL="postgresql://user:password@host:5432/citeflow?pgbouncer=true"
```

## CDN Setup

### Tracker Script

Host the tracker on a CDN for better performance:

1. Build the tracker:
   ```bash
   npm run build:tracker
   ```

2. Upload `public/tracker.js` to your CDN

3. Update the script URL in your integration

## Monitoring

### Health Check

Create a health check endpoint:

```typescript
// app/api/health/route.ts
export async function GET() {
  return Response.json({ status: 'ok' });
}
```

### Logging

Use structured logging:

```typescript
import { logger } from '@/lib/logger';

logger.info('Bot crawl logged', { bot: 'GPTBot', url: '/page' });
```

### Error Tracking

Integrate Sentry for error tracking:

```typescript
import * as Sentry from '@sentry/nextjs';

Sentry.init({
  dsn: process.env.SENTRY_DSN,
});
```

## Scaling

### Horizontal Scaling

- Use a load balancer
- Enable sticky sessions for WebSocket
- Use Redis for session storage

### Database Scaling

- Use read replicas for analytics queries
- Partition large tables by date
- Archive old data

## Security

### Headers

Add security headers in `next.config.js`:

```javascript
module.exports = {
  async headers() {
    return [{
      source: '/:path*',
      headers: [
        { key: 'X-Frame-Options', value: 'DENY' },
        { key: 'X-Content-Type-Options', value: 'nosniff' },
      ],
    }];
  },
};
```

### Rate Limiting

Implement rate limiting for API routes:

```typescript
import { rateLimit } from '@/lib/rate-limit';

export async function POST(request: Request) {
  const { success } = await rateLimit(request);
  if (!success) {
    return Response.json({ error: 'Too many requests' }, { status: 429 });
  }
  // ...
}
```

## Backup

### Database Backup

Set up automated backups:

```bash
pg_dump citeflow > backup_$(date +%Y%m%d).sql
```

### Restore

```bash
psql citeflow < backup_20240620.sql
```

---

Need help? Check the [full documentation](./README.md).
