# Examples

### Complete Express.js Bot

```typescript
import express from 'express';
import { createWhatsAppHandler } from './whatsapp-handler';

const app = express();
app.use(express.json());

const whatsapp = createWhatsAppHandler({
  token: process.env.WHATSAPP_TOKEN!,
  phoneNumberId: process.env.WHATSAPP_PHONE_NUMBER_ID!,
  webhookVerifyToken: process.env.WHATSAPP_WEBHOOK_VERIFY_TOKEN!
});

// Set up handlers
whatsapp.setWebhookHandlers({
  onMessage: async (message, metadata) => {
    const text = message.text?.body;
    const from = metadata.waId!;

    if (!text) return;

    // Echo bot
    if (text.toLowerCase() === 'hello') {
      await whatsapp.sendMessage(from, 'Hello! How can I help you?');
    }
    else if (text.toLowerCase() === 'help') {
      await whatsapp.sendMessage(from, 
        'Available commands:\n- hello\n- help\n- history'
      );
    }
    else if (text.toLowerCase() === 'history') {
      const history = await whatsapp.getConversationHistory(from, 5);
      await whatsapp.sendMessage(from, 
        `You have ${history.length} recent messages`
      );
    }
    else {
      await whatsapp.sendMessage(from, `You said: ${text}`);
    }
  },

  onVoice: async (voice, metadata) => {
    const from = metadata.waId!;
    await whatsapp.sendMessage(from, 'Thanks for the voice message!');
  },

  onLocation: async (location, metadata) => {
    const from = metadata.waId!;
    const { latitude, longitude } = location.location!;
    await whatsapp.sendMessage(from, 
      `Got your location: ${latitude}, ${longitude}`
    );
  }
});

// Webhook endpoint
app.use('/webhook', whatsapp.expressMiddleware());

// Start server
app.listen(3000, () => {
  console.log('Bot running on port 3000');
});
```

### Conversation Flow Example

```typescript
whatsapp.setWebhookHandlers({
  onMessage: async (message, metadata) => {
    const text = message.text?.body;
    const from = metadata.waId!;
    
    // Get conversation state
    const state = whatsapp.getConversationState(from);
    const step = state?.currentStep || 'start';

    switch (step) {
      case 'start':
        await whatsapp.sendMessage(from, 'What\'s your name?');
        whatsapp.updateConversationContext(from, { currentStep: 'name' });
        break;

      case 'name':
        whatsapp.updateConversationContext(from, { 
          currentStep: 'email',
          userName: text 
        });
        await whatsapp.sendMessage(from, `Nice to meet you, ${text}! What\'s your email?`);
        break;

      case 'email':
        const context = whatsapp.getConversationState(from)?.context;
        whatsapp.updateConversationContext(from, { 
          currentStep: 'completed',
          userEmail: text 
        });
        await whatsapp.sendMessage(from, 
          `Thanks ${context?.userName}! We've saved your email: ${text}`
        );
        break;

      case 'completed':
        await whatsapp.sendMessage(from, 
          'Your registration is complete! Type "restart" to start over.'
        );
        if (text?.toLowerCase() === 'restart') {
          whatsapp.updateConversationContext(from, { currentStep: 'start' });
        }
        break;
    }
  }
});
```

### Message Queue Example

```typescript
// Send bulk messages with queue
const recipients = ['1111111111', '2222222222', '3333333333'];

for (const recipient of recipients) {
  await whatsapp.sendMessage(recipient, 'Bulk message', {
    queueIfBusy: true,
    priority: 0
  });
}

// Listen for queue events
whatsapp.on('queuedMessageSent', (data) => {
  console.log(`Queued message sent: ${data.messageId}`);
});

whatsapp.on('queuedMessageFailed', (data) => {
  console.error(`Queued message failed after ${data.attempts} attempts`);
});

// Monitor queue
setInterval(() => {
  const stats = whatsapp.getQueueStats();
  console.log(`Queue: ${stats.size}/${stats.maxSize} (${stats.usagePercentage.toFixed(2)}%)`);
}, 5000);
```

---