# Monaco USA Portal - Production Deployment Guide

## Prerequisites

- Debian/Ubuntu server with root access
- Domain DNS configured (portal.monacousa.org, api.monacousa.org, studio.monacousa.org)
- Ports 80 and 443 open in firewall

## Quick Start

### 1. First-Time Server Setup

```bash
# Clone the repository
git clone https://code.letsbe.solutions/matt/monacousa-portal.git
cd monacousa-portal

# Make deploy script executable
chmod +x deploy.sh

# Run first-time setup (installs Docker, configures firewall)
sudo ./deploy.sh setup
```

### 2. Configure Environment

```bash
# Copy environment template
cp .env.production.example .env

# Generate secrets
./deploy.sh generate-secrets

# Edit environment file with your values
nano .env
```

**Important environment variables to configure:**
- `DOMAIN` - Your domain (e.g., portal.monacousa.org)
- `POSTGRES_PASSWORD` - Strong database password
- `JWT_SECRET` - 32+ character random string
- `ANON_KEY` / `SERVICE_ROLE_KEY` - Generate at supabase.com/docs/guides/self-hosting#api-keys
- `SMTP_*` - Email server settings

### 3. Install and Configure Nginx

```bash
# Install nginx
sudo apt install nginx certbot python3-certbot-nginx -y

# Copy nginx config
sudo cp nginx/portal.monacousa.org.initial.conf /etc/nginx/sites-available/portal.monacousa.org

# Enable the site
sudo ln -s /etc/nginx/sites-available/portal.monacousa.org /etc/nginx/sites-enabled/

# Remove default site if exists
sudo rm -f /etc/nginx/sites-enabled/default

# Test config
sudo nginx -t

# Reload nginx
sudo systemctl reload nginx
```

### 4. Deploy Docker Services

```bash
# Deploy all services
./deploy.sh deploy

# Wait for services to be healthy (check status)
./deploy.sh status
```

### 5. Get SSL Certificate

```bash
# Get SSL certificate (after Docker services are running)
sudo certbot --nginx -d portal.monacousa.org -d api.monacousa.org -d studio.monacousa.org

# Test auto-renewal
sudo certbot renew --dry-run
```

## Common Commands

```bash
# View logs
./deploy.sh logs              # All services
./deploy.sh logs portal       # Portal only
./deploy.sh logs db           # Database only

# Service management
./deploy.sh status            # Check status
./deploy.sh restart           # Restart all services
./deploy.sh stop              # Stop all services

# Database
./deploy.sh backup            # Backup database
./deploy.sh restore backup.sql.gz  # Restore from backup

# Updates
./deploy.sh update            # Pull latest code and rebuild portal

# Cleanup
./deploy.sh cleanup           # Remove unused Docker resources
```

## Architecture

```
                    ┌─────────────────┐
                    │     Internet    │
                    └────────┬────────┘
                             │
                    ┌────────┴────────┐
                    │  Nginx (Host)   │
                    │   :80 / :443    │
                    │  SSL Termination│
                    └────────┬────────┘
                             │
        ┌────────────────────┼────────────────────┐
        │                    │                    │
        ▼                    ▼                    ▼
   ┌─────────┐         ┌─────────┐         ┌─────────┐
   │ Portal  │         │   API   │         │ Studio  │
   │  :7453  │         │  :7455  │         │  :7454  │
   └────┬────┘         └────┬────┘         └────┬────┘
        │                   │                   │
        │              ┌────┴────┐              │
        │              │  Kong   │              │
        │              │ Gateway │              │
        │              └────┬────┘              │
        │                   │                   │
        ▼                   ▼                   ▼
   ┌─────────────────────────────────────────────────┐
   │              Docker Network                      │
   │  ┌──────┐  ┌──────┐  ┌─────────┐  ┌──────────┐  │
   │  │  DB  │  │ Auth │  │ Storage │  │ Realtime │  │
   │  └──────┘  └──────┘  └─────────┘  └──────────┘  │
   └─────────────────────────────────────────────────┘
```

## Ports

| Service | Internal Port | External (localhost) |
|---------|---------------|---------------------|
| Portal  | 3000          | 7453                |
| Studio  | 3000          | 7454                |
| Kong    | 8000          | 7455                |

## Troubleshooting

### Services not starting

```bash
# Check Docker logs
docker logs monacousa-portal
docker logs monacousa-db
docker logs monacousa-kong

# Check if ports are in use
sudo netstat -tlnp | grep -E '7453|7454|7455'
```

### Database connection issues

```bash
# Check database health
docker exec monacousa-db pg_isready -U postgres

# View database logs
docker logs monacousa-db --tail=50
```

### Nginx issues

```bash
# Test config
sudo nginx -t

# Check error log
sudo tail -f /var/log/nginx/error.log

# Check portal access log
sudo tail -f /var/log/nginx/portal.monacousa.org.error.log
```

### SSL certificate issues

```bash
# Renew certificates manually
sudo certbot renew

# Check certificate status
sudo certbot certificates
```

## Backup Strategy

### Automated Daily Backups

Add to crontab (`crontab -e`):

```bash
# Daily database backup at 3 AM
0 3 * * * /path/to/monacousa-portal/deploy.sh backup 2>&1 | logger -t monacousa-backup
```

### Backup Storage

Backups are saved to the project directory as `backup_YYYYMMDD_HHMMSS.sql.gz`.

Consider copying to remote storage:
```bash
# Copy to remote server
scp backup_*.sql.gz user@backup-server:/backups/monacousa/
```

## Security Checklist

- [ ] Strong passwords in .env file
- [ ] Firewall enabled (only 80, 443, 22 open)
- [ ] SSL certificate installed
- [ ] Studio protected with basic auth
- [ ] Regular backups configured
- [ ] Log rotation configured
- [ ] Fail2ban installed (optional)
