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

interface ReceiveFacebookMessageTaskOptions {
  message: any;
}

const receiveFacebookMessageTask = async ({
  message,
}: ReceiveFacebookMessageTaskOptions): Promise<void> => {
  const worker = await getWorkerUtils();

  for (const entry of message.entry) {
    for (const messaging of entry.messaging) {
      const pageId = messaging.recipient.id;
      const row = await db
        .selectFrom("FacebookBot")
        .selectAll()
        .where("pageId", "=", pageId)
        .executeTakeFirstOrThrow();
      const backendId = row.id;
      const payload = {
        to: pageId,
        from: messaging.sender.id,
        sent_at: new Date(messaging.timestamp).toISOString(),
        message: messaging.message.text,
        message_id: messaging.message.mid,
      };

      await worker.addJob("common/notify-webhooks", { backendId, payload });
    }
  }
};

export default receiveFacebookMessageTask;
