# Deployment Guide

Hướng dẫn deploy CuCu Note lên server production.

## 🚀 Quick Deploy với Docker Compose

### 1. Chuẩn bị Server

```bash
# Cài đặt Docker và Docker Compose
curl -fsSL https://get.docker.com -o get-docker.sh
sh get-docker.sh

# Hoặc trên Ubuntu/Debian
sudo apt-get update
sudo apt-get install docker.io docker-compose-plugin
```

### 2. Clone Repository

```bash
git clone https://github.com/Hoanganhvu123/cuccu_note.git
cd cuccu_note
```

### 3. Cấu hình Environment Variables

**Backend `.env`** (`backend/.env`):
```bash
# MongoDB
MONGODB_URI=mongodb://mongodb:27017
MONGODB_DB_NAME=cucu_note

# Authentication
CLERK_SECRET_KEY=sk_live_your_production_key
CLERK_JWKS_URL=https://your-clerk-instance.clerk.accounts.dev/.well-known/jwks.json
CLERK_ISSUER=https://your-clerk-instance.clerk.accounts.dev

# OpenAI
OPENAI_API_KEY=sk-your-openai-key

# Encryption (QUAN TRỌNG!)
# Generate: python -c "from cryptography.fernet import Fernet; print(Fernet.generate_key().decode())"
ENCRYPTION_KEY=your-generated-32-byte-base64-key

# Server
PORT=5000

# Redis
REDIS_HOST=redis
REDIS_PORT=6379
REDIS_CACHE_URL=redis
RATE_STORAGE_URI=redis://redis:6379/0

# CORS (QUAN TRỌNG: Không dùng * trong production!)
CORS_ORIGINS=https://yourdomain.com,https://www.yourdomain.com

# Production settings
DISABLE_AUTH=false
```

**Frontend `.env`** (`frontend/.env`):
```bash
VITE_API_BASE_URL=https://api.yourdomain.com
```

### 4. Deploy

```bash
# Build và start tất cả services
docker-compose up -d

# Xem logs
docker-compose logs -f

# Kiểm tra status
docker-compose ps
```

### 5. Cấu hình Nginx Reverse Proxy (Optional)

Tạo file `/etc/nginx/sites-available/cuccu-note`:

```nginx
# Backend API
server {
    listen 80;
    server_name api.yourdomain.com;

    location / {
        proxy_pass http://localhost:5000;
        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;
    }
}

# Frontend
server {
    listen 80;
    server_name yourdomain.com www.yourdomain.com;

    location / {
        proxy_pass http://localhost:3001;
        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;
    }
}
```

Enable site:
```bash
sudo ln -s /etc/nginx/sites-available/cuccu-note /etc/nginx/sites-enabled/
sudo nginx -t
sudo systemctl reload nginx
```

### 6. SSL với Let's Encrypt

```bash
sudo apt-get install certbot python3-certbot-nginx
sudo certbot --nginx -d yourdomain.com -d www.yourdomain.com -d api.yourdomain.com
```

## 🔧 Maintenance Commands

```bash
# Restart services
docker-compose restart

# Stop services
docker-compose stop

# Start services
docker-compose start

# Rebuild after code changes
docker-compose up -d --build

# View logs
docker-compose logs -f backend
docker-compose logs -f frontend

# Backup MongoDB
docker exec cuccu_mongodb mongodump --out /data/backup

# Restore MongoDB
docker exec -i cuccu_mongodb mongorestore /data/backup
```

## 📊 Monitoring

### Health Checks

- Backend: `http://localhost:5000/docs`
- Frontend: `http://localhost:3001`
- MongoDB: `docker exec cuccu_mongodb mongosh --eval "db.adminCommand('ping')"`
- Redis: `docker exec cuccu_redis redis-cli ping`

### Logs

```bash
# All logs
docker-compose logs

# Specific service
docker-compose logs backend
docker-compose logs frontend

# Follow logs
docker-compose logs -f
```

## 🔒 Security Checklist

- [ ] `ENCRYPTION_KEY` được set và không commit vào git
- [ ] `CORS_ORIGINS` chỉ cho phép domain của bạn (không dùng `*`)
- [ ] `DISABLE_AUTH=false` trong production
- [ ] `CLERK_SECRET_KEY` là production key (không phải test key)
- [ ] MongoDB có authentication enabled
- [ ] Redis có password (nếu cần)
- [ ] SSL/HTTPS được cấu hình
- [ ] Firewall chỉ mở ports cần thiết
- [ ] Regular backups được setup
- [ ] Monitoring và alerting được cấu hình

## 🚨 Troubleshooting

### Backend không start

```bash
# Check logs
docker-compose logs backend

# Check MongoDB connection
docker exec cuccu_backend python -c "from common.mongo_client import mongodb_client; import asyncio; asyncio.run(mongodb_client.connect())"
```

### Frontend không build

```bash
# Check Node version
docker exec cuccu_frontend node --version

# Rebuild
docker-compose build --no-cache frontend
```

### MongoDB connection issues

```bash
# Check MongoDB status
docker exec cuccu_mongodb mongosh --eval "db.adminCommand('ping')"

# Check network
docker network inspect cuccu_network
```

## 📈 Scaling

### Horizontal Scaling

Để scale backend:

```bash
docker-compose up -d --scale backend=3
```

### Load Balancer

Sử dụng Nginx hoặc Traefik làm load balancer cho multiple backend instances.

## 🔄 Updates

```bash
# Pull latest code
git pull origin main

# Rebuild và restart
docker-compose up -d --build

# Migrate database (nếu có)
docker exec cuccu_backend python -m alembic upgrade head
```

