# Production & Development Deployment Guide

## 1. Prerequisites

- **Node.js:** v20.x or v24.x LTS
- **Package Manager:** npm v10+
- **Database:** MySQL 8.0+ (Local, MySQL Workbench, or via Docker)

---

## 2. Environment Configuration

Copy `.env.example` to `apps/api/.env`:

```bash
cp .env.example apps/api/.env
```

Ensure the following variables are configured:

| Variable | Description | Example / Recommended Value |
| :--- | :--- | :--- |
| `NODE_ENV` | Runtime environment | `development` or `production` |
| `PORT` | HTTP port | `5000` |
| `DATABASE_URL` | MySQL connection string | `mysql://root:password@localhost:3306/loan_marketplace` |
| `JWT_ACCESS_SECRET` | 32+ character access secret | Generate via `openssl rand -hex 32` |
| `JWT_REFRESH_SECRET` | 32+ character refresh secret | Generate via `openssl rand -hex 32` |
| `STORAGE_DRIVER` | Storage engine | `local` (or `s3` in cloud) |
| `STORAGE_LOCAL_DIR` | Private disk storage directory | `./uploads/documents` |
| `LENDER_INTEGRATION_MODE`| External lender mode | `mock` (or `live`) |
| `LENDER_WEBHOOK_SECRET` | Webhook verification key | Random secret string |

---

## 3. Database Initialization (MySQL)

### Option A: Using Local MySQL Server / MySQL Workbench
1. Open MySQL Workbench and ensure your MySQL server is running on port `3306`.
2. Create the database:
   ```sql
   CREATE DATABASE IF NOT EXISTS loan_marketplace CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
   ```
3. Set your username and password in `apps/api/.env`:
   ```text
   DATABASE_URL="mysql://root:your_mysql_password@localhost:3306/loan_marketplace"
   ```
4. Push schema and seed data:
   ```bash
   npm run db:push
   npm run db:seed
   ```

### Option B: Using Docker Compose
```bash
# Start MySQL 8.0 container
docker compose up -d mysql

# Push schema and seed
npm run db:push
npm run db:seed
```

---

## 4. Running the Application

### Development Mode (with hot-reload)
```bash
# Build shared library
npm run --workspace=@loan-marketplace/shared build

# Start API server
npm run dev
```

The server starts at `http://localhost:5000`:
- **API Endpoint:** `http://localhost:5000/api/v1`
- **Interactive Swagger Documentation:** `http://localhost:5000/api/docs`
- **Health Check:** `http://localhost:5000/health`

### Production Build & Run
```bash
npm run build
npm run --workspace=@loan-marketplace/api start
```

---

## 5. Testing & Quality Verification

```bash
# Run all unit tests (math, formulas, rules, magic bytes)
npm run test:unit

# Run all API integration tests
npm run test:integration

# Run entire test suite
npm test

# Run TypeScript typecheck across all workspaces
npm run typecheck
```

---

## 6. Database Migrations, Backup & Rollback

### Create and Apply Migrations
```bash
npm run db:migrate
```

### Database Backup
```bash
mysqldump -u root -p loan_marketplace > backup_$(date +%Y%m%d).sql
```

### Database Restore
```bash
mysql -u root -p loan_marketplace < backup_20261010.sql
```
