# WhatsApp Cloud API Integration

## Overview
BoonTrack integrates directly with Meta's official **WhatsApp Cloud API** (Graph API), providing enterprise-grade conversational commerce rails. The architecture emphasizes strict compliance, zero-ban operational reliability, deterministic message processing, idempotent webhook ingestion, and seamless human agent collaboration.

---

## 1. Official WhatsApp Cloud API Rail

Unlike unofficial third-party solutions that rely on browser emulation (Puppeteer/web-socket reverse engineering), BoonTrack routes all messaging traffic through Meta's verified Cloud API infrastructure.

### Operational Advantages
- **Zero-Ban Risk**: Full compliance with Meta Business and Commerce Policies; eliminates the risk of phone number blacklisting.
- **High Throughput**: Capable of processing up to 80 to 500 messages per second per phone number ID based on Meta Messaging Tier (Tier 1K to Unlimited).
- **Template Message (HSM) Integrity**: Automated transactional notifications (Order Placed, Dynamic QRIS Bill, Payment Success, Resi Ekspedisi) utilize pre-approved Highly Structured Message (HSM) templates with variable parameter binding.
- **Enterprise SLA**: Direct Cloud API availability with guaranteed delivery receipts (`sent`, `delivered`, `read`).

---

## 2. Idempotent Webhook Processing via `wamid` Deduplication

Meta's webhook infrastructure operates on an **at-least-once delivery model**. Transient network timeouts, latency spikes, or delayed HTTP acknowledgments frequently cause Meta to resend identical webhook payloads.

To prevent duplicate database records, repeat automated replies, or duplicate order generation, BoonTrack implements a deterministic deduplication guard at the edge of the webhook handler using the unique WhatsApp Message ID (`wamid`).

```mermaid
sequenceDiagram
    autonumber
    participant Meta as Meta Webhook Dispatcher
    participant API as FastAPI Webhook Handler
    participant Redis as Redis Cache & Lock
    participant Queue as Redis Task Stream
    participant Worker as Message Processing Worker

    Meta->>API: POST /api/v1/whatsapp/webhook (Payload + X-Hub-Signature-256)
    Note over API: 1. Verifikasi HMAC-SHA256 Signature
    Note over API: 2. Ekstrak wamid unik dari payload.entry[].changes[].value.messages[]

    API->>Redis: SET wa:dedup:{wamid} 1 EX 86400 NX
    alt Key Sudah Ada (Duplicate Delivery)
        Redis-->>API: Nilai NULL / 0 (Key already exists)
        API-->>Meta: 200 OK (Acknowledge segera tanpa re-proses)
    else Key Baru (First-time Processing)
        Redis-->>API: OK (Key tersimpan, TTL 24 Jam)
        API->>Queue: XADD wa:events (wamid, raw_payload, timestamp)
        API-->>Meta: 200 OK (Fast Acknowledgment < 50ms)
    end

    Queue->>Worker: Asynchronous Event Consumption
    Worker->>Worker: Evaluasi Alur Pesan / Bot / Takeover
```

### Mekanisme Deduplikasi Redis
```python
# Atomic check-and-set menggunakan Redis NX (Set if Not Exists)
is_new = await redis_client.set(
    name=f"wa:dedup:{wamid}",
    value=1,
    ex=86400,  # TTL 24 jam untuk menampung window retry Meta
    nx=True
)

if not is_new:
    # Event duplikat telah diproses sebelumnya; kembalikan 200 OK untuk menghentikan retry Meta
    return {"status": "already_processed", "wamid": wamid}
```

---

## 3. Sliding Window Customer Support (CS) Takeover Engine

Dalam operasional conversational commerce, otomatisasi bot harus dapat dialihkan ke agen manusia (*human takeover*) secara halus tanpa interupsi bot yang saling bertabrakan.

### Mekanisme Kerja Sliding Window Takeover
1. **Pemicu Takeover**:
   - Pelanggan mengetik kata kunci eskalasi (contoh: *"bicara dengan admin"*, *"butuh bantuan manusia"*).
   - Atau agen CS mengirimkan pesan manual pertama kali melalui dashboard BoonTrack.
2. **Aktivasi State di Redis**:
   - Sistem mencatat kunci state takeover: `wa:takeover:{tenant_id}:{customer_phone}` dengan nilai status `ACTIVE` dan TTL dinamis (default: 1.800 detik / 30 menit).
3. **Sliding Window Extension**:
   - Setiap kali terjadi interaksi baru (pesan masuk dari pelanggan atau balasan dari agen) selama sesi berlangsung, timer TTL diperpanjang secara otomatis:
     ```python
     await redis_client.expire(f"wa:takeover:{tenant_id}:{customer_phone}", 1800)
     ```
4. **Pencegahan Bot Bentrok**:
   - Sebelum mengeksekusi logika bot otomatis atau AI assistant, sistem selalu mengecek keberadaan kunci takeover. Jika kunci aktif, bot dilewati (*bypass*) dan pesan hanya diarahkan ke inbox dashboard CS.
5. **Auto-Release**:
   - Jika percakapan tidak aktif selama lebih dari 30 menit, kunci di Redis akan kedaluwarsa (*expire*) dengan sendirinya, mengembalikan mode percakapan ke otomatisasi bot standar.
