# Apache Frontend + Docker Backend Deployment Guide

## 🏗 Architecture Overview

**Frontend**: Built React app served by your existing Apache webserver  
**Backend**: Docker containers running FastAPI + workers + database

```
Apache Webserver (Frontend) → Docker Backend Services
    └── Built React App              ├── FastAPI API (:8000)
                                     ├── Celery Workers
                                     ├── Change Stream Service
                                     ├── MongoDB
                                     └── Redis
```

## 🚀 Deployment Steps

### 1. **Deploy Backend Services**

```bash
# 1. Create production environment file
cp .env.prod.example .env.prod
# Edit .env.prod with your production values

# 2. Start backend services only
docker-compose -f docker-compose.prod.yml up -d

# 3. Verify services are running
docker-compose -f docker-compose.prod.yml ps
```

**Running Services:**
- `accessible-video-api-prod` - FastAPI API (port 8000)
- `accessible-video-worker-prod` - Celery workers
- `accessible-video-mongo-prod` - MongoDB database
- `accessible-video-redis-prod` - Redis cache/queue

### 2. **Build and Deploy Frontend to Apache**

```bash
# 1. Configure frontend environment
cd frontend
cp .env.example .env.production.local

# Edit .env.production.local:
# VITE_API_URL=https://your-api-domain.com:8000
# VITE_SENTRY_DSN=your-sentry-dsn
# VITE_ENVIRONMENT=production

# 2. Build production frontend
npm run build

# 3. Deploy to Apache document root
sudo cp -r dist/* /var/www/html/your-app/
# OR
sudo rsync -av --delete dist/ /var/www/html/your-app/
```

### 3. **Configure Apache Virtual Host**

Create `/etc/apache2/sites-available/your-app.conf`:

```apache
<VirtualHost *:443>
    ServerName your-domain.com
    ServerAlias www.your-domain.com
    DocumentRoot /var/www/html/your-app
    
    # SSL Configuration
    SSLEngine on
    SSLCertificateFile /path/to/your/certificate.crt
    SSLCertificateKeyFile /path/to/your/private.key
    
    # Security Headers
    Header always set X-Frame-Options "SAMEORIGIN"
    Header always set X-Content-Type-Options "nosniff"
    Header always set X-XSS-Protection "1; mode=block"
    Header always set Referrer-Policy "strict-origin-when-cross-origin"
    Header always set Strict-Transport-Security "max-age=31536000; includeSubDomains"
    
    # Compression
    <IfModule mod_deflate.c>
        AddOutputFilterByType DEFLATE text/plain
        AddOutputFilterByType DEFLATE text/html
        AddOutputFilterByType DEFLATE text/xml
        AddOutputFilterByType DEFLATE text/css
        AddOutputFilterByType DEFLATE application/xml
        AddOutputFilterByType DEFLATE application/xhtml+xml
        AddOutputFilterByType DEFLATE application/rss+xml
        AddOutputFilterByType DEFLATE application/javascript
        AddOutputFilterByType DEFLATE application/x-javascript
    </IfModule>
    
    # Caching for static assets
    <LocationMatch "\.(css|js|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot)$">
        ExpiresActive On
        ExpiresDefault "access plus 1 year"
        Header set Cache-Control "public, immutable"
    </LocationMatch>
    
    # Don't cache HTML files
    <LocationMatch "\.html$">
        ExpiresActive On
        ExpiresDefault "access plus 0 seconds"
        Header set Cache-Control "no-cache, no-store, must-revalidate"
    </LocationMatch>
    
    # React Router support (handle client-side routing)
    <Directory "/var/www/html/your-app">
        Options -Indexes
        AllowOverride All
        Require all granted
        
        # Fallback to index.html for client-side routing
        FallbackResource /index.html
    </Directory>
    
    # Optional: Proxy API requests (alternative to CORS)
    # ProxyPreserveHost On
    # ProxyPass /api/ http://your-docker-host:8000/api/
    # ProxyPassReverse /api/ http://your-docker-host:8000/api/
    
    # Logs
    ErrorLog ${APACHE_LOG_DIR}/your-app_error.log
    CustomLog ${APACHE_LOG_DIR}/your-app_access.log combined
</VirtualHost>

# HTTP to HTTPS redirect
<VirtualHost *:80>
    ServerName your-domain.com
    ServerAlias www.your-domain.com
    Redirect permanent / https://your-domain.com/
</VirtualHost>
```

Enable the site:
```bash
sudo a2ensite your-app.conf
sudo systemctl reload apache2
```

## ⚙️ Configuration Files Updated

### `docker-compose.prod.yml`
- ✅ Removed frontend and nginx services
- ✅ Added CORS_ORIGINS environment variable
- ✅ Backend services only (API, workers, database)

### `.env.prod.example`
- ✅ Production environment template
- ✅ CORS configuration for Apache frontend
- ✅ All required variables documented

## 🔧 CORS Configuration

Since frontend and backend are on different domains, configure CORS in your backend:

**In `.env.prod`:**
```bash
CORS_ORIGINS=https://your-domain.com,https://www.your-domain.com
```

**Backend automatically handles CORS** based on this environment variable.

## 📋 Deployment Checklist

### Backend Services
- [ ] Copy `.env.prod.example` to `.env.prod`
- [ ] Update all environment variables in `.env.prod`
- [ ] Run `docker-compose -f docker-compose.prod.yml up -d`
- [ ] Verify API accessible at `http://your-docker-host:8000/docs`
- [ ] Check logs: `docker-compose -f docker-compose.prod.yml logs -f`

### Frontend Deployment  
- [ ] Update `frontend/.env.production.local` with API URL
- [ ] Run `npm run build` in frontend directory
- [ ] Copy `dist/*` to Apache document root
- [ ] Configure Apache virtual host
- [ ] Enable site and reload Apache
- [ ] Test frontend loads and connects to API

### Security & Performance
- [ ] SSL certificate configured
- [ ] Security headers enabled
- [ ] Gzip compression enabled
- [ ] Static file caching configured
- [ ] CORS origins properly set
- [ ] Firewall rules: only expose port 8000 for API

## 🔍 Troubleshooting

### Common Issues

**CORS Errors:**
- Verify `CORS_ORIGINS` in `.env.prod` matches your domain
- Check browser dev tools for exact error

**API Connection Failed:**
- Verify `VITE_API_URL` in frontend build
- Check backend API is accessible from frontend server
- Ensure port 8000 is open and reachable

**React Router 404s:**
- Verify `FallbackResource /index.html` in Apache config
- Ensure `AllowOverride All` is set

**File Upload Issues:**
- Check Apache `LimitRequestBody` directive
- Verify backend can write to GCS bucket

### Monitoring Commands

```bash
# Backend services status
docker-compose -f docker-compose.prod.yml ps

# View logs
docker-compose -f docker-compose.prod.yml logs -f api
docker-compose -f docker-compose.prod.yml logs -f worker

# Apache status
sudo systemctl status apache2
sudo tail -f /var/log/apache2/your-app_error.log
```

## 🎯 Benefits of This Setup

✅ **Separation of Concerns** - Frontend and backend independently deployable  
✅ **Existing Infrastructure** - Uses your current Apache setup  
✅ **Scalability** - Backend can be moved to different hosts easily  
✅ **Caching** - Apache handles static file caching efficiently  
✅ **SSL Termination** - Apache handles HTTPS for frontend  
✅ **Monitoring** - Separate logs and monitoring for each tier  

Your backend services will run in Docker containers while the frontend integrates seamlessly with your existing Apache web server infrastructure.