# Beezifi Workspace — Setup Guide

## Prerequisites

| Tool | Version |
|------|---------|
| Node.js | ≥ 18.x |
| MariaDB | ≥ 10.6 |
| npm | ≥ 9.x |
| Docker + Compose | (optional) |

---

## Quick Start (Local)

### 1. Clone and install

```bash
cd nexus/backend
npm install
```

### 2. Configure environment

```bash
cp .env.example .env
```

Edit `.env` with your DB credentials and secrets:

```env
DB_HOST=localhost
DB_USER=nexus
DB_PASSWORD=your_secure_password
DB_NAME=nexus_chat

JWT_ACCESS_SECRET=<generate: openssl rand -hex 64>
JWT_REFRESH_SECRET=<generate: openssl rand -hex 64>
COOKIE_SECRET=<generate: openssl rand -hex 32>
```

### 3. Create the database

```sql
CREATE DATABASE nexus_chat CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
CREATE USER 'nexus'@'localhost' IDENTIFIED BY 'your_secure_password';
GRANT ALL PRIVILEGES ON nexus_chat.* TO 'nexus'@'localhost';
FLUSH PRIVILEGES;
```

### 4. Run migrations and seed

```bash
npm run db:migrate   # Creates all tables
npm run db:seed      # Inserts demo data (optional)
```

### 5. Start the server

```bash
# Development (auto-reload)
npm run dev

# Production
npm start
```

Open **http://localhost:3000**

### Demo accounts (after seeding)

| Email | Password | Role |
|-------|----------|------|
| admin@acme.com | Password123! | System Admin + Org Owner |
| alice@acme.com | Password123! | Org Admin |
| bob@acme.com   | Password123! | Member |
| carol@acme.com | Password123! | Member |

Workspace slug: **acme**

---

## Docker Compose

```bash
# 1. Copy and configure env
cp backend/.env.example backend/.env
# Edit backend/.env with secrets

# 2. Start everything (DB + app)
docker compose up -d

# 3. View logs
docker compose logs -f app
```

Application available at **http://localhost:3000**

---

## Production Deployment (VPS)

### Nginx reverse proxy

```nginx
server {
    listen 80;
    server_name chat.yourdomain.com;
    return 301 https://$host$request_uri;
}

server {
    listen 443 ssl http2;
    server_name chat.yourdomain.com;

    ssl_certificate     /etc/letsencrypt/live/chat.yourdomain.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/chat.yourdomain.com/privkey.pem;

    client_max_body_size 55M;

    location / {
        proxy_pass http://127.0.0.1:3000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";   # WebSocket
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_read_timeout 86400;                # Keep WS alive
    }
}
```

### Apache reverse proxy

Enable the required modules first:

```bash
sudo a2enmod proxy proxy_http proxy_wstunnel headers rewrite
sudo systemctl restart apache2
```

Example virtual host:

```apache
<VirtualHost *:80>
    ServerName workspace.yourdomain.com
    RewriteEngine On
    RewriteCond %{HTTPS} off
    RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
</VirtualHost>

<VirtualHost *:443>
    ServerName workspace.yourdomain.com

    SSLEngine on
    SSLCertificateFile    /etc/letsencrypt/live/workspace.yourdomain.com/fullchain.pem
    SSLCertificateKeyFile /etc/letsencrypt/live/workspace.yourdomain.com/privkey.pem

    ProxyPreserveHost On
    RequestHeader set X-Forwarded-Proto "https"

    # Socket.IO must be declared before the catch-all "/" proxy so
    # WebSocket upgrade requests reach the ws:// upstream correctly.
    ProxyPass        /socket.io/ ws://127.0.0.1:3000/socket.io/
    ProxyPassReverse /socket.io/ ws://127.0.0.1:3000/socket.io/

    ProxyPass        / http://127.0.0.1:3000/
    ProxyPassReverse / http://127.0.0.1:3000/

    ErrorLog ${APACHE_LOG_DIR}/workspace.yourdomain.com-error.log
    CustomLog ${APACHE_LOG_DIR}/workspace.yourdomain.com-access.log combined
</VirtualHost>
```

If the browser shows a Socket.IO error like `transport=websocket ... failed`, check that:

- `proxy_wstunnel` is enabled
- the `/socket.io/` proxy rules appear before the `/` proxy rules
- Apache was restarted after the config change

### systemd service

```ini
# /etc/systemd/system/nexus.service
[Unit]
Description=Beezifi Workspace
After=network.target mariadb.service

[Service]
Type=simple
User=nexus
WorkingDirectory=/opt/nexus/backend
ExecStart=/usr/bin/node server.js
EnvironmentFile=/opt/nexus/backend/.env
Restart=always
RestartSec=10

[Install]
WantedBy=multi-user.target
```

```bash
sudo systemctl enable --now nexus
```

---

## Environment Reference

| Variable | Description | Default |
|----------|-------------|---------|
| `PORT` | HTTP port | 3000 |
| `DB_HOST` | MariaDB host | localhost |
| `DB_PORT` | MariaDB port | 3306 |
| `DB_USER` | DB user | nexus |
| `DB_PASSWORD` | DB password | — |
| `DB_NAME` | Database name | nexus_chat |
| `DB_POOL_MAX` | Max DB connections | 20 |
| `JWT_ACCESS_SECRET` | Access token secret (≥64 chars) | — |
| `JWT_REFRESH_SECRET` | Refresh token secret (≥64 chars) | — |
| `JWT_ACCESS_EXPIRES` | Access token TTL | 15m |
| `JWT_REFRESH_EXPIRES` | Refresh token TTL | 7d |
| `COOKIE_SECRET` | Cookie signing secret | — |
| `STORAGE_TYPE` | `local` or `s3` | local |
| `UPLOAD_DIR` | File storage directory | ./uploads |
| `MAX_FILE_SIZE_MB` | Max upload size | 50 |
| `ALLOWED_ORIGINS` | CORS origins (comma-sep) | http://localhost:3000 |
| `LOG_LEVEL` | Winston log level | info |
| `RATE_LIMIT_MAX_REQUESTS` | Requests per window | 100 |
| `AUTH_RATE_LIMIT_MAX` | Auth attempts per window | 10 |

---

## File Structure

```
nexus/
├── backend/
│   ├── server.js               Entry point
│   ├── src/
│   │   ├── config/             DB, JWT, logger
│   │   ├── middleware/         Auth, tenant, rate-limit
│   │   ├── controllers/        Request handlers
│   │   ├── routes/             Express routers
│   │   ├── services/           Business logic
│   │   ├── websocket/          WS server + room manager
│   │   └── utils/              Sanitize, pagination, audit
│   └── uploads/                File storage (gitignored)
├── frontend/
│   ├── index.html
│   ├── css/                    main.css, themes.css
│   └── js/
│       ├── app.js              Bootstrap + theme
│       ├── auth.js             Login/register
│       ├── api.js              REST client
│       ├── websocket.js        WS client + reconnect
│       ├── store.js            Reactive state
│       └── components/         Chat, Sidebar, Thread, etc.
├── database/
│   ├── schema.sql
│   └── seeds.sql
├── docs/
├── Dockerfile
└── docker-compose.yml
```
