# Deployment Guide

## Overview

This guide covers deploying the Math2 Platform in various environments.

## Deployment Environments

### 1. Development (Local)

**Prerequisites:**
- Node.js 20+
- PostgreSQL 15
- Redis 7
- Docker (optional)

**Setup:**

```bash
# Clone repository
git clone https://github.com/math2/platform.git
cd platform

# Backend setup
cd backend
npm install
cp .env.example .env
# Edit .env with your values

# Database setup
npx prisma generate
npx prisma migrate dev
npm run prisma:seed

# Start backend
npm run dev

# Frontend setup (new terminal)
cd ../frontend
npm install
cp .env.local.example .env.local
# Edit .env.local with your values

# Start frontend
npm run dev
```

**Access:**
- Frontend: http://localhost:3000
- Backend API: http://localhost:3001
- Prisma Studio: http://localhost:5555

### 2. Docker Compose (Single Server)

**Prerequisites:**
- Docker 24+
- Docker Compose 2.20+
- 4GB+ RAM
- 20GB+ Disk space

**Setup:**

```bash
# Clone and configure
git clone https://github.com/math2/platform.git
cd platform

# Configure environment
./scripts/setup-secrets.sh
# Or manually:
cp .env.example .env
nano .env

# Start services
docker-compose up -d

# Run migrations
docker-compose exec backend npx prisma migrate deploy

# Verify health
./scripts/health-check.sh
```

**Environment Variables:**

```bash
# Required
NODE_ENV=production
DATABASE_URL=postgresql://mathuser:password@postgres:5432/mathdb
REDIS_HOST=redis
REDIS_PASSWORD=secure_redis_password
JWT_SECRET=your-super-secret-jwt-key-min-32-chars

# AI Service (Optional)
AI_API_KEY=your-ai-api-key
AI_API_BASE_URL=https://api.example.com/v1

# Telegram (Optional)
TELEGRAM_BOT_TOKEN=your-bot-token
TELEGRAM_ADMIN_CHAT_ID=admin-chat-id
```

**Production Checklist:**

- [ ] Change default passwords
- [ ] Set strong JWT_SECRET (min 32 chars)
- [ ] Enable SSL/TLS
- [ ] Configure firewall rules
- [ ] Set up monitoring
- [ ] Configure backups
- [ ] Test health checks
- [ ] Verify rate limiting

### 3. Production with SSL (Let's Encrypt)

**Prerequisites:**
- Domain name pointing to server
- Ports 80/443 open
- Docker Compose installed

**Setup:**

```bash
# Configure domain
export DOMAIN=mathplatform.com
export EMAIL=admin@mathplatform.com

# Run setup script
./scripts/setup-ssl.sh

# Or manually:
# 1. Copy SSL configuration
cp docker/nginx-ssl.conf docker/nginx.conf

# 2. Update .env
DOMAIN=mathplatform.com
ACME_EMAIL=admin@mathplatform.com

# 3. Start with SSL
docker-compose -f docker-compose.yml -f docker-compose.ssl.yml up -d
```

**SSL Configuration:**

```nginx
# nginx-ssl.conf
server {
    listen 80;
    server_name mathplatform.com;
    return 301 https://$server_name$request_uri;
}

server {
    listen 443 ssl http2;
    server_name mathplatform.com;

    ssl_certificate /etc/letsencrypt/live/mathplatform.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/mathplatform.com/privkey.pem;
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers 'ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256';
    ssl_prefer_server_ciphers off;

    # HSTS
    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;

    location / {
        proxy_pass http://frontend:3000;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
    }

    location /api {
        proxy_pass http://backend:3001;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
    }
}
```

### 4. Kubernetes

**Prerequisites:**
- Kubernetes 1.28+
- kubectl configured
- Helm 3.12+

**Setup:**

```bash
# Add secrets
kubectl create secret generic math-platform-secrets \
  --from-literal=DATABASE_URL="postgresql://..." \
  --from-literal=JWT_SECRET="..." \
  --from-literal=REDIS_PASSWORD="..."

# Deploy with Helm
helm install math-platform ./helm-chart \
  --namespace math-platform \
  --create-namespace \
  --set ingress.enabled=true \
  --set ingress.host=mathplatform.com

# Verify deployment
kubectl get pods -n math-platform
kubectl get svc -n math-platform
```

**Helm Values:**

```yaml
# helm-chart/values.yaml
replicaCount: 3

image:
  repository: math-platform
  tag: latest
  pullPolicy: IfNotPresent

service:
  type: ClusterIP
  port: 3001

ingress:
  enabled: true
  className: nginx
  annotations:
    cert-manager.io/cluster-issuer: letsencrypt
  hosts:
    - host: mathplatform.com
      paths:
        - path: /
          pathType: Prefix
  tls:
    - secretName: math-platform-tls
      hosts:
        - mathplatform.com

resources:
  limits:
    cpu: 1000m
    memory: 1Gi
  requests:
    cpu: 500m
    memory: 512Mi

autoscaling:
  enabled: true
  minReplicas: 3
  maxReplicas: 10
  targetCPUUtilizationPercentage: 70
```

### 5. AWS ECS

**Prerequisites:**
- AWS CLI configured
- ECS CLI installed
- VPC and Subnets configured

**Setup:**

```bash
# Create ECS cluster
ecs-cli up --cluster math-platform --region us-east-1

# Configure task definition
ecs-cli compose \
  --project-name math-platform \
  --file docker-compose.yml \
  --ecs-params ecs-params.yml \
  up

# Configure ALB
aws ecs create-service \
  --cluster math-platform \
  --service-name math-platform-service \
  --task-definition math-platform \
  --desired-count 3 \
  --load-balancers targetGroupArn=arn:aws:elasticloadbalancing:...
```

## Database Migrations

### Running Migrations

```bash
# Docker Compose
docker-compose exec backend npx prisma migrate deploy

# Kubernetes
kubectl exec -it deployment/backend -- npx prisma migrate deploy

# AWS ECS
aws ecs run-task \
  --cluster math-platform \
  --task-definition math-platform-migrate \
  --launch-type FARGATE
```

### Rollback Strategy

```bash
# Check migration status
docker-compose exec backend npx prisma migrate status

# Rollback one migration
docker-compose exec backend npx prisma migrate resolve --rolled-back "20240330120000"

# Emergency rollback
docker-compose exec backend npx prisma db execute --file ./rollback.sql
```

## Backup and Recovery

### Automated Backups

```bash
# Daily backup cron job
0 2 * * * docker-compose exec postgres pg_dump -U mathuser mathdb > /backup/mathdb_$(date +\%Y\%m\%d).sql

# Backup with compression
0 2 * * * docker-compose exec postgres pg_dump -U mathuser mathdb | gzip > /backup/mathdb_$(date +\%Y\%m\%d).sql.gz

# S3 backup
0 2 * * * docker-compose exec postgres pg_dump -U mathuser mathdb | gzip | aws s3 cp - s3://math-platform-backups/db-$(date +\%Y\%m\%d).sql.gz
```

### Recovery

```bash
# Restore from backup
# 1. Stop services
docker-compose stop backend

# 2. Restore database
docker-compose exec -T postgres psql -U mathuser mathdb < backup_20240330.sql

# 3. Restart services
docker-compose start backend

# Verify
docker-compose exec backend npx prisma migrate status
```

## Monitoring and Logging

### Health Checks

```bash
# Check service health
curl http://localhost/health

# Docker health
docker-compose ps

# Kubernetes health
kubectl get pods -n math-platform
kubectl describe pod <pod-name> -n math-platform
```

### Logs

```bash
# Docker Compose
docker-compose logs -f backend
docker-compose logs -f --tail=100 frontend

# Kubernetes
kubectl logs -f deployment/backend -n math-platform
kubectl logs -f deployment/frontend -n math-platform --all-containers

# Centralized logging (if configured)
curl https://logs.mathplatform.com/api/search?query=error
```

### Metrics

```bash
# Prometheus metrics (if enabled)
curl http://localhost:9090/metrics

# Custom application metrics
curl http://localhost:3001/metrics
```

## Scaling

### Horizontal Scaling

```bash
# Scale backend instances
docker-compose up -d --scale backend=5

# Scale workers
docker-compose up -d --scale exercise-worker=3

# Kubernetes
kubectl scale deployment backend --replicas=5 -n math-platform
```

### Vertical Scaling

Update resource limits in docker-compose.yml:

```yaml
services:
  backend:
    deploy:
      resources:
        limits:
          cpus: '2.0'
          memory: 2G
        reservations:
          cpus: '1.0'
          memory: 1G
```

## Blue-Green Deployment

```bash
# Deploy to blue environment
docker-compose -f docker-compose.yml -f docker-compose.blue.yml up -d

# Test blue environment
./scripts/test-blue.sh

# Switch traffic to blue
docker-compose exec nginx nginx -s reload

# Stop green environment
docker-compose -f docker-compose.green.yml stop
```

## Troubleshooting

### Common Issues

#### Services Won't Start

```bash
# Check logs
docker-compose logs service-name

# Check resource usage
docker stats

# Restart with cleanup
docker-compose down -v
docker-compose up -d
```

#### Database Connection Issues

```bash
# Check PostgreSQL
docker-compose exec postgres pg_isready

# Check network
docker network inspect math2_default

# Test connection
docker-compose exec backend ping postgres
```

#### Migration Failures

```bash
# Check status
docker-compose exec backend npx prisma migrate status

# Reset (WARNING: Data loss)
docker-compose exec backend npx prisma migrate reset

# Manual fix
docker-compose exec backend npx prisma migrate resolve --applied "migration_name"
```

### Performance Issues

```bash
# Check slow queries
docker-compose exec postgres psql -U mathuser -d mathdb -c "SELECT * FROM pg_stat_statements ORDER BY total_time DESC LIMIT 10;"

# Check Redis memory
docker-compose exec redis redis-cli info memory

# Analyze response times
curl -w "@curl-format.txt" -o /dev/null -s http://localhost:3001/health
```

## CI/CD Pipeline

### GitHub Actions

```yaml
# .github/workflows/deploy.yml
name: Deploy

on:
  push:
    branches: [main]

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - uses: actions/setup-node@v3
        with:
          node-version: '20'
      - run: npm ci
      - run: npm run test
      - run: npm run lint
      - run: npm run type-check

  build:
    needs: test
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - name: Build Docker images
        run: |
          docker build -t math-platform:${{ github.sha }} .
          docker tag math-platform:${{ github.sha }} math-platform:latest
      - name: Push to registry
        run: |
          echo ${{ secrets.DOCKER_PASSWORD }} | docker login -u ${{ secrets.DOCKER_USERNAME }} --password-stdin
          docker push math-platform:${{ github.sha }}

  deploy:
    needs: build
    runs-on: ubuntu-latest
    steps:
      - name: Deploy to production
        run: |
          ssh ${{ secrets.SSH_USER }}@${{ secrets.SSH_HOST }} '
            cd /opt/math-platform && \
            docker pull math-platform:${{ github.sha }} && \
            docker-compose up -d
          '
```

## Security Checklist

### Pre-Deployment

- [ ] Environment variables configured
- [ ] Secrets not in code
- [ ] SSL certificates installed
- [ ] Security headers configured
- [ ] Rate limiting enabled
- [ ] CORS properly configured
- [ ] Database encrypted at rest
- [ ] Backups configured
- [ ] Monitoring enabled
- [ ] Health checks passing

### Post-Deployment

- [ ] Verify HTTPS
- [ ] Test authentication flow
- [ ] Check security headers
- [ ] Verify rate limiting
- [ ] Test backup restoration
- [ ] Monitor error rates
- [ ] Check resource usage
- [ ] Verify logging

## Support

For deployment issues:
- Check logs: `docker-compose logs`
- Run health check: `./scripts/health-check.sh`
- Review documentation: [README.md](../README.md)
- Contact: devops@mathplatform.com
