# Deployment Guide – node.ekpk.pk & whatsapp.ekpk.pk

Backend runs at **https://node.ekpk.pk**, frontend at **https://whatsapp.ekpk.pk**, using your **remote database**. Use the **Pre-Deployment Checklist** first to verify WhatsApp and the app; then follow this guide for deployment.

---

## Overview

| Component | Domain / path | Notes |
|-----------|----------------|--------|
| Backend (Node) | https://node.ekpk.pk | API, webhook, Socket.io. Runs in its own node folder on server. |
| Frontend (static) | https://whatsapp.ekpk.pk | Document root: `/home/scnbuneredu/whatsapp.ekpk.pk`. |
| Database | Remote | Configure in backend `.env` (DATABASE_URL or DB_*). |
| WhatsApp webhook | https://node.ekpk.pk/api/v1/webhooks/whatsapp | Set this in Meta Dashboard. |

---

## 1. Backend (node.ekpk.pk)

### 1.1 SSH and code

- SSH (use your key; passphrase if you set one):
  ```bash
  ssh -i /home/scnbuneredu/.ssh/hashmi your_user@server_for_node.ekpk.pk
  ```
- Go to the **node folder** for node.ekpk.pk (path on server may be e.g. `/home/scnbuneredu/node` or similar).
- Clone or upload the project; ensure `backend/unified_server` is present (or copy only that tree into the node folder).

### 1.2 Dependencies and build

```bash
cd /path/to/node/folder/backend/unified_server
npm install
# If you use Prisma:
npx prisma generate
# Optional: run migrations against remote DB
# npx prisma migrate deploy
```

### 1.3 Environment (.env)

Create or edit `.env` in `backend/unified_server` (never commit this file):

```env
NODE_ENV=production
PORT=5000

# Remote database (use your actual remote DB credentials)
DATABASE_URL=postgresql://user:password@remote-db-host:5432/dbname
# Or separate vars:
# DB_HOST=...
# DB_PORT=...
# DB_NAME=...
# DB_USER=...
# DB_PASSWORD=...

# WhatsApp / Meta (same as in Pre-Deployment Checklist)
WEBHOOK_VERIFY_TOKEN=AfsaraliKhan
GRAPH_API_TOKEN=your_meta_token_here
META_PHONE_NUMBER_ID=your_phone_number_id
META_API_VERSION=v21.0

# Allow frontend origin (for CORS)
CORS_ORIGIN=https://whatsapp.ekpk.pk
# Or SOCKET_CORS_ORIGIN if your app uses that for Socket.io
```

Replace placeholders with real values; keep credentials only on the server.

### 1.4 Process manager (PM2)

Run the backend with PM2 so it restarts on crash and survives logout:

```bash
cd /path/to/node/folder/backend/unified_server
pm2 start server.js --name "chat-automation-api"
pm2 save
pm2 startup
```

Check: `pm2 logs chat-automation-api` and `pm2 status`.

### 1.5 Nginx (reverse proxy to Node)

Ensure Nginx for **node.ekpk.pk** proxies to the Node app (e.g. port 5000). Example (adjust paths and server name):

```nginx
server {
    listen 443 ssl;
    server_name node.ekpk.pk;
    # ssl_certificate and ssl_certificate_key;

    location / {
        proxy_pass http://127.0.0.1:5000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}
```

Reload Nginx after changes. Then:

- `https://node.ekpk.pk/` or `https://node.ekpk.pk/health` should return 200.
- Webhook: `https://node.ekpk.pk/api/v1/webhooks/whatsapp?...` (see Pre-Deployment Checklist).

---

## 2. Frontend (whatsapp.ekpk.pk)

### 2.1 Build with production API URL

The app currently hardcodes `localhost:5000`. For production, the frontend must call **https://node.ekpk.pk**.

**Option A – build-time env (recommended)**  
In `frontend/` create `.env.production`:

```env
VITE_API_URL=https://node.ekpk.pk
```

The app uses `src/config.js`, which reads `VITE_API_URL`; all API clients and the socket use this. Then build:

```bash
cd frontend
npm install
npm run build
```

**Option B – no env yet**  
If you don’t add `VITE_API_URL` yet, you can do a find-and-replace in the built files (not ideal): replace `http://localhost:5000` with `https://node.ekpk.pk` in the generated JS under `frontend/dist/`. Prefer Option A for maintainability.

### 2.2 Deploy built files

- Copy the **contents** of `frontend/dist/` to the document root of whatsapp.ekpk.pk:
  - `/home/scnbuneredu/whatsapp.ekpk.pk`
- So that `index.html` is at `/home/scnbuneredu/whatsapp.ekpk.pk/index.html` and assets (e.g. `assets/`) are in the same directory.

Example (from your dev machine or CI):

```bash
rsync -avz --delete frontend/dist/ your_user@server:/home/scnbuneredu/whatsapp.ekpk.pk/
```

Or from server after uploading a zip of `dist/`:

```bash
cd /home/scnbuneredu/whatsapp.ekpk.pk
# extract or copy dist contents here
```

### 2.3 Nginx for SPA

For client-side routing (React Router), Nginx should serve `index.html` for non-file requests:

```nginx
server {
    listen 443 ssl;
    server_name whatsapp.ekpk.pk;
    root /home/scnbuneredu/whatsapp.ekpk.pk;
    index index.html;
    location / {
        try_files $uri $uri/ /index.html;
    }
    # ssl_certificate and ssl_certificate_key;
}
```

Reload Nginx. Then open https://whatsapp.ekpk.pk and test login and API calls.

---

## 3. Backend CORS and Socket

In `backend/unified_server/server.js` (or where CORS is set), allow the frontend origin in production:

- `origin: process.env.CORS_ORIGIN || 'https://whatsapp.ekpk.pk'`  
  (or an array including that origin).

If you use Socket.io, set `SOCKET_CORS_ORIGIN` (or the same CORS config) so the socket server allows `https://whatsapp.ekpk.pk`.

---

## 4. WhatsApp webhook in Meta

Only after the backend is live and the webhook URL is reachable:

1. Meta App Dashboard → WhatsApp → Configuration → Webhook.
2. **Callback URL:** `https://node.ekpk.pk/api/v1/webhooks/whatsapp`
3. **Verify token:** same as in backend `.env` (e.g. `AfsaraliKhan`).
4. Verify and save; subscribe to **messages** (and optionally message status).

---

## 5. Order of operations

1. **Pre-Deployment Checklist** – Run through it (WhatsApp env, DB, CORS, health, webhook verification test).
2. **Backend** – Deploy code, `.env`, PM2, Nginx; confirm health and webhook GET.
3. **Meta** – Set webhook URL and verify; test receive/send (checklist 1.3, 1.4).
4. **Frontend** – Build with production API URL; deploy to whatsapp.ekpk.pk; test login and messaging.

---

## 6. Security notes

- Do **not** commit `.env` or any file containing DB passwords, Meta tokens, or SSH passwords.
- Keep SSH key (`hashmi`) and passphrase private; use key-based auth only if possible.
- Use HTTPS for both domains; keep Nginx and Node updated.

---

## 7. Troubleshooting

| Issue | Check |
|-------|--------|
| 502 Bad Gateway | Node not running (pm2 status) or Nginx proxy_pass port wrong. |
| Webhook verify fails | Backend .env verify token matches Meta; Nginx forwards to Node; HTTPS works. |
| CORS errors | Backend CORS includes `https://whatsapp.ekpk.pk`; frontend uses that origin. |
| API 404 | Backend routes mounted correctly; Nginx location / proxies to Node. |
| Frontend shows old API | Rebuild with VITE_API_URL and redeploy dist. |

Use **documentation/PRE_DEPLOYMENT_CHECKLIST.md** to verify WhatsApp messaging and all requirements before and after deployment.
