import { db } from "@link-stack/bridge-common";

interface SendWhatsappMessageTaskOptions {
  token: string;
  to: string;
  message: any;
}

const sendWhatsappMessageTask = async ({
  message,
  to,
  token,
}: SendWhatsappMessageTaskOptions): Promise<void> => {
  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 = { message, phoneNumber: to };
  try {
    const result = await fetch(url, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(params),
    });
    console.log({ result });
  } catch (error) {
    console.error({ error });
    throw new Error("Failed to send message");
  }
};

export default sendWhatsappMessageTask;
