# WhatsApp Business API - Quick Reference

## 🚀 Quick Start

### 1. Get Credentials from Meta
- Access Token
- Phone Number ID
- Business Account ID
- Webhook Verify Token

### 2. Set Environment Variables
```bash
WHATSAPP_ACCESS_TOKEN=EAAxxxxx
WHATSAPP_PHONE_NUMBER_ID=123456789
WHATSAPP_BUSINESS_ACCOUNT_ID=987654321
WHATSAPP_WEBHOOK_VERIFY_TOKEN=random-secret
ENABLE_WHATSAPP_NOTIFICATIONS=true
```

### 3. Run Migration
```bash
cd services/notification
alembic upgrade head
```

### 4. Deploy
```bash
kubectl apply -f kubernetes/notification-deployment.yaml
```

---

## 💰 Pricing at a Glance

| Tier | Conversations/Month | Cost |
|------|---------------------|------|
| Free | First 1,000 | €0.00 |
| Paid | After 1,000 | €0.01-0.10 each |

**Conversation** = 24-hour window, multiple messages = 1 charge

---

## 📋 Template Format

**Name**: `po_notification`

**Message**:
```
Hola {{1}}, has recibido una nueva orden de compra {{2}} por un total de {{3}}.
```

**Parameters**:
1. Supplier name
2. PO number
3. Total amount

**Example**:
```
Hola Proveedor ABC, has recibido una nueva orden de compra PO-2024-001 por un total de €1,250.00.
```

---

## 🔗 Important URLs

| Resource | URL |
|----------|-----|
| Meta Business Suite | https://business.facebook.com/ |
| Developers Console | https://developers.facebook.com/ |
| Template Manager | https://business.facebook.com/wa/manage/message-templates/ |
| API Docs | https://developers.facebook.com/docs/whatsapp/cloud-api |
| Status Page | https://developers.facebook.com/status |

---

## 🛠️ Common Commands

### Check Migration Status
```bash
kubectl exec -it deployment/notification-service -- alembic current
```

### View WhatsApp Logs
```bash
kubectl logs -f deployment/notification-service -n bakery-ia | grep WhatsApp
```

### Query Messages
```sql
SELECT
  id, recipient_phone, status, template_name,
  sent_at, delivered_at, error_message
FROM whatsapp_messages
ORDER BY created_at DESC
LIMIT 10;
```

### Test Webhook
```bash
curl -X GET "https://your-domain.com/api/v1/whatsapp/webhook?hub.mode=subscribe&hub.verify_token=YOUR_TOKEN&hub.challenge=test123"
```

---

## 🔍 Troubleshooting

| Issue | Solution |
|-------|----------|
| Webhook verification failed | Check WHATSAPP_WEBHOOK_VERIFY_TOKEN matches Meta config |
| Template not found | Ensure template is APPROVED in Meta Business Suite |
| Access token expired | Generate permanent system user token |
| Message failed | Check phone format: +34612345678 (E.164) |
| No webhook events | Verify webhook URL is publicly accessible |

---

## 📊 Message Status Flow

```
PENDING → SENT → DELIVERED → READ
                    ↓
                 FAILED
```

### Status Meanings
- **PENDING**: Created in DB, not yet sent
- **SENT**: Accepted by WhatsApp API
- **DELIVERED**: Delivered to recipient's device
- **READ**: Recipient opened the message
- **FAILED**: Delivery failed (check error_message)

---

## 📞 Phone Number Format

✅ **Correct**: `+34612345678`
❌ **Incorrect**:
- `612345678` (missing country code)
- `34612345678` (missing +)
- `+34 612 34 56 78` (has spaces)

---

## 📝 Required Template Info

| Field | Value |
|-------|-------|
| Name | `po_notification` |
| Category | UTILITY |
| Language | Spanish (es) |
| Status | APPROVED (required!) |
| Parameters | 3 (supplier, PO #, amount) |

---

## 🔐 Security Checklist

- [ ] Access tokens stored in Kubernetes secrets
- [ ] Webhook verify token is random and secure
- [ ] HTTPS enabled for webhook URL
- [ ] API tokens never committed to git
- [ ] Environment-specific tokens (dev/prod)

---

## 📈 Monitoring

### Key Metrics to Track
- Messages sent per day
- Delivery rate (delivered/sent)
- Failed message count
- Response time
- Conversation usage vs free tier

### Where to Monitor
- **Meta Business Suite** → Analytics
- **Database**: `whatsapp_messages` table
- **Logs**: Kubernetes pod logs
- **Prometheus**: Custom metrics

---

## 🆘 Support Contacts

- **Meta Support**: https://www.facebook.com/business/help
- **Developer Community**: https://developers.facebook.com/community
- **Internal Docs**: [WHATSAPP_SETUP_GUIDE.md](WHATSAPP_SETUP_GUIDE.md)

---

## ✅ Pre-Launch Checklist

- [ ] Meta Business Account verified
- [ ] WhatsApp phone number registered
- [ ] Access token is permanent (not 24h temp)
- [ ] Template approved (status = APPROVED)
- [ ] Webhook configured and verified
- [ ] Environment variables set in production
- [ ] Database migration completed
- [ ] Test message sent successfully
- [ ] Webhook events received
- [ ] Supplier phone numbers formatted correctly
- [ ] Monitoring configured
- [ ] Team trained on template management
