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

interface SendFacebookMessageTaskOptions {
  token: string;
  to: string;
  message: string;
}

const sendFacebookMessageTask = async (
  options: SendFacebookMessageTaskOptions,
): Promise<void> => {
  const { token, to, message } = options;
  const { pageId, pageAccessToken } = await db
    .selectFrom("FacebookBot")
    .selectAll()
    .where("token", "=", token)
    .executeTakeFirstOrThrow();

  const endpoint = `https://graph.facebook.com/v19.0/${pageId}/messages`;

  const outgoingMessage = {
    recipient: { id: to },
    message: { text: message },
    messaging_type: "RESPONSE",
    access_token: pageAccessToken,
  };

  try {
    const response = await fetch(endpoint, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(outgoingMessage),
    });
    console.log({ response });
  } catch (error) {
    console.error({ error });
    throw error;
  }
};

export default sendFacebookMessageTask;
