class WebMessageSender {
  constructor(whatsappService) {
    this.whatsappService = whatsappService;
  }

  async send({ tenantId, item, metadata }) {
    if (!this.whatsappService) {
      return { success: false, error: 'WhatsApp service not available' };
    }
    if (item.message_type === 'raw' && metadata.payload?.raw) {
      const instance = this.whatsappService.getInstance?.(tenantId);
      const sock = instance?.connection?.getSocket?.(tenantId);
      if (!sock) {
        return { success: false, error: 'WhatsApp not connected' };
      }
      const jid = metadata.payload?.jid || item.phone_number;
      await sock.sendMessage(jid, metadata.payload.raw);
      return { success: true, messageId: null };
    }
    const result = await this.whatsappService.sendMessage(
      tenantId,
      item.phone_number,
      item.content || '',
      metadata.conversationId || null,
      metadata.options || {}
    );
    if (!result?.success) {
      return { success: false, error: result?.error || 'Failed to send message' };
    }
    return { success: true, messageId: result.whatsappMessageId || null };
  }
}

module.exports = { WebMessageSender };
