import { createHealthServer } from "@hereconnect/lib-service-health-checkserver";
import { createBot, setupCommands } from "./bot";
import { createServiceChangesMessagesDb } from "./services/serviceChangesMessagesDb";
import { createServiceChangesTgUpdatesDb } from "./services/serviceChangesTgUpdatesDb";
import { iterateMessagesChanges } from "./services/iterateMessagesChanges";
import { setupWebHook } from "./services/setupWebHook";
import { env } from "./config/env";

const abortController = new AbortController();

(async () => {
  const healthServer = createHealthServer(abortController);
  const bot = createBot({ abortController });
  const messagesChanges = await createServiceChangesMessagesDb({
    abortController,
  });

  const tgUpdatesChanges =
    env.BOT_USE_CHANGES_DB_UPDATES &&
    (await createServiceChangesTgUpdatesDb({
      abortController,
    }));

  process.on("SIGINT", async () => {
    messagesChanges.changesStream.stop();
    if (tgUpdatesChanges) {
      tgUpdatesChanges.changesStream.stop();
    }
    bot.stop();
  });

  await healthServer.start();

  await bot.init();

  await setupWebHook(bot);
  await setupCommands(bot);

  // outgoing messages
  iterateMessagesChanges({ bot, ...messagesChanges });

  console.log("Бот запущен!");

  // incoming messages
  if (tgUpdatesChanges) {
    for await (const change of tgUpdatesChanges.changesStream) {
      tgUpdatesChanges.serviceSeqTracker.checkNextSeq(change.seq);
      if (change.doc) {
        await bot.handleUpdate(change.doc.data);
      }
      await tgUpdatesChanges.serviceSeqTracker.saveSeq(change.seq);
    }
  } else {
    await bot.start();
  }
})();
