# Feature Plan: Autogenerierte OpenAPI / Swagger Spec + API Restructuring

**Branch:** `feature/autogen-openapi`  
**Datum:** 16. November 2025  
**Status:** ✅ Complete - Auto-generation active, Single Source of Truth established

## 🎯 Hauptziele
1. ✅ **OpenAPI Auto-Generation:** Swagger Spec wird automatisch aus Route-Definitionen generiert
2. ✅ **Konsistente API-Struktur:** Klare, REST-konforme API-Organisation für einfache KI-Navigation
3. ✅ **Single Source of Truth:** `routeMappings.js` als zentrale Route-Konfiguration
4. ✅ **Developer Experience:** Swagger UI unter `/api/docs/` (dev-only)
5. ✅ **Test Coverage:** 45 automatisierte Tests, 100% passing
6. ✅ **API Security:** Bearer Token Authentication für Admin-Endpoints

---

## 📊 API-Struktur (Ziel)

### Design-Prinzipien
- **Prefix = Zugriffsebene:** Struktur basiert auf Authentifizierung/Autorisierung
- **REST-konform:** Standard HTTP Methoden (GET, POST, PUT, PATCH, DELETE)
- **KI-freundlich:** Klare Hierarchie, vorhersagbare Patterns
- **Konsistent:** Alle Routen folgen dem gleichen Muster

### Routing-Schema

```
/api/upload              (öffentlich - Upload-Funktionen)
/api/groups              (öffentlich - Slideshow-Anzeige)
/api/manage/:token/*     (token-basiert - User-Verwaltung)
/api/admin/*             (geschützt - Moderation)
/api/system/*            (intern - Wartung)
```

### Detaillierte Endpunkte

#### 📤 Public API
```
POST   /api/upload              - Single file upload
POST   /api/upload/batch        - Batch upload
GET    /api/groups              - List approved slideshows
GET    /api/groups/:groupId     - View specific slideshow
```

#### 🔑 Management API
Token-basierter Zugriff für Slideshow-Ersteller:
```
GET    /api/manage/:token                    - Get slideshow info
PUT    /api/manage/:token/consents           - Update consents
PUT    /api/manage/:token/metadata           - Update metadata
PUT    /api/manage/:token/images/descriptions - Update image descriptions
POST   /api/manage/:token/images             - Add images
DELETE /api/manage/:token/images/:imageId    - Delete image
DELETE /api/manage/:token                    - Delete slideshow
```

#### 👮 Admin API
Geschützte Moderation- und Management-Funktionen:
```
# Moderation
GET    /api/admin/moderation/groups           - List pending slideshows
GET    /api/admin/moderation/groups/:id       - Get slideshow details
PATCH  /api/admin/groups/:id/approve          - Approve slideshow
PATCH  /api/admin/groups/:id                  - Edit slideshow
DELETE /api/admin/groups/:id/images/:imageId  - Delete single image
PATCH  /api/admin/groups/:id/images/batch-description
PUT    /api/admin/groups/:id/reorder          - Reorder images

# Logs & Monitoring
GET    /api/admin/deletion-log                - Recent deletions
GET    /api/admin/deletion-log/stats          - Deletion statistics
GET    /api/admin/management-audit            - Audit log
GET    /api/admin/rate-limiter/stats          - Rate limiter stats

# Cleanup
POST   /api/admin/cleanup/trigger             - Trigger cleanup
GET    /api/admin/cleanup/preview             - Preview cleanup targets

# Consents & Social Media
GET    /api/admin/consents/export             - Export consents (CSV)
GET    /api/admin/social-media/platforms      - List platforms
```

#### ⚙️ System API
Interne System-Operationen:
```
GET    /api/system/migration/status   - Migration status
POST   /api/system/migration/migrate  - Run migration
POST   /api/system/migration/rollback - Rollback migration
GET    /api/system/migration/health   - Health check
```

---

## 🔧 Technische Implementierung

### Komponenten
- **swagger-autogen** (v6.2.8): OpenAPI 3.0 Generation
- **swagger-ui-express** (v4.6.3): Interactive API docs
- **Custom Generator:** `src/generate-openapi.js`

### Generator-Logik
```javascript
// Pro Router-Datei einzeln scannen + Mount-Prefix anwenden
for each routerMapping {
  swaggerAutogen(tempFile, [routeFile], { basePath: prefix })
  merge paths with prefix into final spec
}
```

### Single Source of Truth
1. **Router-Files (`src/routes/*.js`)**: Enthalten nur relative Pfade
2. **Mount-Konfiguration (`src/routes/index.js`)**: Definiert Prefixes
3. **OpenAPI Generation:** `generate-openapi.js` liest beide und merged

---

## 📚 Für KI-Nutzung

### API-Hierarchie verstehen
```
/api/*                    ← Alle API-Endpoints
  ├─ /upload, /groups     ← Öffentlich
  ├─ /manage/:token/*     ← Token-basiert
  ├─ /admin/*             ← Geschützt
  └─ /system/*            ← Intern
```

### Neue Route hinzufügen
```bash
# 1. Route in passender Datei hinzufügen (z.B. admin.js)
router.get('/new-endpoint', ...)

# 2. In routeMappings.js registrieren (falls neue Datei)
{ router: 'newRoute', prefix: '/api/admin', file: 'newRoute.js' }

# 3. OpenAPI wird automatisch beim Backend-Start generiert
npm run dev

# 4. Tests schreiben: tests/api/newRoute.test.js
npm test

# 5. Swagger UI: http://localhost:5001/api/docs/
```

---

## ✅ Implementierungsstatus (November 16, 2025)

### Completed Features

✅ **Single Source of Truth**: `routeMappings.js` als zentrale Route-Konfiguration  
✅ **Auto-Generation**: OpenAPI-Spec automatisch beim Backend-Start  
✅ **Authentication**: Bearer Token für Admin-Endpoints  
✅ **Test Suite**: 45 automatisierte Tests (100% passing)  
✅ **Documentation**: `routes/README.md` + `AUTHENTICATION.md`  
✅ **Route Order Fix**: Express routing order documented & fixed

### Known Issues (Resolved)

✅ **Express Route Order**: Consent router now mounted before admin router  
✅ **Test Permissions**: Tests use `/tmp/` for uploads  
✅ **SQLite Async**: Connection properly promisified

---

## ⏱️ Aufwandsschätzung (Final)

| Phase | Zeit | Status |
|-------|------|--------|
| MVP OpenAPI Generation | 2h | ✅ Done |
| API Restructuring | 8h | ✅ Done |
| Authentication System | 4h | ✅ Done |
| Test Suite | 6h | ✅ Done |
| Documentation | 2h | ✅ Done |
| **Total** | **22h** | **100%** |

---

## 🚀 Frontend Migration Guide

**Required Changes:**

1. **Add Bearer Token**: All `/api/admin/*` calls need `Authorization: Bearer <token>` header
2. **Verify Paths**: Check against `routeMappings.js` (consent: `/api/admin/groups/by-consent`)
3. **Handle 403**: Add error handling for missing authentication
4. **Environment**: Add `REACT_APP_ADMIN_API_KEY` to `.env`

**See `AUTHENTICATION.md` for complete setup guide**

---

**Erstellt:** 16. November 2025  
**Aktualisiert:** 16. November 2025  
**Status:** ✅ Production Ready
