# 01 — Next.js Application Structure (Target Build)

How to extend the **current Next.js App Router** application for RAG + Facebook/LinkedIn photo-video publishing (auto + manual).

> Stack today: **Next.js 15** (`package.json` ^15.3.3 / lockfile 15.5.x). Structure below stays valid for future Next.js majors (App Router, Route Handlers, `instrumentation`).

---

## 1. Current top-level layout

```
postsync_pro/
├── src/
│   ├── app/                 # pages + api route handlers
│   ├── components/
│   ├── lib/                 # ai, auth, context, db, generation, scheduling, social, storage
│   ├── store/               # zustand
│   ├── providers/
│   ├── middleware.ts
│   └── instrumentation.ts   # starts cron poller
├── db/migrations/
├── data/                    # JSON + media + website-cache
├── docs/                    # this documentation set
├── scripts/
└── package.json
```

---

## 2. Target module additions

```
src/lib/rag/                          # NEW
├── types.ts
├── ingest/{adapters,chunker,indexer}.ts
├── embed/openai-embeddings.ts
├── store/{interface,mysql-store,memory-store}.ts
├── retrieve.ts
├── prompt.ts
└── query.ts

src/lib/social/                       # EXTEND
├── publish-post.ts                   # destination-aware
├── facebook-publish.ts               # + video
├── linkedin-publish.ts               # + organization author
├── linkedin-organizations.ts         # NEW
├── facebook-destinations.ts          # NEW (optional)
└── media-upload.ts                   # NEW — user photo/video intake

src/lib/ai/                           # EXTEND
├── config.ts                         # rag chat + caption model splits
└── providers/{openai,anthropic}.ts

src/app/api/rag/                      # NEW
├── query/route.ts
└── reindex/route.ts

src/app/api/media/upload/route.ts     # NEW — authenticated upload

src/app/knowledge-base/page.tsx       # REPLACE stub — Ask + Reindex UI
src/app/live-generation/              # EXTEND — destination picker, media upload
src/app/connected-accounts/           # EXTEND — LI Company Pages, multi FB Pages
```

---

## 3. API surface (target)

| Method | Route | Auth | Purpose |
|--------|-------|------|---------|
| POST | `/api/rag/query` | Session + project own | Ask GPT-4o mini / Claude with retrieval |
| POST | `/api/rag/reindex` | Session + project own | Rebuild project chunks |
| POST | `/api/media/upload` | Session | Upload photo/video → asset URL |
| POST | `/api/generation/generate` | Session | Existing — optionally RAG-augmented |
| POST | `/api/generation/posts/[id]/publish` | Session | Manual publish with destinations[] |
| POST | `/api/scheduling/run-auto-post` | Session / ops | Manual kick of auto path |
| GET/POST | `/api/cron/scheduled-publish` | `CRON_SECRET` Bearer | Scheduled publish |
| GET | `/api/social/linkedin/organizations` | Session | List admin Company Pages |
| POST | `/api/social/linkedin/connect-org` | Session | Persist org destination |

Keep existing Meta/LinkedIn OAuth connect + callback routes.

---

## 4. Data layer changes

### 4.1 Migrations (suggested numbers continue from 008)

| Migration | Purpose |
|-----------|---------|
| `009_rag_chunks.sql` | `rag_chunks` table |
| `010_connected_account_targets.sql` | `target_type`, ensure URN/page id clarity |
| `011_media_assets_upload.sql` | user uploads metadata if not enough in `media_assets` |

### 4.2 Storage dual-write

Follow existing pattern: MariaDB primary when `DB_HOST` set; JSON fallback under `data/`.  
RAG chunks: **DB-only recommended** (large embeddings).

---

## 5. UI information architecture

| Screen | Change |
|--------|--------|
| Knowledge Base | Unhide when RAG ships: chat + sources + Reindex |
| Connected Accounts | Tabs: Facebook Pages · LinkedIn Profile · LinkedIn Company Pages |
| Live Generation | Upload photo/video · destination checkboxes · Publish now |
| Post Review | Same destination controls · partial success UI |
| Automation | Toggle: require approval before auto-publish |
| Smart Schedule | Unchanged slots; show which destinations will receive |

---

## 6. Cross-cutting concerns

| Concern | Approach |
|---------|----------|
| Auth | Replace forgeable cookies before exposing RAG/upload publicly (see code review) |
| Validation | Zod (or existing patterns) on new route bodies |
| Logging | Extend `publish-logs` / `ai_usage_logs` with `rag_*` ops |
| Config | Empty `next.config.ts` — add security headers when hardening |
| Cron | Stay single-instance or strengthen DB locks |

---

## 7. Local dev

```bash
npm run dev          # :3033
# .env.local
AI_PROVIDER=openai
OPENAI_MODEL=gpt-4o-mini
RAG_ENABLED=true
RAG_CHAT_MODEL=gpt-4o-mini
ANTHROPIC_API_KEY=...   # optional quality path
```

---

## 8. Definition of done (application-level)

- [ ] Docs in `docs/` match implemented routes  
- [ ] RAG query returns citations for a seeded project  
- [ ] Manual photo to Facebook Page + LinkedIn member  
- [ ] Manual photo to LinkedIn Company Page  
- [ ] Auto path publishes image to connected FB Page + LI targets  
- [ ] Video path documented and working for at least FB Page or YT  
- [ ] No secrets in RAG index  
