# Option A Implementation Plan: One Webhook, Route by phone_number_id

This plan implements **Option A** in your project: one app webhook URL; each user connects their WhatsApp number; your system routes incoming messages by `phone_number_id` to the correct business. No per-user webhook URL.

**→ How to test:** See [HOW_TO_TEST_OPTION_A.md](./HOW_TO_TEST_OPTION_A.md) for step-by-step testing (Phases 1–3).

---

## Current state (what you already have)

| Component | Status | Notes |
|-----------|--------|--------|
| **Webhook** | ✅ Done | Single URL; `extractBusinessId` uses `phone_number_id` → `api_keys` → `integrations.business_id` |
| **Outbound send** | ✅ Done | Uses business’s `integrations` + `api_keys` (token, phone_number_id) or env fallback |
| **DB schema** | ✅ Done | `integrations` (business_id, integration_type), `api_keys` (integration_id, phone_number_id, access_token) |
| **Auth + Business** | ✅ Done | Register, Login, business by user; Settings loads/updates business |
| **Inbox** | ✅ Done | Conversations/messages per business; send uses businessId |
| **Integration API** | ❌ Missing | No backend route to create/update WhatsApp integration + api_keys for a business |
| **Connect WhatsApp UI** | ❌ Missing | No Settings section or page for user to connect their number (manual or Embedded Signup) |
| **Business on first use** | 🟡 Partial | User may have no business; need clear “Create business” or onboarding step |

---

## Implementation phases

### Phase 1: Backend – Integration API (required)

**Goal:** Allow the app to create or update a WhatsApp integration (and its api_keys) for a business when a user “connects” their number.

**Tasks:**

1. **Create integration controller**  
   - `backend/unified_server/src/controllers/integration.controller.js`  
   - `connectWhatsApp(req, res)` (or `upsertWhatsAppIntegration`):
     - Input: `businessId`, `phone_number_id`, `access_token` (and optionally `waba_id`).
     - Validate: user is allowed to manage this business (e.g. owner or team member; reuse existing auth pattern).
     - Find or create `integrations` row: `business_id`, `integration_type: "whatsapp"`, `identifier` (e.g. phone_number_id or display name), `status: "active"`.
     - Find or create `api_keys` row for that integration: `phone_number_id`, `access_token`, `is_active: true` (and `waba_id` if provided). Deactivate old keys if you want one active key per integration.
     - Return: integration id and success (and optionally mask token in response).
   - `getWhatsAppStatus(req, res)` (optional but useful):
     - Input: `businessId` (from query or auth).
     - Return: whether the business has an active WhatsApp integration (and maybe display_name / phone_number_id for UI).

2. **Create integration routes**  
   - `backend/unified_server/src/routes/integration.routes.js` (or add under an existing router).
   - `POST /api/v1/integrations/whatsapp/connect` → body: `businessId`, `phone_number_id`, `access_token` → `connectWhatsApp`.
   - `GET /api/v1/integrations/whatsapp/status?businessId=...` → `getWhatsAppStatus`.
   - Protect with `validateUser` (and ensure `businessId` is allowed for that user).

3. **Register routes**  
   - In `server.js`: `app.use("/api/v1/integrations", integrationRoutes)` (or equivalent).

4. **Optional:** Add DB index on `api_keys.phone_number_id` if you have many keys (faster webhook lookup). Prisma: `@@index([phone_number_id])` on `api_keys` and run migration.

**Deliverable:** Frontend can call `POST .../integrations/whatsapp/connect` with businessId + credentials and backend saves them; webhook and send already use this data.

**Verification (do not mark Phase 1 done until checked):**
- Backend starts without errors (`npm run dev` in `backend/unified_server`).
- `GET /api/v1/integrations/whatsapp/status?businessId=<id>&user_id=<id>` with valid auth returns `{ DATA: { connected: true|false } }`.
- `POST /api/v1/integrations/whatsapp/connect` with body `{ businessId, phone_number_id, access_token, user_id }` (owner of business) returns success and creates/updates `integrations` + `api_keys`.

---

### Phase 2: Frontend – “Connect WhatsApp” (manual) (required)

**Goal:** User can connect their WhatsApp number to their business via a form (Phone Number ID + Access Token). No Embedded Signup yet.

**Tasks:**

1. **Settings – new section or tab “Channels” / “WhatsApp”**  
   - In `SettingsPage.jsx` (or a dedicated Integrations/Channels page):
     - Get `businessId` from `user?.business?.id` or `localStorage.getItem("business_id")`.
     - If no business, show: “Create a business first” (link to create business or onboarding).
     - If business exists:
       - **Status:** Call `GET /api/v1/integrations/whatsapp/status?businessId=...` and show “Connected” (and maybe last 4 digits of phone_number_id) or “Not connected”.
       - **Form (when not connected or “Reconnect”):** Two fields: **Phone Number ID**, **Access Token** (type password), and a “Connect” button.
       - On submit: `POST /api/v1/integrations/whatsapp/connect` with `{ businessId, phone_number_id, access_token }`. On success: show “Connected” and optionally clear form; on error show message.

2. **API client**  
   - Add in `frontend/src/api/` (e.g. `integrationsApi.js` or inside existing api):
     - `getWhatsAppStatus(businessId)`, `connectWhatsApp(businessId, phone_number_id, access_token)` with auth header.

3. **Copy and docs**  
   - Short help text: “Get these from Meta Developer Dashboard → Your App → WhatsApp → API Setup” (and link to Meta docs if you want).

**Deliverable:** User with a business can open Settings → WhatsApp, paste Phone Number ID + Token, click Connect; backend stores them; incoming messages to that number are routed to that business; agent can reply from Inbox.

**Verification (do not mark Phase 2 done until checked):**
- Log in, ensure user has a business (Workspace tab). Open Settings → **Channels** tab.
- See "Not connected" or "Connected (mask)" after status loads.
- Enter Phone Number ID + Access Token, click "Connect WhatsApp"; success toast and status shows "Connected".
- Reconnect (change token and click again) works; form clears on success.

---

### Phase 3: Ensure user has a business before using Inbox (recommended)

**Goal:** Avoid “no business” state when opening Inbox or Connect WhatsApp: either create a business or show a clear prompt.

**Tasks:**

1. **Onboarding or first-login check**  
   - After login, if `user.business` is null and no `business_id` in localStorage:
     - Option A: Redirect to a short “Create your business” step (name, type) and call existing business creation API, then set `business_id` in context/localStorage.
     - Option B: Show a modal/banner: “Create a business to use the Inbox and connect WhatsApp” with a button that opens the same flow.

2. **Guard on Settings → WhatsApp and Inbox**  
   - If no business: show “Create a business first” (and link/button) instead of Connect form or empty Inbox. You already have some of this for Inbox (empty list when no businessId); make the message explicit.

**Deliverable:** New users are guided to create a business; Connect WhatsApp and Inbox are only used in the context of a business.

**Verification (do not mark Phase 3 done until checked):**
- With a user that has **no** business: open **Inbox** → see “Create a business to use the Inbox” and “Go to Settings → Workspace” / “Or create a new business”.
- Open **Contacts** → same style guard with “Create a business to manage Contacts”.
- Open **Dashboard** → see banner “Create a business to use Inbox, Contacts, and connect WhatsApp” with “Create business” button (→ /business-info).
- After creating a business (Settings → Workspace or /business-info), Inbox and Contacts load normally; banner on Dashboard disappears.

---

### Phase 4: Embedded Signup (optional, later)

**Goal:** User clicks “Connect WhatsApp” and completes Meta’s flow in your app; you get token and Phone Number ID without them copying from the dashboard.

**Tasks:**

1. **Meta app configuration**  
   - In Meta Developer: App → WhatsApp → Embedded Signup (or Configuration): enable Embedded Signup, set redirect/callback URL (your frontend or backend URL as per Meta docs).

2. **Backend: callback endpoint**  
   - Endpoint (e.g. `GET /api/v1/integrations/whatsapp/callback` or POST) that receives the **code** (or token) from Meta after Embedded Signup.
   - Exchange code for access token (Meta Graph API); then get WABA and phone number list (or default phone number) for that token.
   - Extract `phone_number_id` and `access_token` (and optionally waba_id).
   - Load or create business (e.g. from state or user session), then call the same logic as Phase 1: create/update `integrations` + `api_keys` for that business.
   - Redirect user to Settings or Inbox with success message.

3. **Frontend: “Connect with Meta” button**  
   - Instead of (or in addition to) the manual form, show “Connect with Facebook/Meta”. Button opens Meta’s Embedded Signup URL (with your app id, redirect_uri, etc.). After Meta redirects back to your callback, backend does the exchange and save; user sees “Connected”.

**Deliverable:** User can connect WhatsApp without copying credentials; optional and can be added after Phase 1–3 are stable.

---

## Suggested order of work

| Order | Phase | Priority | Reason |
|-------|--------|----------|--------|
| 1 | Phase 1 – Backend Integration API | Must | Nothing can “connect” without it. |
| 2 | Phase 2 – Frontend Connect WhatsApp (manual) | Must | Users need a way to connect; manual is enough for launch. |
| 3 | Phase 3 – Ensure business exists | Should | Avoids confusion and support issues. |
| 4 | Phase 4 – Embedded Signup | Later | Improves UX; not required for Option A to work. |

---

## Checklist (Option A “done”)

- [ ] Backend: `POST /api/v1/integrations/whatsapp/connect` creates/updates integration + api_keys for business.
- [ ] Backend: `GET /api/v1/integrations/whatsapp/status` returns connected/not and optional display info.
- [ ] Backend: Routes protected; only allowed users can connect for a given business.
- [ ] Frontend: Settings (or Integrations) has “Connect WhatsApp” with form (Phone Number ID, Access Token).
- [ ] Frontend: Shows “Connected” when integration exists; form only when not connected or reconnecting.
- [ ] Frontend: If no business, show “Create a business first” before Connect WhatsApp.
- [ ] E2E: New user can register → create business → connect WhatsApp (manual) → receive test message on that number → see it in Inbox and reply.
- [ ] (Optional) Index on `api_keys.phone_number_id`; (Optional) Embedded Signup in a later phase.

---

## Files to add or change (summary)

| File | Action |
|------|--------|
| `backend/unified_server/src/controllers/integration.controller.js` | Create: connectWhatsApp, getWhatsAppStatus |
| `backend/unified_server/src/routes/integration.routes.js` | Create: POST connect, GET status |
| `backend/unified_server/server.js` | Register integration routes |
| `frontend/src/api/integrationsApi.js` (or similar) | Create: getWhatsAppStatus, connectWhatsApp |
| `frontend/src/components/pages/Settings/SettingsPage.jsx` | Add section/tab “WhatsApp” / “Channels” with form and status |
| (Optional) `prisma/schema.prisma` | Add `@@index([phone_number_id])` on api_keys; migrate |
| (Later) Backend callback + Frontend “Connect with Meta” | Phase 4 |

---

## Reference

- User flow: `documentation/USER_FLOW_SIGNUP_TO_WHATSAPP.md`
- Option A vs B: `documentation/WHATSAPP_MULTI_USER_RESEARCH.md`
- Webhook test: `documentation/TEST_WHATSAPP_WEBHOOK.md`
