## System Admin - Quick Reference Guide

### 🚀 Getting Started

#### Step 1: Migrate Database
```bash
mysql -u root -p database_name < nexus/database/schema.sql
```

#### Step 2: Create First Admin
```bash
cd nexus/backend
node scripts/initSystemAdmin.js
```

#### Step 3: Access Console
```
Navigate to: /admin
Login with credentials from step 2
```

---

### 📋 System Admin Features

#### ✅ Admin Management
- **Check if admin exists**: `GET /api/system-admin/check`
- **Create first admin**: `POST /api/system-admin/init`
- **Add admin**: `POST /api/system-admin/add-admin`
- **Remove admin**: `POST /api/system-admin/remove-admin`
- **List admins**: `GET /api/system-admin/admins`

#### ✅ Account Management
- **Ban account**: `POST /api/system-admin/ban-account`
- **Unban account**: `POST /api/system-admin/unban-account`
- **Check ban status**: `GET /api/system-admin/ban-status/:userId`
- **List banned accounts**: `GET /api/system-admin/banned-accounts`

#### ✅ Promo Code Management
- **Create batch**: `POST /api/system-admin/promo-batches`
- **List batches**: `GET /api/system-admin/promo-batches`
- **View batch**: `GET /api/system-admin/promo-batches/:batchId`
- **Revoke code**: `POST /api/system-admin/promo-revoke`

#### ✅ Audit Logs
- **Get logs**: `GET /api/system-admin/logs`

---

### 📁 File Structure

```
nexus/
├── backend/
│   ├── src/
│   │   ├── controllers/
│   │   │   └── systemAdminController.js      [NEW]
│   │   ├── routes/
│   │   │   ├── systemAdmin.js               [NEW]
│   │   │   └── index.js                     [UPDATED]
│   │   └── middleware/
│   │       └── auth.js                      [Check requireSystemAdmin middleware]
│   └── scripts/
│       └── initSystemAdmin.js               [NEW]
├── frontend/
│   ├── js/
│   │   └── components/
│   │       └── systemAdminConsole.js        [NEW]
│   └── css/
│       └── systemAdmin.css                  [NEW]
├── database/
│   └── schema.sql                           [UPDATED - Added 3 tables]
└── docs/
    ├── system-admin.md                      [NEW - Full guide]
    └── setup.md                             [Consider updating]
```

---

### 🗄️ Database Tables Added

1. **banned_accounts** - Account suspension records
   - Tracks who banned, when, reason
   - Supports permanent/temporary bans
   - Records unban information

2. **system_admin_logs** - Audit trail
   - Logs all admin actions
   - Captures IP, user-agent
   - Tracks resource changes

3. **system_admin_sessions** - Admin sessions
   - Tracks active admin sessions
   - Optional TOTP verification status
   - Session expiration tracking

---

### 🔐 Security Features

✅ Password hashing (bcrypt)
✅ System admin role separation
✅ TOTP 2FA support (optional)
✅ Complete audit logging
✅ IP tracking
✅ Separate authorization middleware
✅ Request validation
✅ Immutable audit logs

---

### 💾 Example Usage

#### Create System Admin
```bash
POST /api/system-admin/init
{
  "email": "admin@example.com",
  "username": "sysadmin",
  "password": "SecurePassword123",
  "displayName": "System Admin"
}
```

#### Ban Account
```bash
POST /api/system-admin/ban-account
Authorization: Bearer {admin_token}
{
  "userId": "user-uuid",
  "reason": "Violation of ToS",
  "isPermanent": false
}
```

#### Create Promo Batch
```bash
POST /api/system-admin/promo-batches
Authorization: Bearer {admin_token}
{
  "name": "Q1 2024",
  "plan": "growth",
  "durationMonths": 12,
  "quantity": 100,
  "expiresAt": "2024-12-31T23:59:59Z"
}
```

---

### 🛠️ Authentication

Requires middleware check in `auth.js`:
```javascript
const requireSystemAdmin = (req, res, next) => {
  if (!req.user || !req.user.is_system_admin) {
    return res.status(403).json({ error: 'System admin access required' });
  }
  next();
};
```

---

### 📊 Promo Code Format

- **Format**: `XXX-XXX-XXX-XXX` (12 chars + 3 dashes)
- **Example**: `ABC-DEF-GHI-JKL`
- **Single-use**: Each code can only be redeemed once
- **Duration**: 6 or 12 months (configured at batch level)
- **Plan**: Can be restricted to specific plan or any plan

---

### 🎯 Key Endpoints Summary

| Method | Endpoint | Purpose |
|--------|----------|---------|
| GET | `/api/system-admin/check` | Check if admin exists |
| POST | `/api/system-admin/init` | Create first admin |
| POST | `/api/system-admin/add-admin` | Promote user to admin |
| POST | `/api/system-admin/remove-admin` | Remove admin privileges |
| GET | `/api/system-admin/admins` | List all admins |
| POST | `/api/system-admin/ban-account` | Ban user account |
| POST | `/api/system-admin/unban-account` | Unban user |
| GET | `/api/system-admin/ban-status/{id}` | Check ban status |
| GET | `/api/system-admin/banned-accounts` | List banned accounts |
| POST | `/api/system-admin/promo-batches` | Create promo batch |
| GET | `/api/system-admin/promo-batches` | List promo batches |
| GET | `/api/system-admin/promo-batches/{id}` | Get batch details |
| POST | `/api/system-admin/promo-revoke` | Revoke promo code |
| GET | `/api/system-admin/logs` | View audit logs |

---

### ⚙️ Configuration Needed

Ensure your `auth.js` middleware includes `requireSystemAdmin`:

```javascript
const requireSystemAdmin = (req, res, next) => {
  if (!req.user?.is_system_admin) {
    return res.status(403).json({ 
      error: 'System admin access required' 
    });
  }
  next();
};
```

Export it so routes can use it.

---

### 📚 Documentation Files

- [Full System Admin Guide](./system-admin.md) - Complete documentation
- [Database Schema](../database/schema.sql) - All table definitions

---

### 🤝 Support

Files created:
- ✅ Database schema updates
- ✅ Backend controller (systemAdminController.js)
- ✅ Backend routes (systemAdmin.js)
- ✅ Initialization script
- ✅ Frontend console component
- ✅ Frontend styles
- ✅ Comprehensive documentation

Everything is ready for use! Follow the Getting Started steps above.
