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

const fetchSignalMessagesTask = async (): Promise<void> => {
  const worker = await getWorkerUtils();
  const rows = await db.selectFrom("SignalBot").selectAll().execute();
  const config = new Configuration({
    basePath: process.env.BRIDGE_SIGNAL_URL,
  });
  const messagesClient = new MessagesApi(config);

  for (const row of rows) {
    const { id, phoneNumber: number } = row;
    const messages = await messagesClient.v1ReceiveNumberGet({ number });

    for (const msg of messages) {
      const { envelope } = msg as any;
      const { source, sourceUuid, dataMessage } = envelope;
      const messageID = sourceUuid;
      const message = dataMessage?.message;
      const timestamp = new Date(dataMessage?.timestamp);
      if (source !== number && message) {
        await worker.addJob("signal/receive-signal-message", {
          token: id,
          sender: source,
          messageID,
          message,
          timestamp: timestamp.toISOString(),
        });
      }
    }
  }
};

export default fetchSignalMessagesTask;
