# DailyDew Backend: Full Admin System Flow

This is the complete backend-side flow for the admin system, prepared for frontend implementation handoff.

## 1) System Overview

The admin system is cookie-authenticated and role-gated.

- Auth mechanism: JWT stored in HttpOnly cookie `dailydew_token`
- Role model: `STUDENT` and `ADMIN`
- RBAC enforcement:
  - `requireAuth` validates JWT
  - `requireAdmin` blocks non-admin users
- API base: `http://127.0.0.1:4000/api/v1`

All API responses are envelope-based:

- Success:
```json
{
  "success": true,
  "message": "...",
  "data": { }
}
```

- Error:
```json
{
  "success": false,
  "error": {
    "code": "...",
    "message": "...",
    "details": null
  },
  "meta": {
    "timestamp": "..."
  }
}
```

## 2) Auth and Session Flow (Admin)

### Step A: Login
- Endpoint: `POST /auth/login`
- Input:
```json
{
  "email": "admin@dailydewtech.com.ng",
  "password": "Password123!"
}
```
- Output includes user profile and role:
```json
{
  "success": true,
  "message": "Login successful",
  "data": {
    "user": {
      "id": "...",
      "fullName": "...",
      "email": "...",
      "role": "ADMIN"
    },
    "token": "..."
  }
}
```
- Server also sets HttpOnly cookie `dailydew_token`.

### Step B: Frontend must send credentials
Every authenticated request must include cookie credentials:

```js
fetch(url, {
  credentials: 'include'
})
```

### Step C: Optional admin guard check
- Endpoint: `GET /auth/admin-check`
- Behavior: returns 200 only for authenticated admins.

## 3) Admin Domain Modules

## 3.1 Admin Dashboard and Reports

All these routes are under `/admin` and require `requireAuth + requireAdmin`.

- `GET /admin/overview`
  - Returns counts across users, colleges, departments, courses, topics, notes, discussions, saved items, notifications, announcements, quiz attempts.

- `GET /admin/usage`
  - Returns grouped usage from `topicProgress` and `lessonProgress` by status.

- `GET /admin/students?page=&limit=`
  - Paged student list with relations and counts.

- `GET /admin/courses?page=&limit=`
  - Paged courses with topic counts.

- `GET /admin/topics?page=&limit=`
  - Paged topics with course relation and counts.

## 3.2 Catalog Management (Admin CRUD)

Route group: `/catalog`

- Public read:
  - `GET /catalog` (public snapshot for frontend browsing)

- Admin write routes:
  - `POST /catalog/colleges`
  - `PUT /catalog/colleges/:id`
  - `DELETE /catalog/colleges/:id` (archive)
  - `POST /catalog/colleges/:id/restore`

  - `POST /catalog/departments`
  - `PUT /catalog/departments/:id`
  - `DELETE /catalog/departments/:id` (archive)
  - `POST /catalog/departments/:id/restore`

  - `POST /catalog/courses`
  - `PUT /catalog/courses/:id`
  - `DELETE /catalog/courses/:id` (archive)
  - `POST /catalog/courses/:id/restore`

  - `POST /catalog/topics`
  - `PUT /catalog/topics/:id`
  - `DELETE /catalog/topics/:id` (archive)

Current behavior:
- `Topic` records are created one-by-one via `POST /catalog/topics`.
- Course creation does not yet accept comma-separated bulk topics in the same request.

## 3.3 YouTube Integration (Admin)

This module now supports persisted key handling.

### Data model
`YoutubeIntegration` stores:
- `enabled`
- `maskedKey`
- `encryptedApiKey`
- `dailyLimit`
- `lastTestedAt`

### Key handling
- Raw key is never returned to frontend.
- Raw key is encrypted before persistence.
- Search uses stored decrypted key first, then env fallback.

### Endpoints
- `GET /admin/integrations/youtube`
  - Returns current integration state.
  - If no row exists, creates one.
  - If env key exists and DB lacks encrypted key, persists it.

- `PUT /admin/integrations/youtube`
  - Body: `{ apiKey?, enabled?, dailyLimit? }`
  - If `apiKey` provided:
    - validates with a test search
    - on success, saves encrypted key + masked key + `lastTestedAt`
    - on failure, returns explicit key error

- `GET /admin/integrations/youtube/test`
  - Tests active key and returns sample item.

### Common YouTube errors and backend codes
- Missing key: `YOUTUBE_API_KEY_MISSING`
- Invalid/restricted key: `YOUTUBE_API_KEY_INVALID`
- Upstream API/network issue: `YOUTUBE_API_ERROR`

## 3.4 YouTube Search Proxy (Authenticated)

- Endpoint: `GET /youtube/search?q=...&pageToken=...&maxResults=...`
- Requires auth
- Uses active key resolution (`stored encrypted key -> env key fallback`)
- Includes cache and quota metadata in response:
  - `source: "cache" | "api"`
  - `quotaRemaining`

## 3.5 Rate Limiting and Quota (YouTube)

- Per-user rate limit middleware
- Daily quota tracking via key pattern
- Quota info exposed in admin integration response

## 4) Expected Frontend Admin Flow

1. Login as admin via `/auth/login`
2. Verify role from login payload (`role === "ADMIN"`)
3. Load admin integration state from `/admin/integrations/youtube`
4. If key update needed:
   - submit to `PUT /admin/integrations/youtube`
   - render returned `maskedKey` and `lastTestedAt`
5. Run validation via `/admin/integrations/youtube/test`
6. Use `/youtube/search` for key-dependent search UX
7. Use `/admin/overview`, `/admin/usage`, `/admin/students`, `/admin/courses`, `/admin/topics` for dashboard screens
8. Use `/catalog/*` admin routes for catalog CRUD

## 5) Known Gaps (Important)

These requested features are NOT implemented yet and should be treated as pending scope:

1. Comma-separated topic input at course creation time
- Desired: create course + parse `"topic1, topic2, topic3"` into multiple Topic rows automatically.
- Current: topics are created manually one-by-one via `POST /catalog/topics`.

2. Semester scheduler from start date
- Desired: admin sets semester start date; backend computes week ranges and distributes topics per week.
- Current: no semester planning endpoint/model exists yet.

## 6) Why 404 "Route not found" can happen

If frontend gets:
```json
{
  "success": false,
  "error": { "code": "NOT_FOUND", "message": "Route not found" }
}
```
for a route that exists in source, this usually means the running backend process is stale (old build).

Resolution:
- Stop old Node process on port 4000
- Rebuild/start backend from latest code
- Re-test route

## 7) Frontend Integration Checklist

- [ ] Always send `credentials: 'include'` on authenticated calls
- [ ] Branch admin UI by `data.user.role`
- [ ] Handle `YOUTUBE_API_KEY_INVALID` gracefully in admin settings UI
- [ ] Use `maskedKey` only; do not expect raw API key in response
- [ ] Use catalog GET endpoint as public
- [ ] Use admin-protected catalog routes for write operations

## 8) Handoff Summary for Lovable Dev

Backend is ready for:
- Admin auth + role-gated admin pages
- Admin analytics and list pages
- Admin YouTube integration with encrypted key persistence and test endpoint
- Authenticated YouTube search proxy
- Catalog CRUD for colleges/departments/courses/topics

Backend pending for requested advanced planning flow:
- Bulk comma-separated topic ingestion at course level
- Semester start-date scheduling and automatic weekly topic mapping

If needed, next backend sprint can add those two endpoints/models as Phase 2.
