# Embed Addon - Troubleshooting & Fix

## 🔧 Issues Fixed

### Problem: Blank white page on embed-config

**Root Causes:**
1. ❌ `get_embed_keys` tidak return `embed_app_sec`
2. ❌ `update_embed_config` tidak ada validation
3. ❌ `get_web_pvt` return semua kolom (performance issue)
4. ❌ Missing `webhook_url` di response
5. ❌ Inconsistent response format

---

## ✅ Fixes Applied

### 1. **routes/user.js** - `/get_embed_keys`

**Before:**
```javascript
// Missing embed_app_sec, no webhook_url
const [web] = await query(`SELECT * FROM web_private`, []);
res.json({
  data: {
    embed_app_id: web?.embed_app_id || null,
    embed_app_config: web?.embed_app_config || null,
  }
});
```

**After:**
```javascript
const [web] = await query(
  `SELECT embed_app_id, embed_app_sec, embed_app_config FROM web_private`,
  []
);
res.json({
  success: true,
  data: {
    embed_app_id: web.embed_app_id || null,
    embed_app_sec: web.embed_app_sec || null,
    embed_app_config: web.embed_app_config || null,
    webhook_url: `${process.env.BACKURI}/api/inbox/embed/webhook`,
  }
});
```

---

### 2. **routes/admin.js** - `/update_embed_config`

**Before:**
```javascript
// No validation, no WHERE clause
await query(
  `UPDATE web_private SET embed_app_sec = ?, embed_app_id = ?, embed_app_config = ?`,
  [embed_app_sec, embed_app_id, embed_app_config]
);
res.json({ msg: "Updated", success: true });
```

**After:**
```javascript
// Validation added, WHERE id = 1, better response
if (!embed_app_id) {
  return res.json({ success: false, msg: "embed_app_id is required" });
}
if (!embed_app_sec) {
  return res.json({ success: false, msg: "embed_app_sec is required" });
}

await query(
  `UPDATE web_private SET embed_app_sec = ?, embed_app_id = ?, embed_app_config = ? WHERE id = 1`,
  [embed_app_sec, embed_app_id, embed_app_config || ""]
);

res.json({
  success: true,
  msg: "Embed configuration updated successfully",
  data: {
    embed_app_id,
    webhook_url: `${process.env.BACKURI}/api/inbox/embed/webhook`,
  }
});
```

---

### 3. **routes/admin.js** - NEW: `/get_embed_config`

**Added new endpoint for admin panel:**
```javascript
router.get("/get_embed_config", adminValidator, async (req, res) => {
  const [data] = await query(
    `SELECT embed_app_id, embed_app_sec, embed_app_config FROM web_private WHERE id = 1`,
    []
  );

  res.json({
    success: true,
    data: {
      ...data,
      webhook_url: `${process.env.BACKURI}/api/inbox/embed/webhook`,
    }
  });
});
```

---

### 4. **routes/web.js** - `/get_web_pvt`

**Before:**
```javascript
// Returns ALL columns (performance issue)
const [data] = await query(`SELECT * FROM web_private`, []);
```

**After:**
```javascript
// Only returns embed columns
const [data] = await query(
  `SELECT embed_app_id, embed_app_sec, embed_app_config FROM web_private WHERE id = 1`,
  []
);
```

---

## 🧪 Testing API Endpoints

### Test 1: Get Embed Config (Public)
```bash
curl http://localhost:8001/api/web/get_web_pvt
```

**Expected Response:**
```json
{
  "success": true,
  "data": {
    "embed_app_id": "1533489467877260",
    "embed_app_sec": "234729cb8fe33877342539f47ddca33e",
    "embed_app_config": "1631983291575709",
    "webhook_url": "http://localhost:8001/api/inbox/embed/webhook",
    "webhook": {
      "success": true,
      "webhook_url": "http://localhost:8001/api/inbox/embed/webhook"
    }
  }
}
```

---

### Test 2: Get Embed Keys (Authenticated)
```bash
curl -H "Authorization: Bearer YOUR_TOKEN" \
  http://localhost:8001/api/user/get_embed_keys
```

**Expected Response:**
```json
{
  "success": true,
  "data": {
    "embed_app_id": "1533489467877260",
    "embed_app_sec": "234729cb8fe33877342539f47ddca33e",
    "embed_app_config": "1631983291575709",
    "webhook_url": "http://localhost:8001/api/inbox/embed/webhook"
  }
}
```

---

### Test 3: Get Embed Config (Admin)
```bash
curl -H "Authorization: Bearer ADMIN_TOKEN" \
  http://localhost:8001/api/admin/get_embed_config
```

**Expected Response:**
```json
{
  "success": true,
  "data": {
    "embed_app_id": "1533489467877260",
    "embed_app_sec": "234729cb8fe33877342539f47ddca33e",
    "embed_app_config": "1631983291575709",
    "webhook_url": "http://localhost:8001/api/inbox/embed/webhook"
  }
}
```

---

### Test 4: Update Embed Config (Admin)
```bash
curl -X POST \
  -H "Authorization: Bearer ADMIN_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "embed_app_id": "your_app_id",
    "embed_app_sec": "your_app_secret",
    "embed_app_config": "your_app_config"
  }' \
  http://localhost:8001/api/admin/update_embed_config
```

**Expected Response:**
```json
{
  "success": true,
  "msg": "Embed configuration updated successfully",
  "data": {
    "embed_app_id": "your_app_id",
    "webhook_url": "http://localhost:8001/api/inbox/embed/webhook"
  }
}
```

---

## 🐛 Common Issues

### Issue 1: Page masih blank setelah fix

**Solusi:**
1. **Hard refresh** browser: `Ctrl + Shift + R` atau `Ctrl + F5`
2. **Clear browser cache**
3. **Check browser console** (F12) untuk error JavaScript

---

### Issue 2: Error "Embed app is not configured"

**Penyebab:** `embed_app_id` atau `embed_app_sec` NULL di database

**Solusi:**
```sql
-- Check current values
SELECT embed_app_id, embed_app_sec FROM web_private WHERE id = 1;

-- Update with valid values
UPDATE web_private SET 
  embed_app_id = 'your_meta_app_id',
  embed_app_sec = 'your_meta_app_secret',
  embed_app_config = 'your_config'
WHERE id = 1;
```

---

### Issue 3: Error 401 Unauthorized

**Penyebab:** Token tidak valid atau expired

**Solusi:**
1. Login ulang di aplikasi
2. Copy token baru dari localStorage
3. Gunakan token yang valid

---

### Issue 4: Webhook URL salah

**Penyebab:** `BACKURI` atau `FRONTENDURI` tidak diset di `.env`

**Solusi:** Update `.env`:
```env
BACKURI=http://localhost:8001
FRONTENDURI=http://localhost:3000
```

Kemudian restart server.

---

## 📋 Checklist Troubleshooting

- [ ] Server running (`npm start`)
- [ ] Database connected
- [ ] `web_private` table punya kolom embed (`embed_app_id`, `embed_app_sec`, `embed_app_config`)
- [ ] Kolom embed sudah diisi dengan value (bukan NULL)
- [ ] Browser cache sudah di-clear
- [ ] Console browser tidak ada error JavaScript
- [ ] API endpoint return response yang benar (test dengan curl)

---

## 🔄 Setelah Apply Fix

1. **Restart server** (wajib!)
   ```bash
   # Ctrl+C untuk stop
   npm start
   ```

2. **Clear browser cache**
   - Chrome: `Ctrl + Shift + Delete`
   - Atau hard refresh: `Ctrl + Shift + R`

3. **Test endpoint** dengan curl atau browser

4. **Reload embed-config page**

---

**Last Updated:** April 9, 2026
