# lymphoaipath-backend
AI-powered patient care pathway platform focused on lymphoproliferative disorders (DLBCL) Backend

## Multi-tenant SaaS (Subdomain → Database routing)

This backend now includes a **multi-tenant PostgreSQL connection layer** using `pg` Pools.

- **Each tenant has its own PostgreSQL database**
- **Tenant metadata lives in a separate PLATFORM database**
- A request’s **subdomain** determines which tenant database is used
- Controllers (when migrated) should use **`req.db.query(...)`** instead of a global pool

### Required environment variables

Shared connection (same credentials/host for all tenant DBs):

- **`PG_HOST`**
- **`PG_PORT`**
- **`PG_USER`**
- **`PG_PASSWORD`**

Multi-tenant additions:

- **`PG_PLATFORM_DB`**: platform database name (contains `tenants` table)
- **`PG_FALLBACK_DB`**: fallback database name for localhost/dev or unknown subdomain

Optional pool tuning:

- **`PG_POOL_MAX`** (default `10`)
- **`PG_POOL_IDLE_TIMEOUT_MS`** (default `30000`)
- **`PG_POOL_CONNECTION_TIMEOUT_MS`** (default `5000`)

### Local development subdomains

Two easy approaches:

- **`*.localhost`**: many browsers resolve `tenant.localhost` to `127.0.0.1` automatically.
  - Example: call your API at `http://tenant1.localhost:5000/api/...`
- **Hosts file**: map subdomains to localhost
  - Add entries like `127.0.0.1 tenant1.localhost tenant2.localhost` (or use a real domain if preferred)

If a subdomain is missing/unknown, the middleware will use **`PG_FALLBACK_DB`**.

## Email Configuration (SendGrid)

To enable email functionality for sending doctor welcome emails, configure SendGrid in your `.env` file:

### SendGrid Setup

1. **Create SendGrid Account**
   - Sign up at: https://signup.sendgrid.com/ (Free tier: 100 emails/day)

2. **Verify Sender Email**
   - Go to: SendGrid Dashboard → Settings → Sender Authentication
   - Click "Single Sender Verification" → "Create New Sender"
   - Fill in details and verify via email
   - This email will be used as `EMAIL_FROM`

3. **Create API Key**
   - Go to: SendGrid Dashboard → Settings → API Keys
   - Click "Create API Key"
   - Name: "LymphoAI Backend"
   - Permissions: Full Access (or Mail Send only)
   - Copy the API key (starts with `SG.`)

4. **Update `.env` File**
```env
SENDGRID_API_KEY=SG.your-actual-api-key-here
EMAIL_FROM=your-verified-email@example.com
SENDGRID_FROM_NAME=DiagnomIQ
```

### Testing Email Configuration
```bash
npm run test-email
```

### Doctor Account Creation

When an admin creates a doctor account:
- A random 12-character password is automatically generated
- The password is hashed and stored in the database
- A welcome email is sent to the doctor with their login credentials
- The doctor can login using the password from the email
