# Facebook Messenger Setup Guide

Step-by-step guide to set up Facebook Messenger Platform integration.

## Prerequisites

- Facebook account
- Facebook Page (already created)
- Developer account on Meta for Developers
- HTTPS endpoint for webhook (production)
- ngrok (for local testing)

## Step 1: Create Facebook App

### 1.1 Access Meta for Developers

1. Go to [developers.facebook.com](https://developers.facebook.com/)
2. Click "My Apps" → "Create App"
3. Select use case: **"Other"**
4. Select app type: **"Business"**

### 1.2 App Configuration

- **App Name**: e.g., "My Shop Chatbot"
- **App Contact Email**: your email
- **Business Account**: Select or create

> **Note**: Copy your **App ID** and **App Secret** (Settings → Basic). You'll need these later.

---

## Step 2: Add Messenger Product

### 2.1 Add Messenger

1. In your app dashboard, click **"Add Product"**
2. Find **"Messenger"** and click **"Set Up"**

### 2.2 Generate Page Access Token

1. In Messenger Settings, scroll to **"Access Tokens"**
2. Click **"Add or Remove Pages"**
3. Select your Facebook Page
4. Click **"Generate Token"**
5. **Copy and save** the Page Access Token

```bash
# Save to .env file
FACEBOOK_PAGE_ACCESS_TOKEN="EAAxxxxxxxxxx..."
```

> **Warning**: Page Access Token is sensitive! Never commit to Git or expose publicly.

---

## Step 3: Configure Webhook

### 3.1 Deploy Service or Use ngrok

**Option A: Local Development with ngrok**

```bash
# Install ngrok
brew install ngrok  # macOS

# Run service locally
dotnet run --project src/MktFacebookService.API

# Expose local service
ngrok http 5000

# Copy HTTPS URL, e.g., https://abc123.ngrok.io
```

**Option B: Production Deployment**

Deploy service to production server with HTTPS enabled.

### 3.2 Add Webhook in Facebook App

1. Go to Messenger → Settings → **"Webhooks"**
2. Click **"Add Callback URL"**
3. Enter:
   - **Callback URL**: `https://your-domain.com/api/v1/webhooks/facebook`
   - **Verify Token**: Create a random string (e.g., `my_verify_token_12345`)
4. Click **"Verify and Save"**

```bash
# Save to .env
FACEBOOK_VERIFY_TOKEN="my_verify_token_12345"
```

> **Important**: Verify Token must match the value in service configuration!

### 3.3 Subscribe to Webhook Events

After webhook is verified, select fields:

- [x] **messages** - Receive customer messages
- [x] **messaging_postbacks** - Receive button clicks
- [x] **message_reads** - Receive read receipts (optional)
- [x] **messaging_optins** - Receive opt-in events

Click **"Subscribe"**.

---

## Step 4: Test Integration

### 4.1 Send Test Message

1. Go to your Facebook Page
2. Click **"Send Message"** (as a user, not admin)
3. Type: `Hello`
4. Check service logs for incoming webhook event

**Expected Log**:
```
[INFO] Received message event from user: 1234567890
[INFO] Processing incoming message: "Hello"
[INFO] Sending response via Facebook Messenger
```

### 4.2 Test Get Started Button

Configure Get Started button to trigger welcome flow.

**cURL Command**:
```bash
curl -X POST "https://graph.facebook.com/v21.0/me/messenger_profile" \
  -H "Content-Type: application/json" \
  -d '{
    "get_started": {
      "payload": "GET_STARTED"
    }
  }' \
  -d "access_token=YOUR_PAGE_ACCESS_TOKEN"
```

---

## Environment Variables Summary

```bash
# Facebook App Configuration
FACEBOOK_APP_ID="123456789012345"
FACEBOOK_APP_SECRET="abcdef1234567890abcdef1234567890"
FACEBOOK_VERIFY_TOKEN="my_verify_token_12345"

# Facebook Page Access Token
FACEBOOK_PAGE_ACCESS_TOKEN="EAAxxxxxxxxxx..."

# Facebook API Version
FACEBOOK_API_VERSION="v21.0"
```

---

## Troubleshooting

### Issue 1: Webhook Verification Failed

**Problem**: 
```
The URL couldn't be validated. Callback verification failed...
```

**Solution**:
1. Check service is running and accessible via HTTPS
2. Verify `FACEBOOK_VERIFY_TOKEN` matches exactly
3. Check logs for webhook GET request
4. Ensure returning hub.challenge as plain text (not JSON)

### Issue 2: Not Receiving Messages

**Problem**: Service not receiving messages

**Solution**:
1. Verify webhook subscriptions are active (messages, messaging_postbacks)
2. Check Page Access Token hasn't expired
3. Test webhook manually with curl

### Issue 3: Cannot Send Messages

**Problem**: 
```
(#200) This user can't receive messages from this bot
```

**Solution**:
- User must send a message first (GDPR compliance)
- Or user must opt-in via checkbox plugin
- Page Access Token must have `pages_messaging` permission

---

## Testing Checklist

- [ ] Facebook App created and Messenger product added
- [ ] Page Access Token generated and saved
- [ ] Webhook configured and verified
- [ ] Webhook events subscribed (messages, postbacks)
- [ ] Test message sent and received successfully
- [ ] Bot response sent back to user
- [ ] Get Started button triggers welcome flow
- [ ] Signature verification working

---

## Resources

### Official Facebook Documentation
- [Messenger Platform Overview](https://developers.facebook.com/docs/messenger-platform/)
- [Webhooks Reference](https://developers.facebook.com/docs/messenger-platform/webhooks)
- [Send API Reference](https://developers.facebook.com/docs/messenger-platform/send-messages)

### Tools
- [Facebook Graph API Explorer](https://developers.facebook.com/tools/explorer/)
- [ngrok](https://ngrok.com/) - Local HTTPS tunnel

### Internal Docs
- [API Documentation](./API.md)
- [Architecture Documentation](./ARCHITECTURE.md)
- [AI Chatbot Configuration](./AI_CHATBOT.md)
