import { db } from "@link-stack/bridge-common"; import { createLogger } from "@link-stack/logger"; const logger = createLogger("bridge-worker-send-whatsapp-message"); interface SendWhatsappMessageTaskOptions { token: string; to: string; message: any; attachments?: Array<{ data: string; filename: string; mime_type: string; }>; } const sendWhatsappMessageTask = async ({ message, to, token, attachments, }: SendWhatsappMessageTaskOptions): Promise => { const bot = await db .selectFrom("WhatsappBot") .selectAll() .where("token", "=", token) .executeTakeFirstOrThrow(); const url = `${process.env.BRIDGE_WHATSAPP_URL}/api/bots/${bot.id}/send`; const params: any = { message, phoneNumber: to }; if (attachments && attachments.length > 0) { params.attachments = attachments; logger.debug( { attachmentCount: attachments.length, attachmentNames: attachments.map((att) => att.filename), }, "Sending WhatsApp message with attachments", ); } try { const result = await fetch(url, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(params), }); if (!result.ok) { const errorText = await result.text(); logger.error( { status: result.status, errorText, url, }, "WhatsApp send failed", ); throw new Error(`Failed to send message: ${result.status}`); } } catch (error) { logger.error({ error }); throw new Error("Failed to send message"); } }; export default sendWhatsappMessageTask;