# Trippy Beats Server Deployment Guide

## Quick Start (Local Development)

```bash
# 1. Navigate to server directory
cd server

# 2. Install dependencies
npm install

# 3. Start server
npm start

# 4. Test server (in another terminal)
npm test
```

The server will be running on `http://localhost:3000`

## Production Deployment

### 1. Direct VPS/Server Deployment

```bash
# On your server:
git clone <your-repo>
cd trippy-beats/server
npm install
NODE_ENV=production PORT=3000 npm start
```

**With PM2 (recommended):**
```bash
npm install -g pm2
pm2 start server.js --name trippy-beats-server
pm2 startup  # Enable auto-restart on boot
pm2 save     # Save current configuration
```

### 2. Docker Deployment

```bash
# Build and run
cd server
docker build -t trippy-beats-server .
docker run -d -p 3000:3000 -v $(pwd)/data:/app/data --name trippy-beats trippy-beats-server

# Check logs
docker logs trippy-beats

# Stop/start
docker stop trippy-beats
docker start trippy-beats
```

### 3. Cloud Platform Deployment

#### Heroku
```bash
# In server directory
echo "node server.js" > Procfile
git init
git add .
git commit -m "Initial commit"
heroku create your-app-name
git push heroku main
```

#### DigitalOcean Apps
1. Connect GitHub repository
2. Set root directory to `/server`
3. Build command: `npm install`
4. Run command: `npm start`
5. Set environment variables if needed

#### Railway
1. Connect GitHub repository
2. Set root directory to `/server`
3. Deploy automatically

#### Render
1. Connect GitHub repository
2. Set root directory to `/server`
3. Build command: `npm install`
4. Start command: `npm start`

## Environment Configuration

### Environment Variables

Set these in your deployment environment:

```bash
# Required
PORT=3000
NODE_ENV=production

# Optional
ALLOWED_ORIGINS=https://yourgame.com,https://www.yourgame.com
RATE_LIMIT_MAX=200
```

### Nginx Reverse Proxy (recommended for production)

```nginx
server {
    listen 80;
    server_name yourdomain.com;
    
    location / {
        proxy_pass http://localhost:3000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_cache_bypass $http_upgrade;
    }
}
```

## SSL/HTTPS Setup

### With Nginx + Let's Encrypt
```bash
# Install certbot
sudo apt install certbot python3-certbot-nginx

# Get certificate
sudo certbot --nginx -d yourdomain.com

# Auto-renewal (add to crontab)
0 12 * * * /usr/bin/certbot renew --quiet
```

### With Cloudflare
1. Add your domain to Cloudflare
2. Set DNS A record to your server IP
3. Enable "Full (strict)" SSL mode
4. The proxy will handle HTTPS automatically

## Monitoring & Maintenance

### Health Checks
```bash
# Manual check
curl https://yourdomain.com/api/health

# Automated monitoring script
#!/bin/bash
if curl -f -s https://yourdomain.com/api/health > /dev/null; then
    echo "$(date): Server is healthy"
else
    echo "$(date): Server is DOWN!" | mail -s "Server Alert" admin@yourdomain.com
fi
```

### Log Management

**With PM2:**
```bash
pm2 logs trippy-beats-server
pm2 logs trippy-beats-server --lines 100
```

**With Docker:**
```bash
docker logs trippy-beats
docker logs -f trippy-beats  # Follow logs
```

### Backup Data
```bash
# Backup leaderboard data
cp server/data/leaderboard.json backups/leaderboard-$(date +%Y%m%d).json

# Automated backup script
#!/bin/bash
DATE=$(date +%Y%m%d)
cp /path/to/server/data/leaderboard.json /path/to/backups/leaderboard-$DATE.json
find /path/to/backups -name "leaderboard-*.json" -mtime +30 -delete
```

## Performance Optimization

### For High Traffic

1. **Use PM2 cluster mode:**
```bash
pm2 start server.js -i max --name trippy-beats-cluster
```

2. **Add Redis for caching:**
```javascript
// In server.js, add caching for leaderboard reads
const redis = require('redis');
const client = redis.createClient();
```

3. **Database upgrade:**
   - Replace file storage with PostgreSQL/MySQL
   - Add connection pooling
   - Use read replicas for scaling

## Security Checklist

- [ ] Set `NODE_ENV=production`
- [ ] Configure `ALLOWED_ORIGINS` for CORS
- [ ] Use HTTPS in production
- [ ] Set up rate limiting
- [ ] Regular security updates: `npm audit fix`
- [ ] Monitor server logs
- [ ] Backup data regularly
- [ ] Use strong server passwords/keys
- [ ] Configure firewall (only allow ports 22, 80, 443)

## Troubleshooting

### Server Won't Start
```bash
# Check if port is in use
lsof -i :3000

# Check server logs
npm start 2>&1 | tee server.log

# Check disk space
df -h
```

### High Memory Usage
```bash
# Monitor with PM2
pm2 monit

# Check Node.js memory
ps aux | grep node
```

### Database Issues
```bash
# Check file permissions
ls -la data/
chmod 755 data/
chmod 644 data/leaderboard.json
```

## Scaling Considerations

### Single Server (up to 1000 concurrent users)
- PM2 with cluster mode
- Nginx reverse proxy
- SSD storage

### Multiple Servers (1000+ concurrent users)
- Load balancer (Nginx/HAProxy)
- Shared database (PostgreSQL)
- Redis session store
- CDN for static assets

### High Availability
- Multiple server instances
- Database replication
- Health checks with auto-failover
- Monitoring (Prometheus + Grafana) 