import { db } from "@link-stack/bridge-common";
import * as signalApi from "@link-stack/signal-api";
const { Configuration, MessagesApi } = signalApi;

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

const sendSignalMessageTask = async ({
  token,
  to,
  message,
}: SendSignalMessageTaskOptions): Promise<void> => {
  console.log({ token, to });
  const bot = await db
    .selectFrom("SignalBot")
    .selectAll()
    .where("token", "=", token)
    .executeTakeFirstOrThrow();

  const { phoneNumber: number } = bot;
  const config = new Configuration({
    basePath: process.env.BRIDGE_SIGNAL_URL,
  });
  const messagesClient = new MessagesApi(config);

  try {
    const response = await messagesClient.v2SendPost({
      data: {
        number,
        recipients: [to],
        message,
      },
    });
    console.log({ response });
  } catch (error) {
    console.error({ error });
    throw error;
  }
};

export default sendSignalMessageTask;
