# Production Deployment Guide: Insurance Border API

This guide provides step-by-step instructions for deploying the **Insurance Border API** (`insurance-border-api`) to a production environment using either **Docker Orchestration** (recommended) or a standard **Linux VPS (Systemd + Nginx)** setup.

---

## 1. Pre-Deployment Security & Environment Setup

Before launching in production, ensure your environment variables in `.env` are configured securely.

### Generate Production Keys
Run the following commands in Python to generate secure secret keys:
```bash
# JWT Secret Key
python -c "import secrets; print(secrets.token_urlsafe(32))"

# Fernet Base64 Encryption Key
python -c "from cryptography.fernet import Fernet; print(Fernet.generate_key().decode())"
```

### Production `.env` File Example
Create `/var/www/insurance_border_backend/.env` (or project root `.env`):
```env
# Production Environment Flags
DEBUG=false
TESTING=false
PRODUCTION=true

# Database Configuration (Production PostgreSQL)
DATABASE_URL=postgresql://insurance_user:SECURE_PASSWORD@localhost:5432/insurance_db

# Security & Tokens
SECRET_KEY=YOUR_GENERATED_JWT_SECRET_KEY
ENCRYPTION_KEY=YOUR_GENERATED_BASE64_FERNET_KEY
ALGORITHM=HS256
ACCESS_TOKEN_EXPIRE_MINUTES=60

# API Meta
API_V1_STR=/api/v1
PROJECT_NAME=Insurance Border API
VERSION=1.0.0

# CORS Configuration (Set strictly to your domain frontend URLs)
BACKEND_CORS_ORIGINS=["https://insuranceborder.com", "https://app.insuranceborder.com"]
FRONTEND_URL=https://insuranceborder.com

# Redis Caching (Optional but recommended)
REDIS_URL=redis://localhost:6379/0
CACHE_TTL=3600

# Rate Limiting
RATE_LIMIT_PER_MINUTE=120
RATE_LIMIT_PER_HOUR=2000

# File Upload Constraints
MAX_FILE_SIZE=10485760
ALLOWED_FILE_TYPES=pdf,jpg,jpeg,png,doc,docx
```

---

## 2. Deployment Option A: Docker Compose (Recommended)

Docker Compose provisions the backend API, PostgreSQL, Redis, and Nginx reverse proxy automatically.

### Prerequisites
- Docker Engine 20.10+ installed
- Docker Compose v2+ installed

### Step-by-Step Instructions

1. **Clone & Configure Environment**:
   ```bash
   git clone https://gitlab.com/Asritha.S/insurance_border_backend.git /opt/insurance-border-api
   cd /opt/insurance-border-api
   cp .env.example .env
   # Edit .env with your production values
   nano .env
   ```

2. **Start Services in Background**:
   ```bash
   docker compose up -d --build
   ```

3. **Run Database Migrations**:
   ```bash
   docker compose exec backend alembic upgrade head
   ```

4. **Verify Health**:
   ```bash
   curl http://localhost:8000/health
   # Expected output: {"status":"ok","service":"Insurance Border API"}
   ```

5. **Enable SSL with Certbot**:
   ```bash
   sudo apt install -y certbot python3-certbot-nginx
   sudo certbot --nginx -d api.insuranceborder.com
   ```

---

## 3. Deployment Option B: Linux VPS (Systemd + Nginx)

For standard Ubuntu / Debian / CentOS Linux servers.

### Step 1: System Dependencies & PostgreSQL Setup
```bash
sudo apt update && sudo apt install -y python3-pip python3-venv nginx postgresql postgresql-contrib redis-server

# Create PostgreSQL database and user
sudo -u postgres psql -c "CREATE DATABASE insurance_db;"
sudo -u postgres psql -c "CREATE USER insurance_user WITH PASSWORD 'SECURE_PASSWORD';"
sudo -u postgres psql -c "GRANT ALL PRIVILEGES ON DATABASE insurance_db TO insurance_user;"
```

### Step 2: Code Deployment & Virtual Environment
```bash
sudo mkdir -p /var/www/insurance_border_backend
sudo chown -R $USER:www-data /var/www/insurance_border_backend
git clone https://gitlab.com/Asritha.S/insurance_border_backend.git /var/www/insurance_border_backend

cd /var/www/insurance_border_backend
python3 -m venv venv
source venv/bin/activate
pip install --upgrade pip
pip install -r requirements.txt

# Run migrations
alembic upgrade head
```

### Step 3: Configure Systemd Service
Copy service file and start the backend daemon:
```bash
sudo cp deployment/systemd/backend.service /etc/systemd/system/backend.service
sudo systemctl daemon-reload
sudo systemctl enable backend
sudo systemctl start backend
sudo systemctl status backend
```

### Step 4: Configure Nginx Reverse Proxy
```bash
sudo cp deployment/nginx/backend.conf /etc/nginx/sites-available/backend.conf
sudo ln -s /etc/nginx/sites-available/backend.conf /etc/nginx/sites-enabled/
sudo nginx -t
sudo systemctl restart nginx
```

### Step 5: Enable SSL (HTTPS)
```bash
sudo certbot --nginx -d api.insuranceborder.com
```

---

## 4. Verification & Health Monitoring

Verify all critical endpoints after deployment:

| Check | Endpoint | Expected Result |
|---|---|---|
| **API Status** | `GET /` | `{"message":"Backend running","service":"Insurance Border API"}` |
| **Health Check** | `GET /health` | `{"status":"ok","service":"Insurance Border API"}` |
| **Database Reachability** | `GET /db-test` | `{"database":"connected"}` |

### Inspection & Logs
- **Systemd Service Logs**:
  ```bash
  journalctl -u backend -f -n 100
  ```
- **Docker Container Logs**:
  ```bash
  docker compose logs -f backend
  ```
- **Nginx Access & Error Logs**:
  ```bash
  tail -f /var/log/nginx/access.log
  tail -f /var/log/nginx/error.log
  ```

---

## 5. Maintenance & Database Backups

### Automated Automated Deployment
Execute the automated deploy script on code updates:
```bash
./deployment/scripts/deploy.sh production /var/www/insurance_border_backend
```

### Daily Database Backup Cron Job
Add to `/etc/crontab`:
```cron
0 2 * * * postgres pg_dump insurance_db | gzip > /var/backups/insurance_db_$(date +\%Y\%m\%d).sql.gz
```
